gpt4 book ai didi

java - 从 JTextField 中获取值并转换为 int

转载 作者:行者123 更新时间:2023-12-01 10:50:06 25 4
gpt4 key购买 nike

eqn.setABC() 接受三个整数,但 CoeffACoeffBCoeffCJTextFields。

如何从 JTextField 获取输入,将其转换为整数,然后将其提供给 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...");

}

}

最佳答案

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

Integer.parseInt(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.

关于java - 从 JTextField 中获取值并转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com