如何在特定条件下禁用一个JButton?

3
我正在进行一个小项目,在其中我有一个带有5个 JButtonsJFrame 。3个主要关注的 JButtons 默认情况下是启用的。
我想要的是,在没有按下这3个 JButtons 之前,其他2个应该保持禁用状态。我尝试了 ActionListnerMouseListener ,但没有成功。
请查看我尝试的多个代码。
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);        
    }

}

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

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

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

}

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

你应该使用一个ActionListener。你说你以前尝试过,但没有成功。我们可以看一下那段代码吗?使用MouseListener绝对不是正确的方法。 - mre
也许你应该使用 JCheckBoxes、JRadioBoxes 或 JToggleButtons 来作为必须先被按下的按钮。这样用户和程序可以一眼知道它们是否已经被按下。 - Hovercraft Full Of Eels
5个回答

6
你需要了解ActionListener类。正如@harper89建议的那样,甚至有一个关于如何编写Action Listener的教程。我还建议您子类化JButton,因为这似乎比查询ActionEvent更合适作为源。

这是一个例子 -

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


如果您按下三个启用的按钮中的任何一个,两个禁用的按钮将根据您的要求变为启用状态。

4

我想知道如果您使用切换按钮,例如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();
         }
      });
   }
}

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

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

同样地,如果您想使用JRadioButtons查看程序,请取消注释JRadioButton行并注释其他两个选项。


3

我相信您可以查看按钮的actionListeners

然后,当您的前三个按钮之一被点击时,您可以使用简单的if语句将.setenabled = true

我以前做过这些,但不太舒适地尝试传达如何操作。我会包含一些代码,应该可以正常工作,并提供一个比我更好的教程。

示例:

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


0

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


目前它们仅在3个按钮中设置。我尚未将监听器分配给其他2个按钮。 - Shashwat
是的,你的建议确实有效,一开始禁用按钮就解决了 :) 这很简单,但正如每个人建议的那样,我会坚持使用ActionListener :) 谢谢。 - Shashwat
抱歉,大家。我本来想说ActionListener的。我的错因为没有确认。 - Chris

-2

使用 MouseEvent 的 getComponent 方法尝试:

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

}

文档


因为我想根据他发布的内容提供帮助。 - Geo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接