justinleesf
justinleesf

Reputation: 3

Get values out from JTextField and convert to int

eqn.setABC() takes in three integers, but CoeffA, CoeffB, and CoeffC are JTextFields.

How can I take the input from the JTextFields, convert it to ints, and feed it to eqn.setABC()?

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

public class FactorQuadraticUI extends JFrame implements ActionListener {

public JTextField coeffA;
public JTextField coeffB;
public JTextField coeffC;
public JTextField factors; //contains answer in form (px+q)(rx+s)
public JButton findFactors;
public QuadraticEqn eqn;
static final long serialVersionUID = 12345L;

public FactorQuadraticUI(QuadraticEqn e) {
    super("Quadratic Equation Factor Finder");
    
    eqn = e;
    
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
                
    JPanel eqnArea = new JPanel(new FlowLayout());
    coeffA = new JTextField(2);
    eqnArea.add(coeffA);
    eqnArea.add(new JLabel("x^2 +"));
    coeffB = new JTextField(2);
    eqnArea.add(coeffB);
    eqnArea.add(new JLabel("x +"));
    coeffC = new JTextField(2);
    eqnArea.add(coeffC);
    
    
    //////////JTextField f1 = new JTextField("-5");
    
    //control button:  find factors
    findFactors = new JButton("factor!");
    findFactors.addActionListener(this);
    eqnArea.add(findFactors);
    
    c.add(eqnArea);
    
    //output area
    factors = new JTextField(27);
    factors.setEditable(false);
    c.add(factors);
    
    this.setBounds(100, 100, 350, 100);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setVisible(true);
 }

public void actionPerformed(ActionEvent e) {
    //"factor" button pressed
    
    
    //how to get the values out 
    // and make them ints
     
    eqn.setABC(coeffA, coeffB, coeffC);
    
    factors.setText(eqn.toString()  + " = " + eqn.getQuadraticFactors()     );
     
    
    factors.setText("testing...");
    
}

}

Upvotes: 0

Views: 63

Answers (1)

Jaskaranbir Singh
Jaskaranbir Singh

Reputation: 2034

You can extract integers from JTextField using:

Integer.parseInt(jtextField.getText());

This command has two parts:

First part:

JTextField.getText() // This gets text from text field. Ofcourse replace "JTextField" with your textfield's name.

Second part:

Integer.parseInt(..) // This gets/parses the integer values in a string. We are inputting the string here from above step.

Upvotes: 1

Related Questions