Button event still works with button disabled

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

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

How can I do this if I press a button, it ignores the code and is really disabled?

+4
source share
3 answers

However, the button still executes the code under MouseEvent , and I see that the button is clicked. "in the debug console.

That is why you should not use MouseListener with JButton, but rather an ActionListener. Of course, the solution is obvious - get rid of MouseListener and instead add an ActionListener to the JButton of interest.

+10
source

you need to use ActionListener instead of MouseClickListener.

your button is logically pressed even if it is disabled, so the click event will execute

+1
source

Actually there is a very simple way to enable and disable a button in java that 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 trying to create something similar, and that’s how I solved it. All MouseListener methods return void, so it works pretty well. In my situation, returning to an ActionListener would require a lot of extra work, while a MouseListener would be ideal for the job. Click set the variable that Release undid and another thread used the variable in the current simulation.

+1
source

Source: https://habr.com/ru/post/1335579/


All Articles