在IDE中运行我的程序时出现NullPointerException错误

时间:2017-10-20 15:06:08

标签: java swing button nullpointerexception jlabel

我有一个奇怪的问题。我的IDE说我的代码是正常的,但是当我尝试运行它时,它表示发生了错误并且程序没有运行。我已经仔细阅读了代码,但我根本不知道该怎么做才能让它运转起来。我希望你能帮我解决这个问题。提前谢谢。

  package twobuttons;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class TwoButtons extends JFrame implements ActionListener {

    JButton button1;
    JButton button2;
    JLabel label;

    public static void main(String[] args){
     new TwoButtons();


    }
    public TwoButtons(){
        this.setTitle("Dos botones");
        this.setSize(400,400);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());

        button1.setText("hola");
        button1.addActionListener(this);
        button1.setActionCommand("hola");

        button2.setText("Te odio.");
        button2.addActionListener(this);
        button2.setActionCommand("Te odio.");

        button1.add(this);
        button2.add(this);
        this.setVisible(true);


    } 


    @Override
    public void actionPerformed(ActionEvent e) {
        String command= e.getActionCommand();

        if (e.getActionCommand().equals("hola")){
           JOptionPane.showMessageDialog(this.getComponent(0), "Espero que tengas un buen día");  
        } else {
            JOptionPane.showMessageDialog(this.getComponent(0), "Odio mi vida");
        }
    }}

我得到的错误是:

Exception in thread "main" java.lang.NullPointerException
    at twobuttons.TwoButtons.<init>(TwoButtons.java:28)
    at twobuttons.TwoButtons.main(TwoButtons.java:18)
C:\Users\Juan\Desktop\Informatik 12\TwoButtons\nbproject\build-impl.xml:1040: The following error occurred while executing this line:
C:\Users\Juan\Desktop\Informatik 12\TwoButtons\nbproject\build-impl.xml:805: Java returned: 1
BUILD FAILED (total time: 1 second)   

0 个答案:

没有答案