What's wrong with my Java code?

筅森魡賤 提交于 2019-12-13 21:42:49

问题


I am showing my code; I am having problem with to display an output on submit button click. At first, I was not able to use local varible in my inner class, but when I search some guy said use final with it. I did, but still not getting any output this is simple formula behind this button.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JOptionPane;

public class FtoC {

    public static void main(String[] args) {
        Frame frm = new Frame();
        Label lb = new Label("Calculater");
        frm.setSize(500, 300);
        frm.setVisible(true);
        frm.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

        Panel obj = new Panel();
        Panel obj2 = new Panel();
        Label F = new Label("F");
        final TextField Ft = new TextField(10);
        Label C = new Label("C");
        TextField Ftc = new TextField(10);
        obj.setLayout(new GridLayout(1, 1));
        obj.add(F);
        obj.add(Ft);
        obj.add(C);
        obj.add(Ftc);
        final String sFt = Ft.getText();
        Button submit = new Button("Calculate");
        submit.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                double Ftn = Double.parseDouble(sFt);
                double result = (Ftn - 32) * 5 / 9;
                //System.out.println(Ft);
                JOptionPane.showMessageDialog(null, result);
            }
        });

        obj.add(submit);
        obj2.add(obj);
        frm.add(obj2, BorderLayout.NORTH);
    }
}

回答1:


final String sFt=Ft.getText();

The problem here is your assigning the value from the field BEFORE the user has ever entered any text.

Instead of making the String final, get the text from the field when the action event is fired.

While I hope this is a test program, I'd suggest that you should create your self a custom panel (a class that extends from JPanel), make the form elements private members. Form there you will greatly simply your design and reduce your problems




回答2:


You don't want the value of the Ft widget right after construction, don't you? You want, whatever is there when the button is clicked, right? So, move the

String sFt=Ft.getText()

line into the action listener.




回答3:


In addition, pack() your frame and call setVisible() last:

public static void main(String[] args) {
    ...
    frm.add(obj2, BorderLayout.NORTH);
    frm.pack();
    // frm.setSize(500, 300); // optional
    frm.setVisible(true);
}


来源:https://stackoverflow.com/questions/12552440/whats-wrong-with-my-java-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!