File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Attaching components to JPanel Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Attaching components to JPanel" Watch "Attaching components to JPanel" New topic

Attaching components to JPanel

Agnes Lapka

Joined: Dec 26, 2000
Posts: 23
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

Joined: Feb 20, 2001
Posts: 3695

see here:
subject: Attaching components to JPanel
It's not a secret anymore!