*
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
Author

Attaching components to JPanel

Agnes Lapka
Greenhorn

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.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.addChangeListener(new ChangeListener() {
public void stateChanged( ChangeEvent e)
{ text.setText(" " + slider.getValue() );
repaint(); }
}
);
setLayout( layout);
// these two lines create a problem:
add(slider);
add(text);

} // 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(Container.java:345)
At java.awt.Container.add(Container.java:228)
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

see here: http://www.javaranch.com/ubb/Forum33/HTML/002126.html
 
GeeCON Prague 2014
 
subject: Attaching components to JPanel