how do I get a value from the textField and pass it to an int variable?

0

How do I get the value typed in a field of type JTextField and pass to a variable, so I can do calculations later?

I tried to use getText() , but the variables because they are int , do not receive the content. I wanted to get the numbers typed.

Example:

package teste;

import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class teste02  extends JFrame 
{

    private JTextField field = new JTextField();
    private JTextField field02 = new JTextField();
    private int valor1, valor2;

    public teste02()
    {
        setTitle("Exemplo"); 
        add(campos());
        setSize(450, 350);     
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    private JComponent campos()
    {
        JPanel painelMontaTela = new JPanel();
        painelMontaTela.setLayout(null);

        JLabel label01 = new JLabel();
        label01.setText("Digite o 1º número: ");
        painelMontaTela.add(label01);
        label01.setBounds(35, 30, 200, 25);
        painelMontaTela.add(field);
        field.setBounds(150, 30, 200, 25);        

        JLabel label02 = new JLabel();
        label02.setText("Digite o 2º número: ");
        painelMontaTela.add(label02);
        label02.setBounds(35, 75, 200, 25);
        painelMontaTela.add(field02);
        field02.setBounds(150, 75, 200, 25);

        JLabel label = new JLabel();
        painelMontaTela.add(label);
        label.setBounds(80, 160, 100, 25);
        label.setText("Valors: ");

        painelMontaTela.setBounds(1, 1, 495, 340);
        return painelMontaTela;
    }       

    public void fazCalculo()
    {
        int x;
        x =  valor1 + valor2;
    }

    public static void main(String[] args)
    {
        teste02 t = new teste02();                
    }
}
    
asked by anonymous 17.03.2017 / 06:50

1 answer

2

Just do the parse for int:

try{

    valor1 =  Integer.parseInt(field.getText());
    valor2 = Integer.parseInt(field02.getText());
}catch(NumberFormatException ex) {
   //cairá aqui se a string não for um valor 
   //que possa ser convertido em inteiro
}
    
17.03.2017 / 11:27