0

Im trying to pass Swing components to another object but the system keeps throwing a NullPointerException. When I print out the component to String before passing it, it does not equal null. What's going wrong here?

Thanks alot

public ResizePanel() {
    initComponents();
    setLayout(null);
    this.setBackground(Color.red);
    JButton b = new JButton();
    System.out.println("b = " + b.toString());
    resizer.addJButton(b, 10, 10);  //THROWS NULLPOINTEREXCEPTION HERE
    b.setName("b");
    b.setBounds(100, 100, 100, 40);
    this.add(b);
 }  
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Variable names should NOT start with an upper case character. – camickr Sep 22 '15 at 15:18
  • 2
    `setLayout(null);` 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). .. – Andrew Thompson Sep 22 '15 at 15:20
  • 2
    .. 3) See [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/q/3988788/418556) & [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/q/218384/418556) 4) Always copy/paste error and exception output! – Andrew Thompson Sep 22 '15 at 15:21

1 Answers1

2

When I print out the component to String before passing it,

You don't "pass it". There are no parameters on your "resizePanel()" method.

So you probably have two variables of the same name, an instance variable and a local variable. So you are accessing an instance variable which is null.

The instance variable is probably defined with code like:

JPanel resizer; // this variable is null and used by your method

You probably also created a local variable which is not null:

JPanel resizer = new JPanel(); // this is not null

The above code should be changed to:

resizer = new JPanel(); 

Now you will only have one instance variable which is initialized.

camickr
  • 321,443
  • 19
  • 166
  • 288