I hope to get some help for a problem that confuses me.
I tested getPreferredSize()
on Frame
and on Frame
. In Frame
, getPreferredSize()
returns all 0 (both width and height), while in Frame
, it returns non-zero numbers, which is working.
I am not sure which part of my coding in nolayout()
method such that getPreferredSize()
simply returns 0, and isPreferredSizeSet()
returns FALSE
, which implies preferred size is not set.
Why is it not set? Can anyone help? Thanks.
Below are the codings of this simple test program.
import java.awt.*;
import javax.swing.*;
public class test {
public test(){
JFrame frame = new JFrame("AbsoluteLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container p = frame.getContentPane();
p.setLayout(null);
JButton b1 = new JButton("one");
p.add(b1);
Dimension size = b1.getPreferredSize();
System.out.println("size width is "+size.width+" height is "+size.height);
JLabel label2 = new JLabel("Text-Only Label");
p.add(label2);
size = label2.getPreferredSize();
System.out.println("label size width is "+size.width+" height is "+size.height);
Insets insets = p.getInsets();
frame.setSize(300 + insets.left + insets.right, 125 + insets.top + insets.bottom);
frame.setVisible(true);
}
public static void main(String[] args) {
test t = new test();
nolayout();
}enter code here
public static void nolayout() {
Frame f = new Frame();
f.setLayout(null);
Insets its = f.getInsets();
System.out.println("its left, "+its.left+" right, "+its.right+" top "+its.top+" bottom "+its.bottom);
f.setLocation(200, 100 );
f.setSize(its.left+its.right+300,its.top+its.bottom+200);
Label l1 = new Label("Enter Integer to be added : ",Label.RIGHT);
TextField t1 = new TextField("0",10);
f.add(l1);
f.add(t1);
System.out.println("is l1 preferred size set "+l1.isPreferredSizeSet());
Dimension sz = l1.getPreferredSize();
l1.setBounds(its.left + 10, its.top + 10, sz.width, sz.height);
System.out.println("label 1 width "+sz.width+" height " +sz.height);
sz = t1.getPreferredSize();
t1.setBounds(its.left + 100, its.top + 10, sz.width, sz.height);
System.out.println("Text 1 width "+sz.width+" height " +sz.height);
f.setVisible(true);
}
}
The output on the command window is as follows:
C:\JAVAPR>java test
size width is 55 height is 26
label size width is 88 height is 16
its left, 0 right, 0 top 0 bottom 0
is l1 preferred size set false
label 1 width 0 height 0
Text 1 width 0 height 0 enter code here