Search code examples
javaswinguser-interfacejpanelgridbaglayout

java GridBagLayout not working?


I am trying to use gridbagayout to align a jtabbedpane and a scrollpane. I tried to align them vertically. However, the result was horizontal. Does anyone why this happened? Thank you.

This is the actual result: enter image description here

Here's my code:

  JTabbedPane tabs= new JTabbedPane();
  tabs.setOpaque(false);


        JScrollPane textScrollPane= new JScrollPane();
            textArea= new JTextArea();
            textArea.setEditable(false);
            DefaultCaret caret = (DefaultCaret)textArea.getCaret();
            caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            textScrollPane.setViewportView(textArea);

    GridBagConstraints c = new GridBagConstraints();
        {
            c.fill = GridBagConstraints.BOTH;
            c.gridx = 0;
            c.gridy = 0;
            c.weightx=1;
            c.gridheight=4;
            panel.add(tabs,c);

            c.fill = GridBagConstraints.BOTH;
            c.gridx=0;
            c.gridy=1;
            c.weightx=1;
            c.gridheight=1;
            c.ipadx=20;
            c.ipady=10;
            panel.add(textScrollPane,c);

            /////restore to default
            c.gridheight=1;
            c.ipadx=0;
            c.ipady=0;
        }

Solution

  • However, the result was horizontal. Does anyone why this happened?

    Probably because the default layout manager of a JPanel is the FlowLayout and you didn't change the layout manager when you created the panel. The FlowLayout displays components horizontally.

    When you create the panel you also need:

    JPanel panel = new JPanel( new GridBagLayout() );