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()

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

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

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

// Set gridbaglayout

// 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

// Add JToggleButton to jp

// Add jp to jframe


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

Posted by at on

Tags: Swing Event Handling,