• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Attaching components to JPanel

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
see here: http://www.javaranch.com/ubb/Forum33/HTML/002126.html
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic