Getting Size of Components
Ok, I need to be able to get the current size of a component. I have attempted to use the component's getWidth() method, getHeight() method, getSize() method, and the getPreferredSize() method but they all return 0 or dimensions that have a height and width of 0 (depending on the method).
My components have not been given a specific size by me, they should be getting their size based on what they contain or specifications on construction. For example, the size of a JLabel is the length of the String given to it. The size of a JTextField is the number of columns given to. The size of a JButton is the length of the String given to it. And those sorts of things.
I believe that because of this setup, I am getting 0 because I have not explicitly set a size or a preferred size. And for what I am doing, I shouldnt be sending it a size or a preferred size anyway.
As well as getting the sizes of normal components, I want to be able to get the size of a JPanel when I send it one. I havent managed to get that to work either.
Is anyone able to send me in the correct direction?
Re: Getting Size of Components
When are you trying to retrieve the size? Is this before they are visible or packed within a JFrame? These methods return 0 prior to this:
Code java:
public static void main(String[] args){
JPanel panel = new JPanel();
JLabel lab = new JLabel("Label");
panel.add(lab);
System.out.println(lab.getWidth());//
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
System.out.println(lab.getWidth());
frame.setVisible(true);
}
Re: Getting Size of Components
This will be before packing because I am attempting to create a centerComponent(Component,int) method in my custom layout. It will need to subtract the width of the Component from the width of the JPanel and divide by 2 to find out where it needs to be placed for an X coordinate.
Re: Getting Size of Components
Looks to me that you don't need to get the size, you need to get the preferredSize.
db