okButton.addSelectionListener(newSelectionAdapter(){publicvoidwidgetSelected(finalSelectionEvente){//点击OK事件booleantf=true;//记录用户输入是否正确if(text.getText().leng...
okButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(final SelectionEvent e) {// 点击OK事件
boolean tf = true; //记录用户输入是否正确
if (text.getText().length() == 0){
text.setFocus();
return;
}
if (text.getText().length() == 4) { // 输入长度为四
// 不能输入重复的数字
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++)
if ((text.getText().charAt(i)) == (text.getText()
.charAt(j))) {
JOptionPane.showMessageDialog(null,
"Wrong Input1 !", "Error",
JOptionPane.ERROR_MESSAGE);
i = 5; // 跳出整个循环
tf = false;
break;
}
}
} else {
tf = false;
JOptionPane.showMessageDialog(null, "Wrong Input!",
"Error", JOptionPane.ERROR_MESSAGE);
}
if (tf) {
int num = 0;
try {
num = Integer.parseInt(text.getText());
if (num != 0) {
list.add(text.getText() + "--------"
+ guess.getMod(text.getText()) + "\n");
if (guess.getMod(text.getText()).equals("4A0B")) {
list.add("congratulations!");
text.setText("");
list.add("click new to start a new game!");
guess = new NumberGuess();
}
}
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "Wrong Input!",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
text.setText("");
}
});
text.addKeyListener(new KeyAdapter() {
public void keyPressed(final KeyEvent e) {
if (e.keyCode == 13){
//请写出这里的代码。。。
}
}
});
事情就是有个button点击。已经写好了。现在text里按enter键要实现button按下的相同工能。
代码很长。如何重用。
展开