java 如何在某些子句上禁用 JButton?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7000247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 18:12:39  来源:igfitidea点击:

How to disable a JButton on certain clause?

javaswingjbutton

提问by Shashwat

I am making a small project, and in it I have a JFramewith 5 JButtons. 3 JButtonsare of primary concern and are enabled by default.

我正在做一个小项目,其中有一个JFramewith 5 JButtons。3JButtons是主要关注点,默认情况下启用。

What I want is until and unless any of those 3 JButtonsare pressed rest of the 2 should remain disabled.

我想要的是直到并且除非这 3 个JButtons中的任何一个被按下,否则2 个的其余部分应该保持禁用状态。

I tried with ActionListnerand MouseListenerbut to no avail.

我尝试过ActionListnerMouseListener但无济于事。

Check the multiple code that i tried.

检查我尝试过的多个代码。

public void mousePressed (MouseEvent me){    
     if (me.getButton() == MouseEvent.NOBUTTON ){

        proceedBtn.setEnabled(false);
        proceedBtn.setToolTipText("Please Enter A Button Before Proceeding");
    }
    else {                   
        proceedBtn.setEnabled(true);        
    }

}

and here is another piece of code that I tried.

这是我尝试过的另一段代码。

public void mousePressed (MouseEvent me){    
     if (me.getClickCount == 0 ){

        proceedBtn.setEnabled(false);
        proceedBtn.setToolTipText("Please click a button Before Proceeding");
    }
    else {                   
        proceedBtn.setEnabled(true);        
    }

}

What am I doing wrong here ? I even tried mouseClickedmethod for the same code but nothing happened.

我在这里做错了什么?我什至尝试mouseClicked了相同代码的方法,但什么也没发生。

回答by mre

You need to understand the ActionListenerclass. As @harper89suggested, there's even a tutorial on How to Write an Action Listener. I also suggest you subclass JButton, since that seems more appropriate than querying the ActionEventfor the source.

您需要了解ActionListener类。正如@harper89 所建议的那样,甚至还有一个关于如何编写动作侦听器的教程。我还建议您使用 subclass JButton,因为这似乎比查询ActionEvent源更合适。



Here's an example -

这是一个例子——

public final class JButtonDemo {
    private static DisabledJButton disabledBtnOne;
    private static DisabledJButton disabledBtnTwo;

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

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        final JPanel disabledBtnPanel = new JPanel();
        disabledBtnOne = new DisabledJButton();
        disabledBtnTwo = new DisabledJButton();
        disabledBtnPanel.add(disabledBtnOne);
        disabledBtnPanel.add(disabledBtnTwo);
        panel.add(disabledBtnPanel);

        final JPanel enablerBtnPanel = new JPanel();
        enablerBtnPanel.add(new EnablerJButton("Button 1"));
        enablerBtnPanel.add(new EnablerJButton("Button 2"));
        enablerBtnPanel.add(new EnablerJButton("Button 3"));
        panel.add(enablerBtnPanel);

        frame.add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private static final class DisabledJButton extends JButton{
        public DisabledJButton(){
            super("Disabled");
            setEnabled(false);
        }
    }

    private static final class EnablerJButton extends JButton{
        public EnablerJButton(final String s){
            super(s);
            addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    if(!disabledBtnOne.isEnabled()){
                        disabledBtnOne.setEnabled(true);
                        disabledBtnOne.setText("Enabled");
                    }

                    if(!disabledBtnTwo.isEnabled()){
                        disabledBtnTwo.setEnabled(true);
                        disabledBtnTwo.setText("Enabled");
                    }
                }
            });
        }
    }
}

enter image description here

在此处输入图片说明



If you press any of the three enabled buttons, both of the disabled buttons will become enabled, as per your request.

如果您按三个启用的按钮中的任何一个,则两个禁用的按钮都将根据您的要求启用。

回答by Hovercraft Full Of Eels

I wonder if you code would be better with a toggle type of button such as a JToggleButton or one of its children (JRadioButton or JCheckBox). This way the user can see if the lower buttons are selected or "active" or not. This also would allow you to control if the user can check one or more of the three bottom buttons or just one bottom button (by using a ButtonGroup object). For example, and apologies to mre for partly stealing his code (1+ for his answer):

