我目前遇到两个问题,过去 3 小时我一直在尝试解决这两个问题。
如果输入不 == 为 0,我无法让
input--;
递减程序运行后,我无法获取
JTextField 输入
来更新我分配给它的值。我在运行程序中输入 22 单击开始,它将转到“test99”。 图片是我如何输入值 66 然后按下开始键并出现 test99 而不是 test66 的示例
我希望我能够在您能够理解的程度上解释我的问题。我已经阅读了很多有关 Action 监听器的文档,但目前这个想法不适合我。欢迎任何建设性的批评。
我还尽可能地简化了我的问题。
package test;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JButton;
public class test {
private JFrame frame;
private JButton btnStart;
/**
*
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
JLabel Output = new JLabel("Time left: ");
Output.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Output, BorderLayout.CENTER);
JTextField Input = new JTextField();
btnStart = new JButton("start");
Input.setText("99");
int input = (int) (Double.parseDouble(Input.getText()));
Input.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Input, BorderLayout.SOUTH);
Input.setColumns(10);
frame.getContentPane().add(btnStart, BorderLayout.NORTH);
frame.setBounds(100, 100, 300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Input.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Timer t = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Output.setText("test" + input);
if (input == 0) {
((Timer) e.getSource()).stop();
}
input--;
}
});
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
t.start();
}
});
}
}
最佳答案
我建议不要在函数中声明输入变量,而是在类中声明。否则你会遇到范围问题。示例:
public class test {
private JFrame frame;
private JButton btnStart;
private int input;
private JTextField Input;
//...
}
应该解决这个问题:)
我不太确定第二个问题,但如果您想从输入的值开始倒计时,则必须更新您的操作监听器:
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = (int) (Double.parseDouble(Input.getText()));
t.start();
}
});
关于java - ActionListener 和 IF 语句出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38203466/