使用 JTabbedPane 自动扩展

Automatically Expanding using JTabbedPane

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

当我将所有内容都放入 Main class 时,它起作用了:

主线:

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

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

主线:

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

框架采用边框布局,面板采用流式布局。

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

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


编辑

I set a BorderLayout to both, Main and View. But the result remained the same.

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

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