0

Here is my code


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);
    }
}

And its panel

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);
}
}
}

I just want to create a simple GUI that will show a button that if its clicked, it will immediately close the program ,but every time I try to run the Server.java it gives me this:

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)

Can anybody fix it?

Smarkite
  • 109
  • 6
  • 2
    Save and recompile the files, you shouldn't get a NPE there based on the source code you have provided. – Progman Apr 25 '20 at 16:53
  • 2
    And I compiled your files and did not get a NPE. Save BOTH files with the current source code and compile BOTH classes, then start your application. If the problem still exists, verify that the source code in your question is the same source code you have, because the source code in your question is correct. Also verify that you compile and test the correct files and not other copies of files in other directories. – Progman Apr 25 '20 at 17:25

0 Answers0