【问题标题】:Split pane into two halves using Swing使用 Swing 将窗格分成两半
【发布时间】:2014-05-15 01:30:27
【问题描述】:

谁能建议我如何将我的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);

  }
}

【问题讨论】:

    标签: java swing jpanel layout-manager jtabbedpane


    【解决方案1】:

    对放置在该选项卡中的JPanel 使用单行GridLayout。里面有两个组件,它们每个都有一半的空间。例如

    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);
        }
    }
    

    【讨论】:

    • 你能分享一些我上面代码的sn-p例子吗?
    • @Dojo_user 看看How to Use GridLayout的例子
    • 谢谢安德鲁!!这是可行的,但我想水平划分窗口,这个是垂直划分的。我需要更改哪个参数才能在同一代码中水平划分窗口。
    • 我觉得应该是 JPanel tab2Panel = new JPanel(new GridLayout(0,1));对于水平选项..
    • 如果您检查JavaDocs for the GridLayout constructor,您可能会看到new GridLayout(1,0) 将是new GridLayout(0,1) ;)
    猜你喜欢
    • 1970-01-01
    • 2013-05-25
    • 2013-12-06
    • 2012-05-26
    • 2017-07-20
    • 1970-01-01
    • 2015-12-02
    • 2020-07-20
    • 2019-09-04
    相关资源
    最近更新 更多