我正在尝试让JTabbedPane在父JPanel上自动展开。
当我把所有的东西都放在主课堂上时,它起作用了:

Main:
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();
}
}但是当我把它放到另一堂课上时,它就不再起作用了:

Main:
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
}
}发布于 2017-03-12 12:15:40
框架具有边框布局,面板具有流布局。
CENTER中结束&将被拉伸到可用的高度和宽度。一般情况下,不要设置顶级容器的大小。更好的方法是调用pack(),这将使TLC精确地满足内部组件所需的大小。若要向GUI添加空白,请使用布局约束(当布局只有单个组件时不特别相关)或边框。有关工作示例,请参见this answer。
编辑
我将
BorderLayout设置为Main和View。但结果保持不变。
这是如图所示更改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);
}
}https://stackoverflow.com/questions/42747119
复制相似问题