ActionListener 和 IF 语句出现问题

Trouble with ActionListener and an IF statement

我目前有两个问题,过去 3 小时我一直在努力解决这两个问题。

  1. 我无法让 input--; 递减 if input is not == to 0

  2. 程序为 运行 后,我无法让 JTextField input 更新我分配给它的值。我将在 运行 程序中输入 22 单击开始,它将转到 "test99"。 图片是我如何输入值 66 然后我按下开始并出现 test99 而不是test66

我希望我能够在您能够理解的程度上解释我的问题。我已经阅读了很多关于动作侦听器的文档,但目前这个想法对我来说不会点击。欢迎任何建设性的批评。

我也尽可能地简化了我的问题。

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();
        }
    });

}

}

我建议不要在函数中声明输入变量,而是在 class 中声明。否则你 运行 进入范围问题。示例:

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();
    }
});

我对你的代码有几点批评:

  1. 变量名应以小写字母开头,class变量名应以大写字母开头。
  2. int input = (int) (Double.parseDouble(Input.getText())); 为什么要使用 Double.parseDouble 然后转换为 int 而你只能使用 Integer.parseInt()
  3. "test99" 出现在您的 GUI 中而不是 "test66" 因为您将输入的文本 JTextField 设置为 99,然后解析该值 once 然后在你的计时器中使用它。你从不更新这个值所以它是总是 99。而不是这个你应该每次解析输入JTextField中的文本用户按下 "Start" 并更新计时器使用的 int 值。

请参阅下面我更正的解决方案:

import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class Test {

    private Test() {
        initialize();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(Test::new);
    }

    private void initialize() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        JPanel timePanel = new JPanel(new FlowLayout());

        timePanel.add(new JLabel("Time left: "));

        JLabel timeOutput = new JLabel("");
        timePanel.add(timeOutput);

        frame.add(timePanel, BorderLayout.CENTER);

        JPanel inputPanel = new JPanel(new FlowLayout());

        JButton startButton = new JButton("Start");

        JButton stopButton = new JButton("Stop");
        stopButton.setEnabled(false);

        JTextField timeField = new JTextField(5);

        inputPanel.add(startButton);
        inputPanel.add(stopButton);
        inputPanel.add(timeField);

        frame.add(inputPanel, BorderLayout.SOUTH);

        Timer timer = new Timer();

        startButton.addActionListener(e -> {

            startButton.setEnabled(false);
            stopButton.setEnabled(true);

            timer.scheduleAtFixedRate(new TimerTask() {

                int time = Integer.parseInt(timeField.getText());

                @Override
                public void run() {
                    if(time < 0) timer.cancel();
                    timeOutput.setText(String.valueOf(time--));
                }
            }, 0, 1000);
        });

        stopButton.addActionListener(e -> {
            timer.cancel();
            stopButton.setEnabled(false);
            startButton.setEnabled(true);
            timeOutput.setText("");
        });

        frame.pack();
        frame.setVisible(true);
    }
}