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

Asked

Viewed 1,129 times

4

My problem is that I put a button so that when it was clicked, add the value 1 in JTextField.

However, when I click again, it replaces the value, and what I wanted is for it to add another 1 like, I once click from there on the textfield was going to stay 1, then I click again and it was 11, then I click again and would stay 111 and so on. How do I do this?

1 answer

3


Just do a treatment inside 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 the example below:

String textoAnterior = seuTextField.getText();


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

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

inserir a descrição da imagem aqui

  • See, man, I help a lot.

  • @Pauloaleixo if the answer helped you, you mark it as accepted by clicking on v the left of it will thus serve as a reference for other users. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.