This question already has an answer here:
I created a Java Application and get this Exception:
Exception in thread "main" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Executer.<init>(Executer.java:21)
at Executer.main(Executer.java:14
Here is the code:
import javax.swing.*;
import java.awt.*;
public class Executer {
private JLabel lblCommand;
private JTextField txtEnter;
private JButton btNext, btPrevious;
private JPanel panel;
public static void main(String[] args) {
new Executer();
}
public Executer() {
JFrame frame = new JFrame("Execute Script");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setVisible(true);
frame.add(panel);
frame.setVisible(true);
MyPanel();
Text();
Buttons();
Fields();
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);
}
public void Text(){
lblCommand = new JLabel("Enter Here");
lblCommand.setBounds(135, 50, 150, 20);
Font styleOne = new Font("Arial", Font.BOLD, 13);
lblCommand.setFont(styleOne);
panel.add(lblCommand);
}
public void Fields () {
txtEnter = new JTextField();
txtEnter.setBounds(210, 50, 150, 20);
panel.add(txtEnter);
}
public void Buttons() {
btNext = new JButton ("Next");
btNext.setBounds(380,325,100,20);
panel.add(btNext);
btPrevious = new JButton ("Previous");
btPrevious.setBounds(260,325,100,20);
panel.add(btPrevious);
}}
What is a NullPointerException? How would I find out?
Problem in this line
frame.add(panel);
Panel is not initialized at that point, move this lineMyPanel();
before adding to initialize it.Yes you are adding panel to the frame before creating object of JPanel. Anyway change your constructor with this:
thanks.
You need to instantiate
panel
before adding it. If you use panel before callingMyPanel()
,panel
is stillnull
, hence theNullPointerException
.While you're here, give this a glance. http://geosoft.no/development/javastyle.html
Method names in Java should be mixed case starting with a lower case letter, e.g.
myPanel()
instead ofMyPanel()
. To most of us,MyPanel()
looks like a constructor at first glance because you improperly styled it.Additionally,
MyPanel
,Text
,Fields
, andButtons
should all be private methods, as it would be improper for an external class to call them.As others have said, you need to create the JPanel before you try to add it to the JFrame. In fact, you should typically create all components inside the JPanel as well. I suggest that you move the calls to
from the
Executer
constructor to theMyPanel()
method and callMyPanel()
before callingframe.add(panel);
.In addition, you do not need to call
frame.setVisible(true);
twice. Also, you should use aLayoutManager
rather than callingpanel.setLayout(null);
. See the Oracle tutorial for Using Layout Managers.