Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Attaching components to JPanel  RSS feed

Agnes Lapka
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Everyone!
I�m trying to create a subclass of JPanel that will contain 2 JCompontents: a JSlider and a JTextField.
It�s supposed to be a reusable class, so I�ve been trying to build the complete interface in the constructor.
The problem I�m having is that when I attach the components to the panel ( the last two lines of the constructor) and run the program which uses this class, I�m getting the NullPointerException. Is it because the object of this class is just being instantiated, so I can�t refer to it (even implicitly)?
In that case, where exactly should I attach the two components to the panel?
I will be infinitely grateful for help.
Here is the class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Test extends JPanel {
private JSlider slider;
private JTextField text;
FlowLayout layout = new FlowLayout();
public Test() { // constructor
text = new JTextField( " ", 10);
slider = new JSlider( SwingConstants.HORIZONTAL,
0, 225, 10);
slider.addChangeListener(new ChangeListener() {
public void stateChanged( ChangeEvent e)
{ text.setText(" " + slider.getValue() );
repaint(); }
setLayout( layout);
// these two lines create a problem:

} // end of constructor
} // end of class
and here�s the error message that pops up when I try to run it:
Exception (...)java.lang.NullPointerException
At java.awt.Container.addImpl(
At java.awt.Container.add(
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!