使用JTabbedPane自动扩展

时间:2017-03-12 11:59:55

标签: java swing layout-manager border-layout flowlayout

我正在尝试让JTabbedPane自动扩展到父JPanel

当我把所有东西放在Main类中时,它可以工作:

enter image description here

主要

public class Main extends JFrame {

    public Main() {
        JTabbedPane tpane = new JTabbedPane();
        JPanel panel = new JPanel();
        panel.add(new JButton("Button 1"));
        tpane.addTab("Tab1", panel);

        JPanel panel2 = new JPanel();
        panel2.add(new JButton("Button 2"));
        tpane.addTab("Tab2", panel2);

        this.setSize(500, 500);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(tpane);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        Main m = new Main();
    }
}

但是当我把它放到另一个班级时,它将不再起作用了:

enter image description here

主要

public class Main extends JFrame {

    View view = new View();

    public Main() {
        this.setSize(500, 500);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(view, BorderLayout.CENTER); // BorderLayout
        this.setVisible(true);
    }

    public static void main(String[] args) {
        Main m = new Main();
    }
}

查看:

public class View extends JPanel {

    public View() {
        JTabbedPane tpane = new JTabbedPane();
        JPanel panel = new JPanel();
        panel.add(new JButton("Button 1"));
        tpane.addTab("Tab1", panel);

        JPanel panel2 = new JPanel();
        panel2.add(new JButton("Button 2"));
        tpane.addTab("Tab2", panel2);

        this.add(tpane, BorderLayout.CENTER); // BorderLayout
    }
}

1 个答案:

答案 0 :(得分:1)

框架具有边框布局,面板具有流动布局。

  • 添加到没有约束的边框布局的组件最终会出现在CENTER&将被拉伸到可用的高度和宽度。
  • 添加到流程布局的组件将保持其自然大小。

更一般地说,不要设置顶级容器的大小。最好调用pack(),这将使TLC成为容纳其中组件所需的确切大小。要向GUI添加空白,请使用布局约束(当布局仅包含单个组件时不是特别相关)或边框。有关工作示例,请参阅this answer

修改

  

我为BorderLayoutMain设置了View。但结果保持不变。

这是更改View布局的结果,如此处所示。

enter image description here

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

public class Main extends JFrame {

    View view = new View();

    public Main() {
        this.setSize(500, 500);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(view);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        Main m = new Main();
    }
}

class View extends JPanel {

    public View() {
        super(new BorderLayout()); // Just 1 line difference!
        JTabbedPane tpane = new JTabbedPane();
        JPanel panel = new JPanel();
        panel.add(new JButton("Button 1"));
        tpane.addTab("Tab1", panel);

        JPanel panel2 = new JPanel();
        panel2.add(new JButton("Button 2"));
        tpane.addTab("Tab2", panel2);

        this.add(tpane);
    }
}