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

发布于 2024-11-28 20:46:38 字数 964 浏览 0 评论 0原文

我正在制作一个小项目,其中有一个带有 5 个 JButtons 的 JFrame 。 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 方法,但什么也没发生。

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

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

I tried with ActionListner and MouseListener but to no avail.

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 mouseClicked method for the same code but nothing happened.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

别再吹冷风 2024-12-05 20:46:39

我想知道使用切换类型的按钮(例如 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 行并注释其他两行。

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):

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:

     // 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.

呢古 2024-12-05 20:46:39

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

然后,当单击前三个按钮之一时,您可以对 .setenabled = true 执行简单的 if 语句。

我以前做过,但不太愿意尝试传达如何做。我将包括一些应该可以工作的代码和一个可能比我更好地解释它的教程。

示例:

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 教程

I believe you can look into actionListeners for your button.

Then you could do your simple if statement to .setenabled = true when one of your first three buttons are clicked.

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

来日方长 2024-12-05 20:46:39

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

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.

菩提树下叶撕阳。 2024-12-05 20:46:39

尝试使用MouseEvent的getComponent

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

}

文档

Try with getComponent of MouseEvent:

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

}

Docs

感情洁癖 2024-12-05 20:46:38

您需要了解 ActionListener班级。正如@harper89建议的那样,甚至还有一个关于 如何编写动作侦听器。我还建议您对 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");
                    }
                }
            });
        }
    }
}

在此处输入图像描述


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

You need to understand the ActionListener class. As @harper89 suggested, 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 ActionEvent for the source.


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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文