How to add values in the JTextField via the button without deleting the previous value?

4

My problem is that I placed a button so that when it was clicked, I would add the value 1 to JTextField .

But when I click again, it replaces the value, and what I wanted was for it to add another type 1 , I click once on the textfield it would be 1 , hence I click new and ia is 11 , so I click again and it will 111 and so on. How do I do this?

    
asked by anonymous 01.01.2017 / 21:39

1 answer

3

Just do a treatment within the actionPerformed of your button, capturing the current value of the field and incrementing 1 (string, not integer), always checking the current status (if it already has data or is null / empty) before incrementing, as in the example below:

String textoAnterior = seuTextField.getText();


if(textoAnterior == null || textoAnterior.isEmpty()){
    seuTextField.setText("1");
} else {
    seuTextField.setText(textoAnterior + "1");
}

See this snippet working in the example below:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JTextFieldTest {

    public void start(){
        final JTextField tf = new JTextField(15);
        JButton botao = new JButton("Concatenar");

        botao.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent event){

                String textoAnterior = tf.getText();
                //verifica se o campo está vazio ou nulo para evitar
                // exceções por incremento a valores nulos ou perda
                //dos dados já digitados
                if(textoAnterior == null || textoAnterior.isEmpty()){
                    tf.setText("1");
                } else {
                    tf.setText(textoAnterior + "1");
                }
            }
        });

        JPanel panel = new JPanel();
        panel.add(tf);
        panel.add(botao);


        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(250, 150);
        frame.setVisible(true);
        tf.requestFocus();
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JTextFieldTest().start();
            }
        });
    }
}

    
01.01.2017 / 21:43