我正在尝试让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();
}
}
但是当我把它放到另一个班级时,它将不再起作用了:
主要
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
}
}
答案 0 :(得分:1)
框架具有边框布局,面板具有流动布局。
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);
}
}