Java:actionlistener问题并检索文本框输入

时间:2012-10-29 02:17:03

标签: java swing awt jbutton actionlistener

我正在进行一项任务,我需要将华氏温度转换为摄氏温度。我创建了表单和actionlistener按钮。

我遇到的问题是将代码放在actionlistener中以检索文本框输入并进行计算并将其修剪到两个小数位并在Celsius文本框中发布答案。

这是我到目前为止所做的:

 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;
     }
 }

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

不,不要在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。

相关问题