java按钮1。setButton(false)将不会与我的其他代码链接
说明: 嗨,我正在创建我的点击游戏,我不知道为什么我的按钮1。setEnabled(假);代码不会链接到我的JButton按钮1=新JButton(“黑客级别:”)。我用了两个按钮。第一个按钮启动计时器并计算单击/空格键按下的次数。10秒结束后,按钮将自动禁用。第二个按钮重置单击次数并启用第一个按钮
问题: 因为我使用了两个不同的按钮,所以我必须使用JButton,它不会使它链接到按钮1。setEnabled(假);密码我怎样把它连接起来
when the timer runs out, set button1 to disable screenshot . button1 screenshot 这是代码中存在问题的部分:
public TestPane() {
new GridLayout(0, 1); // 0 rows, 1 column
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
timer.stop();
**button1.setEnabled(false);**<<<<<<<<<<<<<<<<<<<<
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss.SSS");
label.setText(df.format(duration - clockTime));
}
});
timer.setInitialDelay(0);
// \/ label wrapper \/ TITLE
label = new JLabel("Hacker GUI v1", JLabel.CENTER); // label text
label.setFont(new Font("Roboto", Font.PLAIN, 20)); // font size
add(label); // add the label
// /\ label wrapper /\
// \/ label wrapper \/ DESCRIPTION
label = new JLabel("To hack, click on the button or press space while on the window.", JLabel.CENTER); // text label
label.setFont(new Font("Roboto", Font.PLAIN, 15)); // font size
label.setHorizontalTextPosition(JLabel.CENTER);
add(label); // add the label
// /\ label wrapper /\
// \/ button wrapper \/ BUTTON PLAY
Dimension d = new Dimension(215, 30); // first number is length (left to right), second number is heigh (top to bottom).
**JButton button1 = new JButton("Hacker Level: "); // button text**<<<<<<<<<<<<
button1.setPreferredSize(d); // size of button relitive to dimension d
button1.setFont(new Font("Roboto", Font.PLAIN, 15)); //font size of button
button1.addActionListener( new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
count++; //count in positive integers
button1.setText("Hacker Level: " + count); //text change when action preformed
if (!timer.isRunning()) {
startTime = -1;
timer.start();
}
}
});
add(button); //add the button
// /\ button wrapper /\
// \/ button wrapper \/ BUTTON RESET
Dimension a = new Dimension(215, 30); // first number is length (left to right), second number is heigh (top to bottom).
JButton button2 = new JButton("Reset Score"); // button text
button2.setPreferredSize(a); // size of button relitive to dimension d
button2.setFont(new Font("Roboto", Font.PLAIN, 15)); //font size of button
button2.addActionListener( new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
count++; //count in positive integers
button1.setText("Hacker Level: " + count); //text change when action preformed
button1.setEnabled(true);
}
});
add(button); //add the button
// /\ button wrapper /\
# 1 楼答案
在使用按钮1之前,您需要声明并设置它。所以试着把这几行移到计时器行之前的某个地方
# 2 楼答案
您正在定义一个局部变量。局部变量不能用于其他方法
您需要将“button1”定义为实例变量(与定义标签的方式相同):