JButton doClick() performs the last clicked button - java

This is the block of code that I am using to check for key presses. If I press the 'esc' key then the JFrame closes. But, if I press the 'space' bar the listener performs the last JButton pressed, NOT the specific button I am telling it to click. The doClick() also does not run unless a JButton was previously clicked.
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if(ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
SaveScripts.saveData(player);
dispose();
}
if(ke.getKeyCode() == KeyEvent.VK_SPACE) {
center.buttonMenuAttack.doClick();
}
}
});
Edit 1: Ok after some more testing, the issue seems to be that the listener breaks when anything in the frame is clicked.
Program Launches
Listener is active and working.
Any component of the frame is clicked, the listener breaks
Edit 2: I ended up going with camickr's solution, its much easier to set up and I haven't had any issues with using it.
InputMap events = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actions = getRootPane().getActionMap();
events.put(KeyStroke.getKeyStroke("SPACE"), "click");
actions.put("click", new AbstractAction() {
public void actionPerformed(ActionEvent event) {
center.bAttack.doClick();
}
});
events.put(KeyStroke.getKeyStroke("ESCAPE"), "click");
actions.put("click", new AbstractAction() {
public void actionPerformed(ActionEvent event) {
manage.bDataExit.doClick();
}
});

I figured out the issue. The Listener stopped working because when a button is clicked, it becomes the focused. I made a class that extends JButton so that all my buttons have the same behavior and added the following line of code to its constructors;
setRequestFocusEnabled(false);
This way, after a button is clicked the JFrame remains focused, allowing the Listener to behave as intended.

Related

How to "close" a JMenu in an Event Handler - Java

I have a simple MouseAdapter that I add to a JMenu. I want the menu to show its contents when moused over, react when clicked on, and hide its contents when the mouse leaves it. Here's where I add the listener:
public final void addGuiReaction(Runnable clickReaction) {
JMenu THIS = this;
this.addMouseListener(new MouseAdapter() {
final Runnable reaction = clickReaction;
final JMenu source = THIS;
#Override
public void mouseClicked(MouseEvent arg0) {reaction.run();}
#Override
public void mouseEntered(MouseEvent arg0) {source.doClick();} // Opens the menu
#Override
public void mouseExited(MouseEvent arg0) {/* Need to "close" the menu */}
});
}
This works just fine for both the reaction and the open when moused over functionality, but I can't figure out how to close it. Tried both setSelected(false) and setPopupMenuVisible(false) but the issue with both is that the menu doesn't open again the next time I mouse over it.
Anyone knows a nice way of closing the menu?
Answering to "How to close the JMenu..."
In place of this:
/* Need to "close" the menu */
You can put this:
source.dispatchEvent(new KeyEvent(source, KeyEvent.KEY_PRESSED, 0, 0, KeyEvent.VK_ESCAPE));
Hence simulate the ESC key press which will trigger the respective Action from the ActionMap of the JMenuBar.
However this will not fully solve your problem as while the keyboard arrow keys will work, you will not be able to use the mouse to select any of the items of the JMenu as trying to enter any of them will trigger the JMenu mouseExited event. You may need to attach a proper mouse event listener to the menu items as well.

How To Use JButton "If pressed and if released"

