我正在做一项作业,需要将华氏温度转换为摄氏度。我已经创建了表单和 Action 监听器按钮。
我遇到的问题是将代码放在 Action 监听器中以检索文本框输入并进行计算,并将其修剪到小数点后两位并将答案发布在摄氏文本框中。
这是我到目前为止所拥有的:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Part3Question1 extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrame mp = new Part3Question1();
mp.show();
}
public Part3Question1() {
setTitle("My Farenheit to Celsius Converter");
setSize(400, 250);
setLocation(400, 250);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
JLabel fahrenheitLabel = new JLabel();
fahrenheitLabel.setText("Fahrenheit: ");
fahrenheitLabel.setBounds(130, 40, 70, 20);
add(fahrenheitLabel);
JTextField fahrenheitTB = new JTextField();
fahrenheitTB.setHorizontalAlignment(fahrenheitTB.RIGHT);
fahrenheitTB.setBounds(200, 40, 70, 20);
add(fahrenheitTB);
JLabel celsiusLabel = new JLabel();
celsiusLabel.setText("celsius: ");
celsiusLabel.setBounds(149, 60, 70, 20);
add(celsiusLabel);
Color color = new Color(255, 0, 0);
JTextField celsiusResultsTB = new JTextField();
celsiusResultsTB.setText("resultbox ");
celsiusResultsTB.setHorizontalAlignment(celsiusResultsTB.CENTER);
celsiusResultsTB.setForeground(color);
celsiusResultsTB.setEditable(false);
celsiusResultsTB.setBounds(200, 60, 70, 20);
add(celsiusResultsTB);
JButton convertButton = new JButton("Convert");
convertButton.setBounds(10, 100, 364, 80);
add(convertButton);
convertButton.addActionListener(this)
}
public void actionPerformed(ActionEvent e) {
Part3Question1 convert = new Part3Question1();
double Farenheit = Double.parseDouble(convert.fahrenheitTB.getText());
double = Celcius(5.0 / 9.0) * (Farenheit - 32);
convert.fahrenheitTB.SetText = Celcius;
}
}
非常感谢您的帮助。
最佳答案
不,不要在 actionPerformed 方法内创建另一个 Part3Question1 对象:
public void actionPerformed(ActionEvent e)
{
Part3Question1 convert = new Part3Question1();
double Farenheit = Double.parseDouble(convert.fahrenheitTB.getText());
是的,您可以创建一个 Part3Question1 对象,但请注意,它将与当前显示的 Part3Question1 对象完全无关,即当前实例,即“this”,如果您愿意的话。
此外,即使您的代码工作正常,这也不是您调用 setText(...) 方法的方式:
fahrenheitTB.SetText = Celcius; // you're not even calling a method here!!
只需调用您所在的当前 Part3Question1 对象的方法即可:
double farenheit = Double.parseDouble(fahrenheitTB.getText());
您可以使用String.format("%.2f", someDoubleValue)
修剪转换结果,如果您喜欢此工具,也可以使用DecimalFormat。
关于Java : issue with actionlistener and retrieving textbox input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13115129/