简体   繁体   English

jbutton.setEnabled(false)不禁用按钮输入

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

I have the following two classes: 我有以下两节课:

#1 #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 #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 ". 即使我在LobbyView构造函数中禁用了JButton,我仍然可以单击它并得到消息“ 您按下了禁用的按钮 ”。

Does component.setEnabled(false) actually DISABLE a component, or just gray it out to make it LOOK disabled? component.setEnabled(false)是否实际上禁用了某个组件,或者只是将其涂成灰色以使其被禁用?

Even though I disabled the JButton in the LobbyView constructor, I can still click it 即使我在LobbyView构造函数中禁用了JButton,我仍然可以单击它

That is correct. 那是对的。 You should NOT be using a MouseListner. 您不应该使用MouseListner。 The MouseListener works independent of the state of the button. MouseListener的工作独立于按钮的状态。

Instead you should be using an ActionListener . 相反,您应该使用ActionListener Read the section from the Swing tutorial on How to Use Buttons for more information. 阅读Swing教程中有关如何使用按钮的部分, 获取更多信息。 Or there is also a section on How to Write an Action Listener . 或者还有关于How to Write an Action Listener

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM