0

I have a JPanel with BoxLayout.PAGE_AXIS, but when I add two JLabels to it, the first fills the whole JPanel. PreferredSize for JPanel is height 10. Both JLabels have preferred height 5, and width is same for all three.

What am I doing wrong?

P.S. That's why I preffer the freaking null layout...

Karlovsky120
  • 6,212
  • 8
  • 41
  • 94

1 Answers1

0

Try this code, it should work fine:

import java.awt.Dimension;

import javax.swing.*;

public class Test extends JFrame{
    JPanel panel = new JPanel();
    JLabel lbl1 = new JLabel("First");
    JLabel lbl2 = new JLabel("Second");

    public Test(){
        super("BoxLayout Test");
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.setPreferredSize(new Dimension(300,200));
        panel.add(lbl1);
        panel.add(lbl2);
        add(panel);

    }
    public static void main(String [] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                Test t = new Test();
                t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                t.pack();
                t.setVisible(true);
        }});
    }
}
Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
  • 1
    You might just want to read about [Threading with Swing](http://www.javamex.com/tutorials/threads/invokelater.shtml) – Sujay Aug 26 '12 at 23:13
  • It will work fine like this. I think there is no need for that. It could just complicate his life. Btw, thanks for editing! :) – Branislav Lazic Aug 26 '12 at 23:18
  • 2
    There's a difference between "working fine" and "working correctly" :) – Sujay Aug 26 '12 at 23:22
  • 1
    Glad to help :) Perhaps you might want to read this [SO Link] (http://stackoverflow.com/questions/7196889/swingutilities-invokelater) and [this blog](https://bitguru.wordpress.com/2007/03/21/will-the-real-swing-single-threading-rule-please-stand-up/) to get some better explanation – Sujay Aug 26 '12 at 23:29