Searching...
Sunday, June 1, 2014

Toggle Button

June 01, 2014
An interesting version of the JButton is the JToggleButton. When you press a ToggleButton it stays on until you switch it off again. Because of this, it uses a different listener to the one we use for a JButton as it maintains a state of 'Selected' or 'Deselected'.   ToggleButton.java
package java9r.blogspot.com;

import javax.swing.*;
import java.awt.Color;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class ToggleButton 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.
        ToggleButton demo = new ToggleButton();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 350);
        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();
            }
        });
    }
}
Output

0 comments:

Post a Comment

ads2