Java – Check if JToggleButton is Pressed and Disable It


I have an array of JTogglebuttons and a JButton, when the JButton is pressed it initiates a loop that iterates through all the JTogglebuttons to see if it is pressed, and if it is it should make it disable/unclickable

Here is the snippet of code that is an issue

Public void actionPerformed(ActionEvent e){
        Object pressed = e.getSource(); 
        if (pressed == btnPurchase) {
            for(int row = 0; row<8 ; row++){
                for(int column = 0; column < 4; column++) {     
                    if (seat[row][column].isPressed()) {

I get this error

cannot find symbol
symbol  : method isPressed()
location: class javax.swing.JToggleButton
                    if (seat[row][column].isPressed()) {

If i use .isSelected

i get

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at cinemaManager.actionPerformed(
    at javax.swing.AbstractButton.fireActionPerformed(
    at javax.swing.AbstractButton$Handler.actionPerformed(
    at javax.swing.DefaultButtonModel.fireActionPerformed(
    at javax.swing.DefaultButtonModel.setPressed(
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(
    at java.awt.Component.processMouseEvent(

Best Solution

look for ButtonModel, thats returns expected method, including isSelected

import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class JToggleButtonChangeListener {

    public static void main(String args[]) {
        JFrame frame = new JFrame("Selecting Toggle");
        final JToggleButton toggleButton = new JToggleButton("Selecting Toggle / Deselacting Toggle");
        toggleButton.addChangeListener(new ChangeListener() {

            public void stateChanged(ChangeEvent e) {
                ButtonModel buttonModel = toggleButton.getModel();
                boolean armed = buttonModel.isArmed();
                boolean pressed = buttonModel.isPressed();
                boolean selected = buttonModel.isSelected();
                System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
        frame.setLocation(150, 150);

notice: change of Backgroung not working for all of Look and Feels

Related Question