Im looking to use JButton in substitute of my Keylistener. Key listener has methods such as if pressed if released etc. Im looking to do the same thing with this JButton, Exp: If user clicks with mouse and holds mouse in clicked position code will execute until s/he releases the buttoning which execution of the code will cease.
What I tried? I tried to use JButton at first which didn't produce the result I wanted because form my understanding JButton requires a full "click" I have been playing with JToggleButton
if (JToggButton.getModel().isPressed()) which is still not working, can someone please point me in the right direction to produce the desired result?
SPECIFIC GOAL:
I want to use the a microphone method I built, I will click the Button that says Microphone and I will hold down the click until I'm ready to finish speaking into the Mic, think of Facebook how you hold down the mic with your thumb and when you release it the voice recording stops, so there would be 2 methods startLogic(); when pressed down and held and stopLogic(); when finally released when user is done speaking
Note that a simple but wrong solution is to use a MouseListener, wrong since this listener does not respond to button depression but rather mouse press, and this will miss button press if it is pressed by any means other than the mouse, such as the spacebar.
I would listen to the button's ButtonModel with a ChangeListener and respond to changes in its isPressed() state. This will work no matter what presses the button, be it the mouse or the spacebar. For example:
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
#SuppressWarnings("serial")
public class ButtonPressTest extends JPanel {
private JButton button = new JButton("Button");
private JTextArea textArea = new JTextArea(15, 15);
public ButtonPressTest() {
button.getModel().addChangeListener(new BtnModelListener());
textArea.setFocusable(false);
add(button);
add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
}
private class BtnModelListener implements ChangeListener {
private boolean pressed = false; // holds the last pressed state of the button
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
// if the current state differs from the previous state
if (model.isPressed() != pressed) {
String text = "Button pressed: " + model.isPressed() + "\n";
textArea.append(text);
pressed = model.isPressed();
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("ButtonPressTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ButtonPressTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to use jbutton to make an jlabel to appear and disappear right away after releasing the click in JAVA

As the title says, I would like to know the syntax for that
I am making a first person boxing game when you click the button it punches the enemy but after releasing it, the image of the punch disappears right away.
the concept of the game is how many click the user can make in a certain period of time
I don't have a code to show because its blank inside the button
Start with this:
JButton btnPunch = new JButton("");
btnPunch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnPunch.setVisible(btnPunch.isVisible() ? false : true);
}
});
If you want an action to be done On Release use:
addMouseListener(new
MouseAdapter() {
public void mouseReleased(MouseEvent e)
{ // TODO: add your code here
} });

Remove button with ActionListener from JFrame

Basically I have a class that extends JFrame, and I'm trying to have an ActionListener remove a button after another button has been clicked, it doesn't seem to be working...
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Registered existing character click...");
getContentPane().remove(loginButton);
frame.remove(newAccountButton);
frame.revalidate();
frame.repaint();
//add(lookUp);
//add(searchButton);
bg.setIcon(rsLgn);
// lookUp.requestFocus();
// setComponentZOrder(searchButton, 0);
// setComponentZOrder(lookUp, 0);
}
});
EDIT: Currently, the button is invisible, so I wouldn't technically know if it was removed or not, but the System.out.println is definitely still outputting the original message of "Registered existing character click..."

Take input from mouse and keyboard at the same time in Java GUI

I need to make the GUI in java respond to mouse and keyboard input simultaneously.. I know I should add something to the loop in the action listener .. but did not find the right idea .. any suggestions please??
I need to make my GUI respond to the mouse motion and clicks and at the same time respond to the keyboard button pressed if mouse is over a button and pressed enter .. the GUI will respond to the keyboard and the mouse motion actions will continue normally !! .. Hope the problem is cleared!
You do not have to "add something in loop". You just have to add MouseListener and KeyListener to your GUI element (e.g. Frame) and implement the callback methods as you want.
Take a look, at Toolkit.addAWTEventLstener
This will allow you monitor all the events flowing the event queue.
The problem your going to have is identifying the components that are in the area of effect and overcoming the default behaviour of the components (pressing enter while a text field has focus will trigger a action event on it, but now you want to do something else)
To get the behavior of responding to a mouse over the button and enter being pressed I would:
Use Key Bindings attached to the JButton to allow it to respond to the enter key.
Make sure that when doing the above use the InputMap that is associated with the JComponent.WHEN_IN_FOCUSED_WINDOW constant so that the button doesn't actually have to have focus to respond but needs to be in the focused window.
Of course bind to the KeyStroke associated with KeyEvent.VK_ENTER.
In the key bindings action, check if the button's model is in the rollOver state by calling isRollOver() on the model.
and if so, respond.
Note that none of this above requires a MouseListener because I'm using the ButtonModel's isRollOver in place of that.
As an example, my SSCCE:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class MouseKeyResponse extends JPanel {
private JButton button = new JButton("Button");
public MouseKeyResponse() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
add(button);
setUpKeyBindings(button);
}
private void setUpKeyBindings(JComponent component) {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = component.getInputMap(condition);
ActionMap actionMap = component.getActionMap();
String enter = "enter";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), enter);
actionMap.put(enter, new EnterAction());
}
private class EnterAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent evt) {
if (button.isEnabled() && button.getModel().isRollover()) {
System.out.println("Enter pressed while button rolled over");
button.doClick();
}
}
}
private static void createAndShowGui() {
MouseKeyResponse mainPanel = new MouseKeyResponse();
JFrame frame = new JFrame("MouseKeyResponse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories

Resources