| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import javax.swing.*; import java.awt.Color; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class ToggleButtonExample implements ItemListener{ // Definition of global values and items that are part of the GUI. JToggleButton toggleButton; JPanel totalGUI; public JPanel createContentPane (){ // We create a bottom JPanel to place everything on. totalGUI = new JPanel(); totalGUI.setBackground(Color.red); totalGUI.setLayout(null); toggleButton = new JToggleButton("Off"); toggleButton.setLocation(75,10); toggleButton.setSize(100,100); toggleButton.addItemListener(this); totalGUI.add(toggleButton); totalGUI.setOpaque(true); return totalGUI; } // This is the new itemStateChanged Method. // It catches any events with an ItemListener attached. // Using an if statement, we can determine if the button is now selected or deselected // after the action and perform changes to the GUI accordingly. public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED) { toggleButton.setText("On!"); totalGUI.setBackground(Color.green); } else { toggleButton.setText("Off"); totalGUI.setBackground(Color.red); } } private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("[=] JToggleButton [=]"); //Create and set up the content pane. ToggleButtonExample demo = new ToggleButtonExample(); frame.setContentPane(demo.createContentPane()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(250, 150); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } |
| 1 2 3 4 5 6 | import javax.swing.*; import java.awt.Color; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; public class ToggleButtonExample implements ItemListener{ |
| 20 21 22 23 24 | toggleButton = new JToggleButton("Off"); toggleButton.setLocation(75,10); toggleButton.setSize(100,100); toggleButton.addItemListener(this); totalGUI.add(toggleButton); |
| 35 36 37 38 39 40 41 42 43 44 45 46 | public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED) { toggleButton.setText("On!"); totalGUI.setBackground(Color.green); } else { toggleButton.setText("Off"); totalGUI.setBackground(Color.red); } } |
