Reputation: 411
There a panel. I add JLabel on that panel and want to know the size of that JLabel.
Here is simple code:
import java.awt.Dimension;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class MyPanel extends JPanel {
MyPanel() {
this.setPreferredSize(new Dimension(300, 300));
Label myLabel = new Label("ddddddddd");
this.add(myLabel);
System.out.println(myLabel.getPreferredSize().width);
System.out.println(myLabel.getSize().width);
System.out.println(myLabel.getMinimumSize().width);
System.out.println(myLabel.getMaximumSize().width);
}
}
class MyFrame extends JFrame {
MyFrame() {
this.setTitle("Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new MyPanel());
this.pack();
this.setVisible(true);
}
}
public class Text {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MyFrame();
}
});
}
}
The results is not what I expected:
0.0
0.0
0.0
32767.0
In some other programm I use the "getPreferredSize().width" and I receive correct result but unfortunately I don't have working code on my hand now.
Can someone explane why with "getPreferredSize().width" I receive zero and how can I get the current label's width?
Upvotes: 1
Views: 2599
Reputation: 26961
Use java.swing.JLabel
instead java.awt.Label
JLabel myLabel = new JLabel("ddddddddd");
OUTPUT:
63
0
63
63
Upvotes: 3