2

華氏を摂氏に変換する必要がある課題に取り組んでいます。フォームと actionlistener ボタンを作成しました。

私が問題を抱えているのは、アクションリスナー内にコードを配置して、テキストボックスの入力を取得し、計算を行い、小数点以下2桁まで切り詰めて、摂氏のテキストボックスに回答を投稿することです.

これは私がこれまでに持っているものです:

 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 オブジェクト (現在のインスタンスである「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 を使用して、変換の結果をトリミングできます。

于 2012-10-29T02:20:53.140 に答える