Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Attaching components to JPanel

 
Agnes Lapka
Greenhorn
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.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
Posts: 3695
IntelliJ IDE Java Ubuntu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic