2

I'm working on a project in swing, and I have a class that subclasses JComponent, but does not override any of its methods. Later, in a subclass of that class I call the following code:

System.out.println(fImage.getHeight() + " " + fImage.getWidth());
propertyFrontLabel = new JLabel(new ImageIcon(fImage));
propertyBackLabel = new JLabel(new ImageIcon(bImage));
propertyFrontLabel.setSize(fImage.getWidth(), fImage.getHeight());
Dimension d = propertyFrontLabel.getSize();
this.setPreferredSize(d);
this.setSize(d);
System.out.println(d.getSize());
System.out.println(this.getSize());
add(propertyFrontLabel);

Those print lines print out the following:
479 296
java.awt.Dimension[width=296,height=479]
java.awt.Dimension[width=0,height=0]

I don't have any idea what is going on. Why is the size of this still 0,0?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Jesan Fafon
  • 2,234
  • 1
  • 25
  • 29
  • 1
    1) Has the custom component been added to anything? 2) What layout is it in, and in which constraint? 3) Has the Top-Level container been made visible? 4) In fact, scratch those questions & the next 5 I was going to ask. For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Mar 13 '12 at 02:55

2 Answers2

3

You've possibly using a null layout, or you're calling 'getSize()' on your component prior to rendering it or prior to calling 'pack()' on the enclosing top-level Window, or you're not overridding the component's getPreferredSize() method of the JComponent... there are many possibilities here and to get better help, you'll need to tell us a lot more detail of this class, your GUI and your problem.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

It has to do when constructors, methods, etc. are called in your class hierarchy, ie. it has to do with where exactly you locate that code.

Basically the method or constructor your expecting to have been called probably hasn't been at the point you expected. Put a system.out in all the methods (or use your debugger) to see what code is called in what order. I can guarantee you the code you're expecting to be called before that code isn't called, it's called after. And it will be due to how code is called in your class hierarchy.

Stephane Grenier
  • 15,527
  • 38
  • 117
  • 192