我正在做一项任务,我需要将华氏温度转换为摄氏温度。我已经创建了表单和 actionlistener 按钮。
我遇到的问题是将代码放在 actionlistener 中以检索文本框输入并进行计算并将其修剪到小数点后两位并将答案发布在摄氏度文本框中。
这是我到目前为止所拥有的:
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;
}
}
非常感谢您的帮助。