Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTabbedPane in JPanel?

I have a simple problem when I want to add tabs in my jpanel. The alignment of the tabs get horizontal instead of vertical, wich looks like crap =/.

It looks like this:

enter image description here

If I discard the panel instead and add the tabbedPane directly to the frame, everything works fine. If you uncomment the three lines of code and remove the getContentPane().add(jtp); you can reproduce my probleme.

working Code:

public class TabbedPane extends JFrame
{
    public TabbedPane()
    {
        setTitle("Tabbed Pane");
        setSize(300, 300); // set size so the user can "see" it
        JTabbedPane jtp = new JTabbedPane();

        // JPanel panel = new JPanel();//uncomment all three lines
        // panel.add(jtp);
        // getContentPane().add(panel);

        getContentPane().add(jtp);//remove me

        JPanel jp1 = new JPanel();// This will create the first tab
        JPanel jp2 = new JPanel();// This will create the second tab

        JLabel label1 = new JLabel();
        label1.setText("This is Tab 1");
        jp1.add(label1);

        jtp.addTab("Tab1", jp1);
        jtp.addTab("Tab2", jp2);

        JButton test = new JButton("Press");
        jp2.add(test);

        setVisible(true); // otherwise you won't "see" it
    }

    public static void main(String[] args)
    {
        TabbedPane tab = new TabbedPane();
    }

}

Thanks a lot!

like image 615
Thkru Avatar asked Dec 19 '25 01:12

Thkru


2 Answers

If I discard the panel instead and add the tabbedPane directly to the frame, everything works fine.

The default layout of JPanel is FlowLayout, which "lets each component assume its natural (preferred) size." The default layout of JFrame is BorderLayout, the CENTER of which ignores preferred size. In either case, invoking setSize() precludes the layout from functioning initially; re-size the frame to see the effect. Instead, use pack(), which "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents."

setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true); // otherwise you won't "see" it
like image 104
trashgod Avatar answered Dec 21 '25 17:12

trashgod


There are many things I would change in that code, starting with the recommendations of @trashgod. OTOH this is the minimal change needed in order to stretch the tabbed pane to the width/height of the parent container.

// give the panel a layout that will stretch components to available space
JPanel panel = new JPanel(new GridLayout());//uncomment all three lines
panel.add(jtp);
getContentPane().add(panel);

//getContentPane().add(jtp);//remove me

For more details see this answer.

like image 27
Andrew Thompson Avatar answered Dec 21 '25 16:12

Andrew Thompson