How to add ChangeListener to JToggleButton?

Here is how to add ChangeListener to JToggleButton. In this example, we are going to make the JPanel semi transparent when the JToggleButton is selected and fully transparent when it is deselected. You will also learn (if you haven't), how to set background image in JFrame in this post. Here is the full code, with helpful commentaries.

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class ChangeListenerForJToggleButton extends JFrame
{
JToggleButton jt;
JPanel jp;
GridBagLayout g=new GridBagLayout();

public ChangeListenerForJToggleButton()
{
createAndShowGUI();
}

private void createAndShowGUI()
{
// Set frame properties
setTitle("ChangeListener Demo");

// Set a background image
setContentPane(new JLabel(new ImageIcon("E:\\Wallpapers\\abstract triangle.jpg")));
setLayout(g);
setDefaultCloseOperation(EXIT_ON_CLOSE);

// Create a JPanel
jp=new JPanel();

// Set gridbaglayout
jp.setLayout(g);

// Make it quite big
jp.setPreferredSize(new Dimension(250,250));

// Create JToggleButton
jt=new JToggleButton("Transparent");
jt.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent ce)
{
// Set a background, semi transprent if selected
// fully transparent if not selected
jp.setBackground(new Color(0,0,0,jt.isSelected()?40:0));

// update the ui, so that you can see the effect without
// updating the jframe manually
SwingUtilities.updateComponentTreeUI(getRootPane());
}
});

// Add JToggleButton to jp
jp.add(jt);

// Add jp to jframe
add(jp);

setSize(400,400);
setVisible(true);
}

public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new ChangeListenerForJToggleButton();
}
});
}
}

If you like this post, feel free to share it. You might also like, using serialization on JToggleButton

No comments: