How can I disable the mouse click on the button action event? - java

Is there a way I can disable mouse click ? In the panel there are different components and for some of the Button Click events, I want to disable the mouse click. I mean the click of the mouse doesn't have any effect on the components. I can disable using the setEnabled() function but I don't want to do that way.
Is there any way I can disable the mouse click ?
Situation :
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//..disable the mouse click on each component present inside the panel
}

You can add an extended ActionListener to all the buttons like this:
public abstract class ExtendedActionListener implements ActionListener{
private static boolean disabled = false;
public static void setDisabled(boolean disabled){
ExtendedActionListener.disabled = disabled;
}
#Override
public final void actionPerformed(ActionEvent e){
if(disabled)
return;
doSomething;
}
}
And now just disable all the ActionListeners by calling the method setDisabled(false). The Button visual behavior doesn't change at all, but nothing happens, when you click on it.
If the visual click behaviour doesn't matter, then you can just remove the MouseListeners.

You can create a button group like this:
public class SingleSelectionButtonGroup {
private final List<JButton> buttons;
public static SingleSelectionButtonGroup group(List<JButton> buttons) {
return new SingleSelectionButtonGroup(buttons);
}
public static SingleSelectionButtonGroup group(JButton...buttons) {
return new SingleSelectionButtonGroup(Arrays.asList(buttons));
}
private SingleSelectionButtonGroup(List<JButton> buttons) {
this.buttons = new ArrayList<JButton>(buttons);
setupListener();
}
private void setupListener() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
SingleSelectionButtonGroup.this.disableAllExcept((JButton) e.getSource());
}
};
for (JButton button : buttons) {
button.addActionListener(listener);
}
}
private void disableAllExcept(JButton clickedButton) {
for (JButton button : buttons) {
if (!clickedButton.equals(button)) {
button.setEnabled(false);
}
}
}
}
And then uses it with a collection of buttons that you want to group:
public class Application {
public void run() {
final JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 300));
final JPanel pane = new JPanel();
List<JButton> buttons = new ArrayList<JButton>();
String[] texts = {"A", "B", "C"};
for (String text : texts) {
JButton button = new JButton(text);
buttons.add(button);
pane.add(button);
}
SingleSelectionButtonGroup.group(buttons);
frame.getContentPane().add(pane);
frame.setVisible(true);
}
public static void main(String[] args) {
new Application().run();
}
}

you should use one common class of your listener and have static method for turn listener turn on and off
public abstract class BaseMouseListener implements ActionListener{
private static boolean active = true;
public static void setActive(boolean active){
BaseMouseListener.active = active;
}
protected abstract void doPerformAction(ActionEvent e);
#Override
public final void actionPerformed(ActionEvent e){
if(active){
doPerformAction(e);
}
}
}
your listeners would have to implements doPerformedAction()

Add empty mouse listener. This will "disable" the click because it will not have any effect.

Related

Java Swings: Is there any provision to add a close button to popup window?

How can we add a close button on the Pop up window similar to a JFrame on the right corner so that we can close that popup by clicking on it?
Thanks for the help
You can create your own PopMenu by extanding JPopupMenu. By adding an action listener to the button you can react with anything you want(for example closing popup). Here is an example:
public class TestPopupMenu extends JPopupMenu {
private JLabel testLabel;
private JButton testButton;
public TestPopupMenu() {
super();
initMenuItems();
}
private void initMenuItems() {
add(getTestLabel());
add(getTestButton());
}
private JButton getTestButton() {
if (testButton == null) {
testButton = new JButton("Test");
testButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do something what you want
}
});
}
return testButton;
}
private JLabel getTestLabel() {
if (testLabel == null) {
testLabel = new JLabel("#Some text");
}
return testLabel;
} }

ActionListener with a custom Button class (Java)

I dont need an outright answer for this. just a suggestion on how this problem could be fixed. I am trying to add an action listener to MyButton so that i can call the action performed method in my main class
this is the buttons constructed. they show up and everything works on them minus the actionlistener.
upButton = new MyButton(upStaticImageLocation, upRolledImageLocation, upClickedImageLocation);
upButton.addActionListener(this);
downButton = new MyButton(downStaticImageLocation, downRolledImageLocation, downClickedImageLocation);
downButton.addActionListener(this);
this is the MyButton class with action listener method.
public class MyButton extends JComponent implements MouseListener {
private Dimension size = new Dimension(32, 32);
private Image staticImage;
private Image rolledImage;
private Image clickedImage;
private ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();
public MyButton(String staticImage, String rolledImage, String clickedImage) {
super();
this.staticImage = new ImageIcon(staticImage).getImage();
this.rolledImage = new ImageIcon(rolledImage).getImage();
this.clickedImage = new ImageIcon(clickedImage).getImage();
enableInputMethods(true);
addMouseListener(this);
setSize(size.width, size.height);
setFocusable(true);
}
This seems like a lot of work which has already been done...see How to Use Buttons, Check Boxes, and Radio Buttons for more details.
However, JComponent already provides access to an EventListenerList, so you don't need your listeners List, for example...
public class MyButton extends JComponent implements MouseListener {
//private ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();
public MyButton(String staticImage, String rolledImage, String clickedImage) {
//...
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
Okay, but how do you trigger the event?
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners != null) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Awesome button action");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
So whenever you want to send an ActionPerformed event, you simply call the fireActionPerformed method within your button
I am not sure if I understand you correctly but think that instead of :
downButton.addActionListener(this);
you must use:
downButton.addActionListener(downButton);
since you are trying to add action listener somewhere outside MyButton so 'this' does not point to instance of MyButton and MyButton must implement ActionListener ie this method:
#Override public void actionPerformed(ActionEvent e)
{
// doo your woodoo here
}
Thought I should post the method that fixed the action listeners and made the whole thing work. Thanks to madProgrammer for his answer.
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners != null) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "Awesome button action");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
public void mouseClicked(MouseEvent e) {
fireActionPerformed();
}
just needed the call on fireActionPerformed when the mouse was clicked.

ActionListener in java performs action on the second click

I am programming my first complex application in Java, Swing. When I have added ActionListener to my JButton.
ActionListener changeButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
if(startButton.getText() == "Spustit") {
startButton.setText("STOP");
} else {
startButton.setText("Spustit");
}
}
}
I am adding ActionListener to the button itself
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
startButton.addActionListener(changeButton);
}
Can you tell me where I coded ActionListener badly?
Thanks to all!
You have coded the ActionListener good enough to be working, at least, for the action listener itself. The problem is that you are adding the action listener after an event (your second sample), thus your action listener will get called the second time you will click it.
A solution is very simple:
JButton button = new JButton();
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//...
}
});
Now the action listener should activate on the first click if you directly add a new ActionListener to the button, not after an action is performed
Why are you adding the actionlistener in actionPerformed? I think you should do something like this:
public static void main(String[] args) {
final JButton startButton = new JButton("Spustit");
ActionListener changeButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (startButton.getText() == "Spustit") {
startButton.setText("STOP");
} else {
startButton.setText("Spustit");
}
}
};
startButton.addActionListener(changeButton);
// Add it to your panel where you want int
}

Clicking a JButton consecutively

Is there a way to know if a JButton was clicked consecutively? Consider my code.
public void actionPerformed(ActionEvent arg0) {
String bucky[] = new String[2];
String firstclick = null, secondclick = null;
clicks++;
if (clicks == 1) {
bucky[0] = firstclick;
} else if(clicks == 2) {
bucky[1] = secondclick;
if (bucky[0] == bucky[1]) {
//This JButton was clicked twice in a row.
}
}
This code checks the entire number of times my JButton was clicked and displays the message "This button was clicked twice in a row". What I want is to compare two clicks from that button and see if they come one after the other rather than counting the number of clicks made. Or is there a built-in function that does this?
Just use a field remembering what the last clicked button was:
private JButton lastButtonClicked;
...
someButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (lastButtonClicked == e.getSource()) {
displayError();
}
else {
lastButtonClicked = (JButton) e.getSource();
doSomething();
}
}
});
Of course, you'll have to do the same thing with all the other buttons.
I have a different approach to your problem:
You want to not allow the user to press the same button in some group of buttons twice in a row.
You're solutions so far have tried to check which button was pressed last, and then warn the user if the same button has been pressed in a row.
Perhaps a better solution is to create a construct that simply doesn't allow the user to press the same button twice in a row.
You can create your ButtonGroup like object that selectively disables the last button pressed, and enables all the other buttons.
You would give this class an add(AbstractButton btn) method to allow you to add all the buttons that you wish to behave this way to it. The button would then be added to an ArrayList.
You would give it a single ActionListener that listens to all the buttons. Whenever the actionPerformed method has been pressed, it enables all of the buttons, and then selectively disables the last button pressed.
For instance consider my class below:
public class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
If you create a single object of this in your class that creates the buttons, and add each button to the object of this class, your code will automatically disable the last button pressed, and re-enable it once another button has been pressed.
You could use it like so:
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
JButton yesButton = new JButton(new YesAction());
noRepeatButtonGroup.add(yesButton);
buttonPanel.add(yesButton);
JButton noButton = new JButton(new NoAction());
noRepeatButtonGroup.add(noButton);
buttonPanel.add(noButton);
JButton maybeButton = new JButton(new MaybeAction());
noRepeatButtonGroup.add(maybeButton);
buttonPanel.add(maybeButton);
For example, here is a proof of concept minimal runnable example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class NoneInARowBtns {
private static void createAndShowGui() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
NoRepeatButtonGroup noRepeatButtonGroup = new NoRepeatButtonGroup();
int buttonCount = 5;
for (int i = 0; i < buttonCount; i++) {
JButton btn = new JButton(new ButtonAction(i + 1));
noRepeatButtonGroup.add(btn);
buttonPanel.add(btn);
}
JOptionPane.showMessageDialog(null, buttonPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
public ButtonAction(int i) {
super("Button " + i);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand() + " Pressed");
}
}
class NoRepeatButtonGroup implements ActionListener {
private List<AbstractButton> btnList = new ArrayList<>();
public void add(AbstractButton btn) {
btnList.add(btn);
btn.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent evt) {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
((AbstractButton) evt.getSource()).setEnabled(false);
}
public void reset() {
for (AbstractButton btn : btnList) {
btn.setEnabled(true);
}
}
}
When the above program runs, and when the second button is pressed, you will see that it is disabled:
Then when the 3rd button has been pressed, the 2nd is re-enabled, and the 3rd one is disabled:
And etc for the 4th button....
A global variable arrau of booleans, one for each button, set true on first click, set false or second, sjould do it

