views:

61

answers:

3

I have an abstract entity:

public abstract class Entity extends JPanel implements FocusListener

And I have a TextEntity:

public class TextEntity extends Entity

Inside TextEntity's constructor I want to put a JTextArea that will cover the panel:

textArea = new JTextArea();
textArea.setSize(getWidth(),getHeight());
add(textArea);

But getWidth() and getHeight() returns 0. Is it a problem with the inheritance or the constructor?

+3  A: 

Shuldn't be an inheritance problem. Probably in the constructor the JPanel doesn't still have a size.

Andrea Polci
you're right. It isn't added yet. I got it now thanks
Halo
A: 

Depending on the layout, you would need to set the preferred/min/max size of at the embedded components in order for pack to calculate the actual sizes.

ddimitrov
+1  A: 

Try using some LayoutManager that takes care of resizing the components inside the panel. For example the BorderLayout, and add the textarea to the center.

Something like this (it's been a few years since I coded Swing):

textArea = new JTextArea();
textArea.setSize(getWidth(),getHeight());
setLayout(new BorderLayout());
add(textArea, BorderLayout.CENTER);

Now, when you make the panel visible, the layout manager should take care of keeping the textarea the same size as the panel. Also make sure you don't have any borders in the panel.

fish
if I use a layout will I not have the problem of "adding children before the parent panel even exists"?
Halo
The parent panel (TextEntity) exists, but that panel does not yet have a parent. When you add TextEntity to some other container, that containers' layout manager will in turn take care of managing the bounds of TextEntity. And so on, until you have the topmost parent, like JFrame or something visible and bounds set.
fish