我想知道使用切换类型的按钮(例如 JToggleButton 或其子项之一(JRadioButton 或 JCheckBox))是否会更好地编写代码。通过这种方式,用户可以查看下方按钮是否被选中或“活动”。这也将允许您控制用户是否可以检查三个底部按钮中的一个或多个或仅检查一个底部按钮(通过使用 ButtonGroup 对象)。例如,向 mre 道歉,因为他部分窃取了他的代码(他的回答为 1+):

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JButtonDemo2 {
   private static final String[] TOGGLE_NAMES = { "Monday", "Tuesday",
         "Wednesday" };
   private JPanel mainPanel = new JPanel();
   private JButton leftButton = new JButton("Left");
   private JButton rightButton = new JButton("Right");

   private JToggleButton[] toggleBtns = new JToggleButton[TOGGLE_NAMES.length];

   public JButtonDemo2() {
      JPanel topPanel = new JPanel();
      topPanel.add(leftButton);
      topPanel.add(rightButton);
      leftButton.setEnabled(false);
      rightButton.setEnabled(false);

      CheckListener checkListener = new CheckListener();
      JPanel bottomPanel = new JPanel(new GridLayout(1, 0, 5, 0));
      for (int i = 0; i < toggleBtns.length; i++) {

         // uncomment one of the lines below to see the program 
         // with check boxes vs. radio buttons, vs toggle buttons
         toggleBtns[i] = new JCheckBox(TOGGLE_NAMES[i]);
         // toggleBtns[i] = new JRadioButton(TOGGLE_NAMES[i]);
         // toggleBtns[i] = new JToggleButton(TOGGLE_NAMES[i]);


         toggleBtns[i].setActionCommand(TOGGLE_NAMES[i]);
         toggleBtns[i].addActionListener(checkListener);
         bottomPanel.add(toggleBtns[i]);
      }

      mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
      mainPanel.add(topPanel);
      mainPanel.add(bottomPanel);
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   public void enableTopButtons(boolean enable) {
      leftButton.setEnabled(enable);
      rightButton.setEnabled(enable);
   }

   private class CheckListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
         for (JToggleButton checkBox : toggleBtns) {
            if (checkBox.isSelected()) {
               enableTopButtons(true);
               return;
            }
         }
         enableTopButtons(false);
      }

   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("JButtonDemo2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new JButtonDemo2().getMainComponent());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

If you want to see this code with JToggleButtons, then comment out the line that creates JCheckBoxes and uncomment the line that creates JToggleButtons:

如果您想使用 JToggleButtons 查看此代码,请注释掉创建 JCheckBoxes 的行并取消注释创建 JToggleButtons 的行:

     // toggleBtns[i] = new JCheckBox(TOGGLE_NAMES[i]);
     // toggleBtns[i] = new JRadioButton(TOGGLE_NAMES[i]);
     toggleBtns[i] = new JToggleButton(TOGGLE_NAMES[i]);

Similarly if you want to see the program with JRadioButtons uncomment only the JRadioButton line and comment the other two.

同样,如果您想查看带有 JRadioButton 的程序,请仅取消注释 JRadioButton 行并注释其他两个。

回答by sealz

I believe you can look into actionListenersfor your button.

我相信你可以看看actionListeners你的按钮。

Then you could do your simple ifstatement to .setenabled = truewhen one of your first three buttons are clicked.

然后,您可以对单击前三个按钮之一的时间进行简单if说明.setenabled = true

I have done them before but am not comfortable trying to relay how. Ill include some code that should work and a tutorial that may explain it better than me.

我以前做过它们,但我不舒服试图传达如何。我将包含一些应该可以工作的代码和一个可能比我更好地解释它的教程。

Example:

例子:

JButtonOne.addActionListener(new ButtonHandler();)

private class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {

//write your if statement or call a method etc here

}
}

Actionlistener Tutorial

动作监听器教程

回答by Chris

Try putting your mouse listeners on the normally active buttons. That way, when they activated, they can enable the normally inactive buttons. Also, set the normally inactive buttons to be disabled when the app first starts.

尝试将鼠标侦听器放在通常处于活动状态的按钮上。这样,当他们激活时,他们可以启用通常不活动的按钮。此外,将通常不活动的按钮设置为在应用程序首次启动时禁用。

回答by Geo

Try with getComponentof MouseEvent:

尝试使用getComponentMouseEvent:

if(mouseEvent.getComponent() == aButton) {

}

Docs

文档