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