我正在尝试用gui制作一个三角形区域计算器,但是当我编译它时,我一直得到这个奇怪的错误

时间:2013-12-21 09:02:01

标签: java swing user-interface nullpointerexception

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class FirstGui extends JFrame {

    int num1;
    int num2;
    int num3;
    //Buttons 'n' stuff
    private JLabel label1;
    private JLabel label2;
    private JLabel label3;
    private JRadioButton button;
    private JButton calculate;
    private JTextField textfield1;
    private JTextField textfield2;
    //Buttons 'n' stuff

    public static void main (String args[]) {
        FirstGui gui = new FirstGui();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setSize(200, 200);
        gui.setVisible(true);
        gui.setTitle("T Calc");
    }

    public FirstGui(){
        setLayout(new FlowLayout());

        label1 = new JLabel ("Triangle Base");
        add(label1);

        textfield1 = new JTextField (15);
        add(textfield1);

        label2 = new JLabel ("Triangle Height");
        add(label2);

        textfield2 = new JTextField (15);
        add(textfield2);

        calculate = new JButton ("Calculate!");
        add(calculate);

        label3 = new JLabel ("Waiting for calculation...");
        add(label3);


        getvalue1 getvalue1 = new getvalue1();
        textfield1.addActionListener(getvalue1);

        getvalue2 getvalue2 = new getvalue2();
        textfield2.addActionListener(getvalue2);

        event event = new event();
        button.addActionListener(event);
    }


    public class getvalue1 implements ActionListener {
        public void actionPerformed(ActionEvent getvalue1){
            num1 = Integer.parseInt(textfield1.getText());

        }
    }

    public class getvalue2 implements ActionListener {
        public void actionPerformed(ActionEvent getvalue2){
            num2 = Integer.parseInt(textfield2.getText());

        }
    }
    public class event implements ActionListener {
        public void actionPerformed(ActionEvent event){
            num3 = 1/2 *num1*num2;
            label3.setText(String.valueOf(num3));
        }

    }

}

所以是的,这就是代码...... 这是我编译时遇到的问题:

Exception in thread "main" java.lang.NullPointerException
    at FirstGui.<init>(FirstGui.java:56)
    at FirstGui.main(FirstGui.java:20)

我不知道出了什么问题。 它真的很烦人,我不确定它是否是编译器...帮助! 这个错误并没有多大帮助。

1 个答案:

答案 0 :(得分:3)

您尚未在代码中的任何位置初始化button。在尝试调用任何方法之前,您需要执行此操作。

button = new JRadioButton("Your text here");

更重要的是,我看不到你正在使用该组件的任何其他地方。您尚未将其添加到框架中。你的意思是将事件添加到计算按钮吗?