2

我正在做一项任务,我需要将华氏温度转换为摄氏温度。我已经创建了表单和 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;
     }
 }

非常感谢您的帮助。

4

1 回答 1

2

不,不要在您的 actionPerformed 方法中创建另一个 Part3Question1 对象:

public void actionPerformed(ActionEvent e)
{   
    Part3Question1 convert = new Part3Question1();
    double Farenheit = Double.parseDouble(convert.fahrenheitTB.getText());

是的,您可以创建一个 Part3Question1 对象,但要了解它与当前显示的 Part3Question1 对象完全无关,即当前实例,如果您愿意的话。

此外,即使您的代码工作正常,这也不是您调用 setText(...) 方法的方式:

fahrenheitTB.SetText = Celcius; // you're not even calling a method here!!

相反,只需调用您所在的当前 Part3Question1 对象的方法:

double farenheit = Double.parseDouble(fahrenheitTB.getText());

String.format("%.2f", someDoubleValue)如果您喜欢此工具,可以使用 或使用 DecimalFormat修剪转换结果。

于 2012-10-29T02:20:53.140 回答