改写一个包含按钮、文本框的窗口程序
加上新按钮之后怎么设置新的监听,addActionListener和原有的“确认”是一样的话好像不能用
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WindowGuess extends JFrame implements ActionListener {
int number;
byte count;
JLabel hintLabel;
JTextField inputGuess;
JButton buttonGetNumber,buttonEnter;
public WindowGuess() {
number = (int)(Math.random()*100)+1;
setLayout(new FlowLayout());
buttonGetNumber = new JButton("请猜测一个数范围是(1~100)");
add(buttonGetNumber);
hintLabel = new JLabel("请输入你的猜测:",JLabel.CENTER);
hintLabel.setBackground(Color.cyan);
inputGuess = new JTextField(10);
add(hintLabel);
add(inputGuess);
buttonEnter = new JButton("确定");
add(buttonEnter);
buttonEnter.addActionListener(this);
buttonGetNumber.addActionListener((e)->{
number = (int)(Math.random()*100)+1;
count = 0;
hintLabel.setText("输入你的猜测:");
inputGuess.setText(null);
buttonEnter.setEnabled(true);
});//Lambada
Font font = new Font("宋体",Font.PLAIN,30);
//SetFont.setFont(font,hintLabel,buttonEnter,buttonGetNumber,inputGuess);
setBounds(100,100,150,150);
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
validate();
}
public void actionPerformed(ActionEvent e) {
buttonGetNumber.setEnabled(false);//只有猜对了才可以重新来set一个number
int guess = 0;
try { guess=Integer.parseInt(inputGuess.getText());
count++;
if(guess==number) {
hintLabel.setText("猜对了(猜测次数:"+count+")");
buttonEnter.setEnabled(false);
buttonGetNumber.setEnabled(true);
}
else if(guess>number) {
hintLabel.setText("猜大了(猜测次数:"+count+")");
inputGuess.setText(null);
}
else if(guess<number) {
hintLabel.setText("猜小了(猜测次数:"+count+")");
inputGuess.setText(null);
}
}
catch(NumberFormatException event) {
hintLabel.setText("请输入数字字符");
}
}
}
public class Example9_14 {
public static void main(String args[]) {
WindowGuess win = new WindowGuess();
win.setTitle("猜数字");
win.setBounds(10,10,460,360);
}
}