Waiting for a click input after a button press Java Fx - java

Im having some issues trying to wait for an input after clicking a button.
With my team, we are making a card game, in which cards attack one another, the problem is that i don't know how to, after a button is clicked, make the event handler wait for the user to click another button.
The code looks like this:
private Button attackingButton(){
Button b1 = new Button();
b1.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent event){
//Here i want the user to press another button and, depending which one he
//pressed, asing a variable
Card aCard = //The card that the button pressed has inside
}
}

That's just it, you don't make the handler wait. Instead you change the behavior of the handler depending on the state of the object. If the object is in the "user has not pressed the first button yet" state, the handler does one thing. If the object is in the "user has previously pressed the first button", then the handler does something else. Your handler should query the state of the object's instance fields to determine this state.
e.g.,
b1.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event){
// may need to use boolean fields or .equals(...) method......
if (someStateField == someValue) {
doBehavior1();
} else {
doBehavior2();
}
}
}

Related

Close custom dialog when Enter is pressed in input field

I've designed (using the GUI designer within Netbeans) a small dialog with two radio buttons and a number spinner.
If I press Enter while the focus is on one of the radio buttons, the dialog correctly closes, but if the focus is on the spinner, I have to Tab away from it in order to use the Enter key.
How do I instruct the dialog that Enter really means "accept and close"?
Alternatively, how do I instruct (each) input field to relay an Enter to the "accept and close" handler?
Similarly, how do I instruct the dialog that Esc really means "cancel and close" even when the focus is on the spinner (or other field)?
how do I instruct (each) input field to relay an Enter to the "accept and close" handler?
The easiest approach is to define a "default button" on the dialog. Then when Enter is pressed the default button will be activated. Check out Enter Key and Button for different ways to do this.
how do I instruct the dialog that Esc really means "cancel and close"
Use Key Bindings to invoke the Action of your Cancel button.
First you define an Action to be used by the button:
public class CancelAction extends AbstractAction
{
public CancelAction()
{
super("Cancel");
putValue( Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_C) );
}
#Override
public void actionPerformed(ActionEvent e)
{
Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
if (window != null)
{
WindowEvent windowClosing = new WindowEvent(window, WindowEvent.WINDOW_CLOSING);
window.dispatchEvent(windowClosing);
}
}
}
Then you add the Action to the button so the user can use the mouse:
CancelAction cancelAction = new CancelAction();
cancelButton.setAction( cancelAction );
dialog.add(cancelButton);
Now you can use Key Bindings to bind the Escape key to the CancelAction so the user can use the keyboard:
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
getRootPane().getActionMap().put("ESCAPE", cancelAction);
I suspect the reason I had problems is that a spinner is really a compound control, and the text (well, number) field is an component of that. So I needed to hook up the events to that subcomponent, rather than to the spinner itself:
// Make Ok/Cancel work when JSpinner has focus
getSpinnerField(jSpinnerOffset).addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
doOk();
}
});
where "getSpinnerField()" is just a shorthand in a private method:
private JFormattedTextField getSpinnerField(JSpinner spinner) {
return ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
}
Doing this, the Esc key automagically becomes able to dismiss the dialog.

JavaFX bind buttons to eachother

Not to sure if my title question is correct.
What I'm trying to achieve is to have one button create a Vehicle object. Then have a different button call the method embark (which will just update some fields).
So in general:
One button to create an instance of the object Vehicle.
A second button to call a method on this instance.
btnCar.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
Vehicle C = new Car(amountPass, "hej", "hej");
}
});
btnEmbark.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
ferry.embark(C);
}
});
Thanks!
There are several ways to that, the first that comes to my mind is with JavaFX properties:
ObjectProperty<Object> object = new SimpleObjectProperty<>();
Button button1 = new Button("create");
button1.setOnAction(ev -> object.set(new Object()));
Button button2 = new Button("magic");
button2.setOnAction(ev -> object.get().hashCode());
button2.disableProperty().bind(Bindings.isNull(object));
With Bindings we ensure that the second button can only be fired when the custom object has already been created and stored.
Another way would be to write a subclass of Button doing the communication with another Button. That is a matter of personal taste.

How to create MouseClick event to detect which node is clicked? - javafx

I want to do global MouseClick event to detect which node is clicked in JavaFX. I mean when someone will click a button then event.getSource will return me reference to this button.
Any ideas, how can i do this?
One way to go about this would be to have a static variable somewhere that was of type Node, and then in the listener of the button, just assign a reference to the button in the handler to that button. ex:
public Class test {
public static Node whichClick;
myButton.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
whichClick = myButton;
}
});
}
And then you could access that variable from wherever.

Can we add a ClickHandler and a KeyDownHandler to the same PushButton with an image? I get the click events but the key press event is not captured

Simplified code
play = new PushButton("Play");
play.getUpFace().setImage(new Image(pathToImages+offImage));
play.getUpHoveringFace().setImage(new Image(pathToImages+hoverImage));
play.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
//This event is captured
}
});
I require a keyboard button as a shortcut to play button accordingly I have added
Event.addNativePreviewHandler(new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{ //Call the functionality of play button for the approriate key press
}
});
But once I click the play button using mouse the above nativePreviewHandler does not capture the key press event from keyboard.
So I added a keyDownHandler to the play button
play.addKeyDownHandler(new KeyDownHandler() {
#Override
public void onKeyDown(KeyDownEvent event) {
//This event is never fired
}
});
But the above onKeyDown() method is never called.
Only after I click at some other place on screen is the key press event captured by the nativePreviewHandler.
Just as additional info, I tried following without success
Added DomHandler to the play button instead of keyDownHandler
Removed the images set to the play button
Tried to unfocus the play button every time it is pressed using play.setFocus(false);
Any possible solutions or suggestions are appreciated.
The play button need to have the focus in order to be able to catch the keyDownEvent.
Could you check this ?
If you can't set the focus on that button: check this answer. You need to set a keyDownHandler to a container and ensure it is focused at all time in order to catch the events even if your button is not focused.
This will work:
Event.addNativePreviewHandler(new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getNativeEvent().getType().equals("keydown")) {
Window.alert("Code: " + Integer.toString(event.getNativeEvent().getKeyCode()));
}
}
});

Can I call ActionPerformed method from an Event Handler class for JButton?

I have a JButton titled "select"
In the class that creates that JButton and other classes, I want to use an if condition with ActionPerformed method.
Something like(pseudo-code)
if(_selectListener.actionPerformed(ActionEvent)) { //i.e., if select Button is clicked,
//do something
}
Is this possible?
I want to call this method because I have to handle a situation in which a player should be able to choose something by clicking "select" button, or another "scroll" button, and I want to control it using something similar to a bunch of if statements like the one above.
If it is possible, what is the syntax for it? What is the argument ActionEvent?
Thank you!
The easiest and cleanest way is to add a dedicated, specific action listener to each button. That way, when the actionPerformed() method is called, you're sure that the associated button has been clicked, and don't need to test which button has been clicked:
selectButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle click on select button
}
});
scrollButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle click on scroll button
}
});
Another way is to use a common ActionListener, and use the getSource() method of ActionEvent to know which component triggered the event. Compare the result with each potential button to determine which is the one that has been clicked:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == selectButton) {
// handle click on select button
}
else if (e.getSource() == scrollButton) {
// handle click on scroll button
}
}
What is the argument ActionEvent?
The answer is in the documentation. Read it.
no you cant call, if needs boolean expression/value, but this method returns void.

Categories

Resources