从JTextField获取值并转换为int

时间:2015-11-28 01:12:10

标签: java

Java新手

我已经尝试了很多次,但我似乎无法让它工作..我尝试阅读javadoc,但我并不完全理解它。

eqn.setABC();取三个整数,但CoeffA,CoeffB和CoeffC是Jtextfields。我只想从Jtextfields获取输入,将它们转换为int,并将其提供给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...");

}

}

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法从JTextField中提取整数:

Integer.parse.Int(jtextField.getText());

此命令包含两部分:

第一部分:

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

第二部分:

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