Reputation: 131
i have a jpanel with an unknown Dimension with gridlayout, and i want to know how to get the size information from components on it.
this is an example:
JPanel basicInformation=new JPanel();
basicInformation.setMaximumSize(100,100);
basicInformation.setPreferredSize(basicInformation.getMaximumSize());
basicInformation.setSize(basicInformation.getMaximumSize());
basicInformation.setMinimumSize(basicInformation.getMaximumSize());
basicInformation.setLayout(new GridLayout(2, 2, 10, 10));
JLabel username=new JLabel("Example");
username.setHorizontalAlignment(JLabel.CENTER);
username.setOpaque(true);
basicInformation.add(username);
i want to know how to get the size of the label?
Upvotes: 0
Views: 823
Reputation: 5937
JLabel inherits GetSize from Component which should return a Dimension for your use.
You can call this at any time, but if the frame or panel is not visible yet (i.e. still being constructed) it will return 0,0. Perform getSize()
after any .setVisible(true)
to get the correct value.
Upvotes: 1
Reputation: 120
username.getPreferredSize();
Returns the Dimension.
username.getPreferredSize().width;
username.getPreferredSize().height;
Returns the individual components.
Upvotes: 0