I want to activate an event without clicking all the button interface.
ex. when i click button_0, it will print red, and at the same time it will perform action on button_1 and button_2, hence will also print blue and green at the same time.
Those three operation must be separate, solution as merging both action is not applicable on my case, I only made the example as a small guide.
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button_0)
{
System.out.println("red");
}
else if(e.getSource()==button_1)
{
System.out.println("blue");
}
else if(e.getSource()==button_2)
{
System.out.println("green");
}
}
Here's a dirty way to do it:
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button_0)
{
System.out.println("red");
button_1.doClick();
button_2.doClick();
}
else if(e.getSource()==button_1)
{
System.out.println("blue");
}
else if(e.getSource()==button_2)
{
System.out.println("green");
}
}
Related
So I have a JOptionPane that appears when a certain condition isn't met and for some reason when I press "Ok" it appears again, but then when pressing "Ok" on the second dialog it goes way.
Below is the method where the dialog gets made:
public boolean checkBet()
{
if(currentPlayer.getBet() <= 0)
{
JOptionPane.showMessageDialog(null, "You must place a bet before you can roll your dice!.",
"Bet Required!",
JOptionPane.ERROR_MESSAGE);
return false;
}
else
return true;
}
and this is where the above method gets called:
#Override
public void actionPerformed(ActionEvent e) {
checkBet();
if(checkBet())
{
setRollingPlayer(currentPlayer);
new Thread() {
#Override
public void run() {
gameEngine.rollPlayer(rollingPlayer, 500, 2000, 500);
}
}.start();
}
}
You're call checkBet twice in the actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
checkBet(); // Here
if(checkBet()) // And here
{
When you are calling function checkBet() in actionPerformed(), it has been mentioned two times. Function checkBet() will also execute inside if().
Remove calling once and it will execute once.
I have a lot of different JFormattedTextFields with action and keylisteners. Every Field has a keylistener, so when I press enter I will focus the next JFormattedTextField. The Problem is, for some JFormattedTextFields my code is formatting the input and then sets the text new and for those selectAll() does not work.
JFormattedTextField a = new JFormattedTextField(someDouble);
JFormattedTextField b = new JFormattedTextField(someDouble2);
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
leasingfaktor1Field.selectAll();
if(...) {
//do something
a.setText(tausenderPunkt(someValue));
}
}
});
a.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
b.requestFocusInWindow();
}
}
});
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
leasingfaktor1Field.selectAll();
if(...) {
//do something
b.setText(tausenderPunkt(someValue));
}
}
});
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
c.requestFocusInWindow();
}
}
});
The function tausenderPunkt():
public String tausenderPunkt(double value) {
String s = String.format("%1$,.2f", value);
return s;
}
So when my cursor is in field a and i press enter the cursor goes to field b but does not select the text or values. When i do not use setText() i do not have the problem. Somebody has a solution?
Edit: For some JFormattedTextFields the solution was to add selectAll() to the keyAdapter, but not for all.
For example:
b.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 10) {
c.requestFocusInWindow();
c.selectAll();
}
}
});
Edit2:
The problem seems to be when i create the JFormattedTextFields.
When i do not create them with a value in the constructor it works.
But i have to do.
Before moving to your next text field you should consider handling all the required conditions for the text field you are currently focused on and this would of course include the formatting of values or text supplied to that field. Once all the desired conditions are met then move on to the next text field.
In reality this can all be accomplished through the keyPressed event for your particular situation. There is no need for the actionPerformed event on any of your text fields, for example:
a.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkConditions(a, b);
}
}
});
b.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
checkConditions(b, c);
}
}
});
//---------- and so on -------------
Here is a simple method so as to eliminate the need for repetitious code:
private void checkConditions(JFormattedTextField fieldA, JFormattedTextField fieldB) {
// Make sure something is contained within fieldA and
// that it's actually numerical text.
if(!fieldA.getText().isEmpty() &&
fieldA.getText().matches("([-]?)\\d+([,]\\d+)?(([.]\\d+)?)")) {
// Convert the supplied text to Double and
// ensure the desired numerical formating.
String res = (String)tausenderPunkt(Double.parseDouble(fieldA.getText().replace(",","")));
fieldA.setText(res);
// Set Focus to our next text fieldB.
fieldB.requestFocusInWindow();
// Highlight the contents (if any) within the
// next text fieldB.
fieldB.selectAll();
}
// If fieldA is empty or fieldA does not contain
// numerical text then inform User and re-highlight
// the entry in fieldA.
else {
JOptionPane.showMessageDialog (null, "Please Enter Numerical Values Only!",
"Incorrect Entry", JOptionPane.WARNING_MESSAGE);
fieldA.selectAll();
}
}
If you want the contents of your first text field to be highlighted as soon as focus has been established upon it (tabbed to or clicked on) then consider using a FocusGained event for that component or any other component where you desire the same effect.
I Hope this has helped in some way.
EDITED!
So as to handle OP's particular situation.
String str=this.getText();
this.setText(str);
this.selectAll();
You can get the focus owner and remove the focusable feature:
Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
When you get the component, put this sentence after load it:
component.setFocusable(false);
I would like my button 'licz' to: change text value of info to ''loading'', do something and change 'info' to "done". ('licz' is here a JButton, 'info' JLabel)
licz.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
info.setText("Loading..."); // Here
if(go())
{
brute(0);
info.setText("Done!"); //here
if(odwrot)
JOptionPane.showMessageDialog(frame, "good");
else
JOptionPane.showMessageDialog(frame, "bad");
}
else
{
JOptionPane.showMessageDialog(frame, "bad");
info.setText("Done"); // And here
}
}
});
But the program makes "something" first, changes 'info' label to "loading" and immediately to "done", how to keep these in case?
The event of actionPerformed is handled on the event handling thread, and should terminate fast to have a responsive GUI. Hence call invokeLater.
licz.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
info.setText("Loading...");
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
boolean good = false;
if (go())
{
brute(0);
good = odwrot;
}
JOptionPane.showMessageDialog(frame, good ? "good" : "bad");
info.setText("Done");
}
});
}
});
Or in java 8:
licz.addActionListener((e) -> {
info.setText("Loading...");
EventQueue.invokeLater(() -> {
boolean good = false;
if (go())
{
brute(0);
good = odwrot;
}
JOptionPane.showMessageDialog(frame, good ? "good" : "bad");
info.setText("Done");
});
});
Sorry if this seems a little too easy, I'm brand new to JavaFX, this is my first little app built with it.
I am trying to make a bare bones chat client. I am using the JavaFX Scene builder to make the client UI, and a controller class connected to the FXML.
How can I make is so that the current text of in the text area is submitted to the server and the text area is cleared upon the enter key press, instead of using some kind of "send" button?
EDIT: Here is the code that is not working:
//...
public class FXMLDocumentController
{
//...
#FXML private TextArea messageBox;
//...
messageBox.setOnKeyPressed(new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent keyEvent)
{
if(keyEvent.getCode() == KeyCode.ENTER)
{
//sendMessage();
}
}
});
//...
This should get you what you want:
TextArea area;
//... (initialize all your JavaFX objects here...)
// wherever you assign event handlers...
area.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
String text = area.getText();
// do your thing...
// clear text
area.setText("");
}
}
});
I might add, that if you are so inclined to provide both a button and an enter key event, you could tie the event handler functions of both controls to a single common function in a way such as this:
Button sendButton;
TextArea area;
// init...
// set handlers
sendButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
sendFunction();
}
});
area.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.ENTER) {
sendFunction();
}
}
});
// define send function
public void sendFunction() {
String text = this.area.getText();
// do the send stuff
// clear text (you may or may not want to do this here)
this.area.setText("");
}
Either way works, good luck.
You can use lambda expressions also ... I think it is more elegant and simply
textArea.setOnKeyPressed(event -> {
if(event.getCode() == KeyCode.ENTER){
//type here what you want
}
});
In addition to the other answers, I think it might be useful in some applications to not actually invoke the send function if the user pressed SHIFT+ENTER. In that case he/she maybe actually wanted a new line.
textArea.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
event.consume(); // otherwise a new line will be added to the textArea after the sendFunction() call
if (event.isShiftDown()) {
textArea.appendText(System.getProperty("line.separator"));
} else {
sendFunction();
}
}
});
If you don't want to send empty messages you can do something like this:
textArea.setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
event.consume();
if (event.isShiftDown()) {
textArea.appendText(System.getProperty("line.separator"));
} else {
if(!textArea.getText().isEmpty()){
sendFunction();
}
}
}
});
I'm working on a Java assignment that has to be done using AWT. I want a button to trigger by pushing the enter key while the button is in focus. I figured out how to do this in Swing with the doClick() method, but this doesn't seem to work in AWT. So far I'm trying this:
button.addActionListener(this); // Passes value from a TextBox to actionPerformed()
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER) {
actionPerformed(null);
}
}
});
public void actionPerformed (ActionEvent e) {
try {
if (e.getSource() == button) {
// Stuff I want to happen
} else if (e.getSource() == anotherButton) {
// Other Stuff
} else { //third button
// More stuff
}
} catch (NumberFormatException nfe) {
// Null argument in keyPressed triggers this
// catches empty string exception from TextBox
}
}
As I mentioned with the comments, the null argument will trigger the catch. Does anyone have any idea what that argument might be for the button press or perhaps an altogether easier way to go about this? Thanks.
Edit - clarification: actionPerformed() does one of three things with input from a TextBox depending on which of three buttons is clicked. The try/catch is to catch empty string/format exceptions.
You can always have a method called something like onButtonPress(), which your actionPerformed can call, as well as your keyPressed.
button.addActionListener(this);
button.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
onButtonPress();
}
}
});
public void actionPerformed (ActionEvent e) {
if (e.getSource() == button){
onButtonPress();
}
}
private void onButtonPress(){
// do something
}