This is the code I'm using to process the input of an integer :
public static int getIntInput(String message) {
String numberStr = JOptionPane.showInputDialog(message);
while (!StringUtils.isNumeric(numberStr) || Integer.parseInt(numberStr) == 0) {
numberStr = JOptionPane.showInputDialog(message);
}
return Integer.parseInt(numberStr);
}
It works fine, except when I want to press "cancel" or close button on the JOption window. When I do that, the JOptionPane window shows up again.
How can I correctly close a JOptionPane window when the cancel or close button is pushed?
while (!StringUtils.isNumeric(numberStr) || Integer.parseInt(numberStr) == 0) {
if (numberStr == null) {
return 0;
}
else {
numberStr = JOptionPane.showInputDialog(message);
}
}
This does the trick.
Related
Hi I am trying to add a sort of option window to my application using JOptionPane. If you click yes, a boolean is true. If you click no, a boolean is false and if you click the last button, I want another boolean to say false. And whenever that last button is clicked, I want that window to never be popped up again.
This is my code at the moment.
if (Configuration.LOGIN_MUSIC) {
Object[] options = {"Yes",
"No",
"No, don't ask me again!"};
int n = JOptionPane.showOptionDialog(null,
"Would you like to play the login music?",
"Login music",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if (n == 0) {
Configuration.LOGIN_MUSIC = true;
} else if (n == 1){
Configuration.LOGIN_MUSIC = false;
} else {
Configuration.LOGIN_MUSIC_NEVER = true;
Configuration.LOGIN_MUSIC = false;
System.out.println("cancel");
System.out.println(Configuration.LOGIN_MUSIC_NEVER);
}
}
}
public static void main(String args[]) {
try {
if (Configuration.LOGIN_MUSIC_NEVER == false) {
checkForLoginMusic();
}
//System.out.println("The login music has been " + (Configuration.LOGIN_MUSIC ? "enabled" : "disabled"));
nodeID = 10;
portOff = 0;
setHighMem();
signlink.startpriv(InetAddress.getLocalHost());
clientSize = 0;
instance = new Client();
instance.createClientFrame(clientWidth, clientHeight);
//instance = new Jframe(args, clientWidth, clientHeight, false); uncomment if i want to add back the menu bar at top
} catch (Exception exception) {
}
}
I am now doing a simple sudoku game by JavaFX. And now I met some difficulty on dialog. I had create two scene, the menu scene contain only "new game" and "continue" button, main scene contain sudoku game. In the main scene I had created a check button to check if the gamer's answer is correct, where if it is incorrect then show a dialog like this img here and when it's correct,it might like this img here.
Then I found that CONFIRMATION ALERT is very similar. All I need to change is to the button's text and it's action,while when click retry to back to game scene and click quit to back to the main scene.
Now I know how to set action for the button in alert box, but i had some new question for that, I have no idea how to call the ventHandler<ActionEvent> in the statement.
Here is my code for two alert box
(source code from https://code.makery.ch/blog/javafx-dialogs-official/)
Alert right = new Alert(AlertType.CONFIRMATION);
right.setTitle("Checking Result");
right.setHeaderText(null);
right.setContentText("Your answer is correct. Would you like to start
again");
ButtonType restart = new ButtonType("Restart");
ButtonType quit = new ButtonType("Quit");
right.getButtonTypes().setAll(restart, quit);
Alert wrong = new Alert(AlertType.CONFIRMATION);
wrong.setTitle("Checking Result");
wrong.setHeaderText(null);
wrong.setContentText("Your answer is incorrect. Would you like to try
again");
ButtonType retry = new ButtonType("Retry");
wrong.getButtonTypes().setAll(retry, quit);
the code for actions
Optional<ButtonType> result = right.showAndWait();
if (result.isPresent() && result.get() == quit) {
stage.setScene(main_frame);
}else if(result.isPresent() && result.get() ==
restart) {// call the actionevent clears}
Optional<ButtonType> result = wrong.showAndWait();
if (result.isPresent() && result.get() == quit) {
stage.setScene(main_frame);
}else if(result.isPresent() && result.get() ==
retry) {// call the actionevent clears}
The code for eventhandler
final EventHandler<ActionEvent> clears = new EventHandler<ActionEvent>() {
#Override
public void handle(final ActionEvent event) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (digging_array[i][j] == 1) {
sudoku[i][j].setText(Integer.toString(final_Array[i][j]));
} else {
sudoku[i][j].setText("");
}
}
}
}
};
You did change the button type correctly regarding the right alert. Your last line does not change the buttons for the wrong alert. Replacing right with wrong will target the correct alert and thus change its buttons.
Checking which button was pressed can be done in multiple ways. Extract from the official documentation (https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html):
Option 1: The 'traditional' approach
Optional<ButtonType> result = alert.showAndWait();
if (result.isPresent() && result.get() == ButtonType.OK) {
formatSystem();
}
Option 2: The traditional + Optional approach
alert.showAndWait().ifPresent(response -> {
if (response == ButtonType.OK) {
formatSystem();
}
});
Option 3: The fully lambda approach
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> formatSystem());
instead of using ButtonType.OK you need to use your custom buttons.
EDIT
In your example you have to modify the code like this:
void clear() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (digging_array[i][j] == 1) {
sudoku[i][j].setText(Integer.toString(final_Array[i][j]));
} else {
sudoku[i][j].setText("");
}
}
}
}
Optional<ButtonType> result = right.showAndWait();
if (result.isPresent() && result.get() == quit) {
stage.setScene(main_frame);
} else if(result.isPresent() && result.get() == restart) {
clear()
}
Optional<ButtonType> result = wrong.showAndWait();
if (result.isPresent() && result.get() == quit) {
stage.setScene(main_frame);
} else if(result.isPresent() && result.get() == retry) {
clear()
}
In the linked tutorial, there is an example on how to set custom actions (I shortened it a bit):
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog with Custom Actions");
ButtonType buttonTypeOne = new ButtonType("One");
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOne){
// ... user chose "One"
} else {
// ... user chose CANCEL or closed the dialog
}
You can get the result (what the user clicked) via result.get() and check, which button was pressed (buttonTypeOne, buttonTypeCancel, ...).
When the user presses "One", you can now do something in the first body of the if statement.
In your code you are missing the showAndWait() call. If for example the user was right, you should do:
Observable<ButtonType> rightResult = right.showAndWait();
if (rightResult.isPresent()) {
if (rightResult.get() == restart) { //because "restart" is the variable name for your custom button type
// some action, method call, ...
} else { // In this case "quit"
}
}
Note, this is probably not the most elegant way (double if-statement) to do it. #Others feel free to edit my answer and put in a better way to do it.
I'm writing a CashRegister program and I'm currently working on the CashierView where I have added an option for the Cashier to input the amount of cash received by the customer. I now formatted it so that the user only can input numbers and 1 period. I now want to limit the numbers you can input after the period to two. I'm struggling to make this work.
I commented out one of the codes that I tried, but didn't work, incase it might be interesting.
Appreciate all the help!
Br,
Victor
private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
//boolean tail = false;
if ((Character.isDigit(c) || (c == KeyEvent.VK_BACKSPACE) || c == KeyEvent.VK_PERIOD)) {
int period = 0;
if (c == KeyEvent.VK_PERIOD) { //Allows only one period to be added to the textfield
//tail = false;
String s = getTextFieldCash();
int dot = s.indexOf(".");
period = dot;
if (dot != -1) {
evt.consume();
}
}
//. if (tail=true){ //This is the code that I tried to use to limit input after the period to two
// String x = getTextFieldCashTail();
// if (x.length()>1){
// evt.consume();
// }
// }
}
else {
evt.consume();
}
}
If you're dead set on doing this with a KeyEvent, here's one possible method:
private void jCashReceivedKeyTyped(java.awt.event.KeyEvent evt) {
char c = evt.getKeyChar(); //Allows input of only Numbers and periods in the textfield
if ((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || c == KeyEvent.VK_PERIOD)) {
String s = getTextFieldCash();
int dot = s.indexOf(".");
if(dot != -1 && c == KeyEvent.VK_PERIOD) {
evt.consume();
} else if(dot != -1 && c != KeyEvent.VK_BACK_SPACE){
String afterDecimal = s.substring(dot + 1);
if (afterDecimal.length() > 2) {
evt.consume();
}
}
}
}
Hope this helps. Just keep in mind that by listening to a KeyEvent, if someone copies and pastes values into your JTextField, this won't catch that. If you want to catch any possible type of input, you'll want to use a DocumentListener. If you're wondering how to use a DocumentListener, here is some code that shows how to use it on a JTextField.
I am creating a matching card application. That only allows the user to select two cards per round.
Where you see the bricks are where the buttons are and so i have added them to an arraylist, but im not sure how to make it so that they can only press 2 buttons until they press the guess button where it checks if they are a match.
https://pastebin.com/65NqJ0GK
private void card1ButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp = cards.get(0);
if (temp.equals("0")) {
card1Button.setIcon(a);
} else if (temp.equals("1")) {
card1Button.setIcon(b);
} else if (temp.equals("2")) {
card1Button.setIcon(c);
} else if (temp.equals("3")) {
card1Button.setIcon(d);
} else if (temp.equals("4")) {
card1Button.setIcon(e);
} else if (temp.equals("5")) {
card1Button.setIcon(f);
} else if (temp.equals("6")) {
card1Button.setIcon(g);
} else if (temp.equals("7")) {
card1Button.setIcon(h);
}
count++;
if (count == 1) {
c1 = Integer.parseInt(temp);
change[0] = 0;
} else if (count == 2) {
c2 = Integer.parseInt(temp);
change[0] = 0;
}
}
^^Here is an example of a button code.
Could someone show me some way to do it.
I am making a blackjack game and was wondering if I could make it so that I had two different actions on a single button.
This is what I have so far on the hit button, but instead of having the second card show on a double click, I want it to show the second card when you press the button again.
public void hit(MouseEvent event) {
if (event.getClickCount() == 1) {
card5 = deck.dealCard();
pcard3.setImage(card5.getImage());
}
if (event.getClickCount() == 2) {
card6 = deck.dealCard();
pcard4.setImage(card6.getImage());
}
}
You can have an iterator whose value can be increased on each click. And for different values set different functionalities. See the code
int i =0;
public void hit(MouseEvent event) {
if (i%2== 0) {
card5 = deck.dealCard();
pcard3.setImage(card5.getImage());
} else if (i%2 == 1) {
card6 = deck.dealCard();
pcard4.setImage(card6.getImage());
}
i++;
}