开发者

How to disable a JButton on certain clause?

开发者 https://www.devze.com 2023-03-26 20:40 出处:网络
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.

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){    
     开发者_如何学Cif (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.


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");
                    }
                }
            });
        }
    }
}

How to disable a JButton on certain clause?


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


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.


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


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.


Try with getComponent of MouseEvent:

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

}

Docs

0

精彩评论

暂无评论...
验证码 换一张
取 消