使用Swing将窗格拆分为两半

时间:2014-05-15 01:30:28

标签: java swing jpanel layout-manager jtabbedpane

有人可以建议我如何将JTabbedPane划分为两个相等的水平部分?我的窗格中有三个标签。我想将第二个选项卡窗格(选项卡2)划分为两个相等的一半?

选项卡式窗格的代码

import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class Monitor{
  public static void main(String[] args){
  JFrame frame = new JFrame("WELCOME");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  JTabbedPane tab = new JTabbedPane();
  frame.add(tab, BorderLayout.CENTER);
  JButton button = new JButton("1");
  tab.add("tab1", button);
  button = new JButton("2");
  tab.add("tab2", button);
  button = new JButton("3");
  tab.add("tab3", button);
  frame.setSize(400,400);
  frame.setVisible(true);

  }
}

1 个答案:

答案 0 :(得分:4)

对于放置在该标签中的GridLayout,请使用单行JPanel。它有两个组件,每个组件都有一半的空间。 E.G。

enter image description here

import javax.swing.*;
import java.awt.*;

public class Monitor {

    public static void main(String[] args){
        Runnable r = new Runnable() {
            public void run() {
                JFrame frame = new JFrame("WELCOME");
                // A better close operation..
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                JTabbedPane tab = new JTabbedPane();
                frame.add(tab, BorderLayout.CENTER);
                JButton button = new JButton("1");
                tab.add("tab1", button);

                // this GridLayout will create a single row of components,
                // with equal space for each component
                JPanel tab2Panel = new JPanel(new GridLayout(1,0));
                button = new JButton("2");
                tab2Panel.add(button);
                tab2Panel.add(new JButton("long name to stretch frame"));
                // add the panel containing two buttons to the tab
                tab.add("tab2", tab2Panel);

                button = new JButton("3");
                tab.add("tab3", button);
                // a better sizing method..
                //frame.setSize(400,400);
                frame.pack();
                frame.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}