这是我的代码
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)
有人可以修复它吗?