【发布时间】:2017-06-19 19:12:03
【问题描述】:
This picture is all my code for the pop-ups I currently have.
我想这样当用户输入他们的名字时(如果他们愿意,如果不是,则默认为玩家 1/玩家 2)并且他们输入了一个数字,它会给出另一个弹出窗口,说他们不能输入数字。
【问题讨论】:
This picture is all my code for the pop-ups I currently have.
我想这样当用户输入他们的名字时(如果他们愿意,如果不是,则默认为玩家 1/玩家 2)并且他们输入了一个数字,它会给出另一个弹出窗口,说他们不能输入数字。
【问题讨论】:
您需要在 JOptionPane 中使用 JTextField。本质上,您需要创建一个 JTextField,将 KeyListener 添加到该字段,并在该字段中显示一个 messageDialog。如果我们使用inputDialog,将显示两个字段。我已经开发了下面的代码。
JTextField field = new JTextField("Player 1 Name"); //Create a new JTextField with the text "Player 1 Name"
field.addKeyListener(new KeyListener() { //Add a KeyListener
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) { //Called when key is pressed
String input = Character.toString(e.getKeyChar()); //Create string input which is equal to the key pressed
if(input.equals("1") || input.equals("2") || input.equals("3") || input.equals("4") || input.equals("5") || input.equals("6") || input.equals("7") || input.equals("8") || input.equals("9") || input.equals("0")){ //If the string equals any number
JOptionPane.showMessageDialog(null, "Numbers are not allowed!", "Error", JOptionPane.ERROR_MESSAGE); //Show a message dialog notifying the user
field.setText(field.getText().substring(0, field.getText().length() - 1)); //Eliminate the number inputed
}
}
@Override
public void keyReleased(KeyEvent e) {
}
});
JOptionPane.showMessageDialog(null, field, "Player Name", JOptionPane.INFORMATION_MESSAGE) //Show MessageDialog with the input field as the JTextField
您可以为所有对话框使用相同的 JTextField,这样您就不必复制代码两次。希望这有帮助!
【讨论】: