import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.ImageIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; /** * ButtonDemo.java * Jeff Ondich, 2/25/08 * * Simplified significantly from * http://java.sun.com/docs/books/tutorial/uiswing/examples/components/ButtonDemoProject/src/components/ButtonDemo.java * * Go to that URL for a much more detailed demonstration * of JButton capabilities. */ public class ButtonDemo extends JPanel implements ActionListener { protected JButton button; public ButtonDemo() { button = new JButton("Click me"); button.setActionCommand("ambivalent_button_clicked"); button.addActionListener(this); //Add button to this container, using the default FlowLayout. add(button); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("ambivalent_button_clicked")) { String label = button.getText(); if (label.equals("Click me")) button.setText("Don't click me"); else button.setText("Click me"); } } /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("Ambivalent Button Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. ButtonDemo newContentPane = new ButtonDemo(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }