Birdman
Birdman

Reputation: 5434

jbutton.setEnabled(false) doesn't disable button input

I have the following two classes:

#1

public class LobbyView extends JPanel
{       

    private final JButton sendGameRequestButton = new JButton();

    public JButton getSendGameRequestButton()
    {
        return sendGameRequestButton;
    }

    LobbyView()
    {
        sendGameRequestButton.setPreferredSize(new Dimension(15, 20));
        sendGameRequestButton.setText("Send game request");
        sendGameRequestButton.addMouseListener(new LobbyListener(this));
        sendGameRequestButton.setEnabled(false);
    }
}

#2

public class LobbyListener implements MouseListener
{
    LobbyView lobbyView;

public LobbyListener(LobbyView sentLobbyView)
{
    lobbyView = sentLobbyView;
}

@Override
public void mouseClicked(MouseEvent e)
{
    if (e.getButton() == 1)
    {      
        if (e.getSource() == lobbyView.getSendGameRequestButton())
        {
            System.out.println("You pushed the disabled button");
        }
    }
}

Even though I disabled the JButton in the LobbyView constructor, I can still click it and get the message "You pushed the disabled button".

Does component.setEnabled(false) actually DISABLE a component, or just gray it out to make it LOOK disabled?

Upvotes: 1

Views: 9581

Answers (1)

camickr
camickr

Reputation: 324207

Even though I disabled the JButton in the LobbyView constructor, I can still click it

That is correct. You should NOT be using a MouseListner. The MouseListener works independent of the state of the button.

Instead you should be using an ActionListener. Read the section from the Swing tutorial on How to Use Buttons for more information. Or there is also a section on How to Write an Action Listener.

Upvotes: 6

Related Questions