How can I disable a jtextfield for ten seconds in java

1

Hi, could you tell me which is the best way to disable a jtextfield after the user press enter for a certain time like 10 sec

Thanks

    
asked by user3100662 28.08.2018 в 05:34
source

2 answers

0

One possible solution is to create a timer

public class Tiempo extends JFrame {

    private JTextField txtTexto;
    private Timer timer, cuenta;
    private JLabel lbCuenta;
    private int contador;

    public Tiempo() throws HeadlessException {
        setSize(400, 400);
        setDefaultCloseOperation(3);
        setLocationRelativeTo(null);
        setLayout(null);

        txtTexto = new JTextField(50);
        txtTexto.setBounds(100, 100, 180, 20);
        contador = 0;
        lbCuenta = new JLabel("Segundos: " + contador);
        lbCuenta.setBounds(100, 80, 80, 20);
        //Se crea el evento para el enter
        txtTexto.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtTexto.setEnabled(false);//Se desactiva el JTextField
                txtTexto.repaint();//Se repinta para actualizar
                timer.start();//Comienza la cuenta
                cuenta.start();//Esto es solo para la cuenta de los seg
            }
        });

        //Es solo para mostrar la cuenta de los segundos
        cuenta = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                contador++;
                lbCuenta.setText("Segundos: " + contador);
                if (contador > 9) {
                    cuenta.stop();
                }
            }
        });

        //El timer se activa despues de 10000 milisegundos equivalente a 10s
        timer = new Timer(10000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                txtTexto.setEnabled(true);//Despues de los 10s se activa
                txtTexto.repaint();//Se repinta para actualizar
                timer.stop();//Se detiene el timer
            }
        });

        add(lbCuenta);
        add(txtTexto);

        setVisible(true);
    }

    public static void main(String[] args) {
        new Tiempo();
    }
}

Any questions, you tell me.

Greetings.

    
answered by 28.08.2018 / 07:16
source
1

Try a Timmer. Something like that would be worth it.

.....
    textField.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                  deshabilitar();
                }
            });
....
void deshabilitar()
{
textField.setEnabled(false);
javax.swing.Timer timer = new javax.swing.Timer(100000, new ActionListener ()
{
    public void actionPerformed(ActionEvent e)
    {
            textField.setEnabled(true);
     }
}); 
}

More examples at: link

    
answered by 28.08.2018 в 07:10