有人可以帮我为什么我的简单GUI代码无法运行吗?

时间:2020-04-25 16:47:36

标签: java

这是我的代码


import javax.swing.JFrame;
public class Server
{
//-----------------------------------------------------------------
// Creates and display the main program frame.
//-----------------------------------------------------------------
    public static void main (String[] args)
    {
        JFrame frame = new JFrame ("exit");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        ServerPanel panel = new ServerPanel();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

及其面板

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ServerPanel extends JPanel
{

private JButton push;



public ServerPanel ()
{

push = new JButton ("Click this button to close the server.....");
push.addActionListener (new ButtonListener());

add (push);
setBackground (Color.red);
setPreferredSize (new Dimension(500, 500));
}


private class ButtonListener implements ActionListener
{

public void actionPerformed (ActionEvent event)
{

System.exit(0);
}
}
}

我只想创建一个简单的GUI,该GUI会显示一个按钮,如果单击该按钮,它将立即关闭程序,但是每次我尝试运行Server.java时,它都会为我提供:

Exception in thread "main" java.lang.NullPointerException
       at java.awt.Container.addImpl(Unknown Source)
       at java.awt.Container.add(Unknown Source)
       at ServerPanel.<init>(ServerPanel.java:20)
       at Server.main(Server.java:12)

有人可以修复它吗?

0 个答案:

没有答案