简体   繁体   English

使用用户输入更新 Java Swing 计时器

[英]Updating Java Swing Timer with User Input

So I am currently having a problem with my Java Swing timer but first lemme describe what I am trying to do.所以我目前在使用 Java Swing 计时器时遇到问题,但首先让我描述一下我正在尝试做什么。

So I have a Swing GUI that updates a map with JSON data every 'X' number of seconds.所以我有一个 Swing GUI,它每“X”秒更新一次带有 JSON 数据的地图。 The user can input the number of seconds into a text field and then click a button to start updating the map.用户可以在文本字段中输入秒数,然后单击按钮开始更新地图。 The map will then update by querying the JSON based on the input.然后,地图将通过根据输入查询 JSON 来更新。

So I am using a Swing timer to repeat a certain action event based on the input of the the user.所以我使用 Swing 计时器根据用户的输入重复某个动作事件。 Seen below:见下图:

clickOkButton.addActionListener(e1 -> {

  ActionListener actionListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
      String url = "";
      url = new_text.getText();

      layer[0] = (RenderableLayer) geo.createLayerFromSource(url);
      appFrame.getWwd().getModel().getLayers().set(20, layer[0]);
      ltree.getModel().refresh(appFrame.getWwd().getModel().getLayers());


    }
  };



  int time = Integer.parseInt(queryTime.getText());
  Timer timer = new Timer(time * 1000, actionListener);
  timer.setRepeats(true);
  //timer.setDelay(1);
  timer.start();

  d.setVisible(false);
  //System.out.println(text);

});

When the program is launched whatever time the user enters first works great.当程序启动时,无论用户首先进入什么时间,效果都很好。 But then if they change the time the timer doesn't change.但是,如果他们更改时间,则计时器不会更改。

  int time = Integer.parseInt(queryTime.getText());
  Timer timer = new Timer(time * 1000, actionListener);

It has something to do with these lines but I just can't figure it out.它与这些线条有关,但我无法弄清楚。 I'm pulling the numerical value from the text field and setting it as the delay in the timer.我正在从文本字段中提取数值并将其设置为计时器中的延迟。 But it only works the first time the program is launched and not when it is changed.但它仅在程序第一次启动时有效,而在更改时无效。

Any help would be much appreciated.任何帮助将非常感激。

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class SwingTimerDemo extends JPanel {


    final static int height = 500;
    final static int width = 500;
    final static String title = "default title";

    JFrame frame = new JFrame(title);
    JTextField field = new JTextField(10);
    JTextArea area = new JTextArea(50,20);


    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new SwingTimerDemo().start());
    }
    public SwingTimerDemo() {
        frame.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        // add this panel to the frame
        frame.add(this);
        // add the JTextArea and JTextField to the panel
        add(area);
        add(field);
        setPreferredSize(
                new Dimension(500, 500));
        frame.pack();
        // center the frame on the screen
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    public void start() {
        // append the string to the JTextArea
        Timer t = new Timer(0, (ae)->area.append("Processing...\n"));

        // set the inter-event delay to 2 seconds
        t.setDelay(2000);
        // start the timer
        t.start();
        field.addActionListener(ae->{
            String text = field.getText();
            field.setText(""); // "erase" the text
            // convert to a number
            int delay = Integer.parseInt(text);
            // reset the timer delay
            t.setDelay(delay*300);
        });     
    }
}

Assuming you are familiar with Frames and Panels I will skip to the JTextField and JTextArea.假设您熟悉框架和面板,我将跳到 JTextField 和 JTextArea。

  • the field is where the user types in the delay.该字段是用户输入延迟的地方。 It is notified using an actionListener .使用actionListener通知它。 That input is then retrieved, parsed as an int and sets the timer delay.然后检索该输入,将其解析为 int 并设置计时器延迟。
  • the area is simply a place where the timer writes the output.该区域只是计时器写入输出的地方。

Note that instead of an event when the user types in information, a button could be used instead.请注意,可以使用按钮代替用户输入信息时的事件。 The user types in the information and then clicks the button.用户输入信息,然后单击按钮。 In that case, there would be no need for JTextField listener.在这种情况下,就不需要 JTextField 侦听器。 Instead the listener would be for the button to check the text field.相反,侦听器将用于按钮检查文本字段。

This is a very rudimentary example to demonstrate the interaction between two actionListeners.这是一个非常基本的示例,用于演示两个 actionListener 之间的交互。 If the user types in anything but a number an exception will be thrown.如果用户输入除数字以外的任何内容,则会引发异常。 You may want to check out the Java Tutorials where they talk about event handling and other things that you would find interesting.您可能想查看Java 教程,其中讨论了事件处理和其他您会感兴趣的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM