package class7_3_RemoteControl_start2; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; /** * The remote control unit which controls the world * @author hornick * */ public class ControlPanelUI extends JFrame { private ControlPanelListener eventListener; // UI event listener private Robot robot; private Car car; private JTextField result; public ControlPanelUI( Car car, Robot robot ) { this.robot = robot; this.car = car; // create the containing window and set its size etc setTitle("X10 Controller"); setSize(200, 300); setLocation(400, 400); setResizable(false); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); eventListener = new ControlPanelListener(); // Retrieves the window's contentPane and sets the background color Container contentPane = getContentPane(); contentPane.setBackground(Color.BLACK); JPanel jp = new JPanel(); FlowLayout fl = new FlowLayout(); jp.setLayout(fl); contentPane.add(jp); // create the command buttons String[] commands = {"Clean", "Scrub", "Start", "Stop", "Undo"}; for( String action: commands ) { JButton cb = new JButton(action); cb.setPreferredSize(new Dimension(150, 25)); cb.setActionCommand(action); jp.add(cb); cb.addActionListener(eventListener); } result = new JTextField(""); result.setPreferredSize(new Dimension(200, 25)); jp.add(result); contentPane.validate(); contentPane.repaint(); } /** * handle the invocation of various commands * @param action String saying which action was performed. */ private void handleCommand( String action ) { boolean status = true; // determine what to do if( action.equals("Clean") ) { robot.tidy(); } else if( action.equals("Scrub") ) { robot.scrub(); } else if( action.equals("Start") ) { car.startEngine(); } else if( action.equals("Stop") ) { car.stopEngine(); } else { // undo button was pressed status = false; } if( status ) { // update the status of executing the commands result.setText("command OK"); } else { result.setText("command failed"); } } /** * This is a nested inner class that handles events * for the ControlPanel * @author hornick */ private class ControlPanelListener implements ActionListener { /** * Constructor; does nothing useful */ private ControlPanelListener() { } /** * ActionListener event handler for this class * @param event - the ActionEvent object that caused the event */ public void actionPerformed(ActionEvent event) { String action = event.getActionCommand(); handleCommand(action); } } // end of ControlPanel inner class }