import java.awt.event.*; import javax.swing.*; import java.awt.*; public class FirstButtonFrame extends JFrame implements ActionListener { private JPanel panel; /* the constructor of this class */ public FirstButtonFrame() { /* JFrame methods */ setTitle("FirstButtonFrame"); setLocation(100, 50); setSize(250, 100); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); panel = new JPanel(); JButton butt = new JButton("White"); panel.add(butt); butt.addActionListener(this); butt.setActionCommand("Button 1"); butt = new JButton("Cyan"); panel.add(butt); butt.addActionListener(this); butt.setActionCommand("Button 2"); Container pane = getContentPane(); pane.add(panel, "North"); } public void actionPerformed(ActionEvent evt) { String cmd = evt.getActionCommand(); System.out.print(cmd + "\t"); // writes cmd and a tab if (cmd.equals("Button 1")) { doButtonOne(); } else if (cmd.equals("Button 2")) { doButtonTwo(); } else { System.out.println("Any error."); } } private void doButtonOne() { System.out.println("is \"White\"."); panel.setBackground(Color.white); } private void doButtonTwo() { System.out.println("is \"Cyan\"."); panel.setBackground(Color.cyan); } /* merely the driver */ public static void main(String[] args) { FirstButtonFrame frame = new FirstButtonFrame(); frame.show(); } }