Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

button event still works with button disabled

Tags:

java

swing

private void button_Clicked_download(MouseEvent e) {
      button_dl.setEnabled(false);
      System.out.println("Button Clicked.");
}

When I click the button the button looks disabled. However the button still executes the code under the MouseEvent and I see "Button Clicked." in the debug console.

How can I make it so if the button is clicked it ignores the code and is indeed disabled?

like image 993
Kyle Avatar asked Jan 14 '11 16:01

Kyle


People also ask

Why disabled Button is still clickable?

Because you have to enable click event again, if you enable the button.

Does click event fire on disabled button?

I want to fire the onclick event of the button. It is not possible to fire Click for disabled button. Simply add a Hidden Button (style="display:none") and Fire click.


2 Answers

However the button still executes the code under the MouseEvent and I see "Button Clicked." in the debug console.

This is exactly why you shouldn't use a MouseListener with a JButton but rather an ActionListener. The solution is of course obvious -- to get rid of the MouseListener and instead add an ActionListener to the JButton of interest.

like image 163
Hovercraft Full Of Eels Avatar answered Oct 05 '22 23:10

Hovercraft Full Of Eels


There is actually a very simple way of enabling and disabling a button in java which uses a Mouse Listener.

class HoldListen extends MouseAdapter {

    @Override
    public void mousePressed(MouseEvent e) {
        JButton bt = (JButton)e.getSource();

        if (!bt.isEnabled()) {
            return;
        }

        // Do code 
    }
}

I found your question while trying to create something similar and this is how I solved it. All the MouseListener's methods return void so it works out quite nice. In my situation going back to an ActionListener would have required a lot of extra work while a MouseListener was perfect for the job. Press set a variable which Release undid and another thread used the variable in a ongoing simulation.

like image 21
Steinin Avatar answered Oct 06 '22 00:10

Steinin