JPanel Action Listener

I have a JPanel with a bunch of different check boxes and text fields, I have a button that's disabled, and needs to be enabled when specific configurations are setup.
What I need is a listener on the the whole JPanel looking for events, whenever anything changes.
I believe I need an action listener but I can't find anything to bridge the action Listener with the JPanel
JPanel Window = new JPanel();
Window.addActionListener(new ActionListener(){
//Check if configurations is good
}
I figure I can copy and paste my code a bunch of times into every listener in the panel, but that seems like bad coding practice to me.
First off as #Sage mention in his comment a JPanel is rather a container than a component which do action. So you can't attach an ActionListener to a JPanel.
I figure I can copy and paste my code a bunch of times into every
listener in the panel, but that seems like bad coding practice to me.
You're totally right about that, it's not a good practice at all (see DRY principle). Instead of that you can define just a single ActionListener and attach it to your JCheckBoxes like this:
final JCheckBox check1 = new JCheckBox("Check1");
final JCheckBox check2 = new JCheckBox("Check2");
final JCheckBox check3 = new JCheckBox("Check3");
final JButton buttonToBeEnabled = new JButton("Submit");
buttonToBeEnabled.setEnabled(false);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
boolean enable = check1.isSelected() && check3.isSelected();
buttonToBeEnabled.setEnabled(enable);
}
};
check1.addActionListener(actionListener);
check2.addActionListener(actionListener);
check3.addActionListener(actionListener);
This means: if check1 and check3 are both selected, then the button must be enabled, otherwise must be disabled. Of course only you know what combination of check boxes should be selected in order to set the button enabled.
Take a look to How to Use Buttons, Check Boxes, and Radio Buttons tutorial.
A suggestion could be to derive a class from each of the components you're using and add an ActionListener that bubbles up the Container tree and looks for the first Container that implements a custom interface like this:
public interface MyCommandProcessor {
void execute(String actionCommand);
}
public class MyButton extends JButton {
public MyButton(string actionCommand) {
setActionCommand(actionCommand);
addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Container traverser = MyButton.this;
while (traverser != null && !(traverser instanceof MyCommandProcessor))
traverser = traverser.getParent();
if (traverser != null)
((CommandListener)traverser).execute(ae.getActionCommand());
}
});
}
}
public class MyApp extends JFrame implements MyCommandListener {
public MyApp() {
JPanel panel = new Panel();
panel.add(new MyButton("MyButton got pressed"));
}
public void execute(String actionCommand) {
System.out.println(actionCommand);
}
}
You need to create custom component listener. Look here:
Create a custom event in Java
Creating Custom Listeners In Java
http://www.javaworld.com/article/2077333/core-java/mr-happy-object-teaches-custom-events.html
I do it throw the standard ActionListener
Example
public class MyPanel extends JPanel {
private final JComboBox<String> combo1;
private final JButton btn2;
.......
//catch the actions of inside components
btn2.addActionListener(new MyPanelComponentsActionListener());
........
//assign actionlistener to panel class
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
//handle registered listeners from components used MyPanel class
protected void fireActionPerformed(ActionEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
ActionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
// Lazily create the event:
if (e == null) {
String actionCommand = event.getActionCommand();
if(actionCommand == null) {
actionCommand = "FontChanged";
}
e = new ActionEvent(FontChooserPanel.this,
ActionEvent.ACTION_PERFORMED,
actionCommand,
event.getWhen(),
event.getModifiers());
}
// here registered listener executing
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
//!!! here your event generator
class MyPanelComponentsActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//do something usefull
//.....
fireActionPerformed(e);
}
}
....
}

Categories

Resources