La actualización del temporizador de Java Swing con la entrada de usuario

timerLad:

Así que actualmente estoy teniendo un problema con mi temporizador Java Swing pero primero déjame describir lo que estoy tratando de hacer.

Así que tengo una Swing GUI que actualiza un mapa con datos JSON cada número 'X' de segundos. La entrada del usuario Puede el número de segundos en un campo de texto y haga clic en un botón para iniciar la actualización del mapa. El mapa a continuación, actualizar mediante la consulta del JSON basado en la entrada.

Así que estoy usando un temporizador Swing para repetir un determinado evento de acción basado en la entrada del usuario. Se ve a continuación:

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

});

Cuando se puso en marcha el programa sea cual sea el tiempo que el usuario entra por primera vez funciona muy bien. Pero entonces si cambian la vez que el temporizador no cambia.

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

Tiene algo que ver con estas líneas, pero simplemente no puede resolverlo. Estoy tirando el valor numérico del campo de texto y se establece como el retraso en el temporizador. Pero sólo funciona la primera vez que se inicia el programa y no cuando se cambia.

Cualquier ayuda sería muy apreciada.

WJS:
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);
        });     
    }
}

Suponiendo que usted está familiarizado con los marcos y los paneles que saltará al JTextField y JTextArea.

  • el campo es donde el usuario escribe en el retraso. Se notificó el uso de un actionListener. Que la entrada es luego recuperada, se analiza como un int y establece el temporizador de retardo.
  • la zona es simplemente un lugar donde el temporizador escribe la salida.

Tenga en cuenta que en lugar de un evento cuando el usuario escribe la información, un botón se podrían utilizar en su lugar. El usuario escribe la información y luego hace clic en el botón. En ese caso, no habría necesidad de JTextField oyente. En lugar del oyente sería que el botón para comprobar el campo de texto.

Este es un ejemplo muy rudimentario para demostrar la interacción entre dos ActionListeners. Si el usuario escribe en otra cosa que un número se produce una excepción. Es posible que desee revisar la Tutoriales de Java , donde se habla de manejo de eventos y otras cosas que usted encontraría interesante.

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=349979&siteId=1
Recomendado
Clasificación