JTabbedPane
在将其连接到能够放置它的容器之前,不会调整大小。
Window#pack
我们的工作是确定子组件的首选大小,并根据布局管理器的要求调整它们的大小。
只有在这个时候组件(和你的JTabbedPane
)才会被调整大小。
组件也可以根据容器层次结构的变化而调整大小,但基本过程是相同的。s 父容器将JTabbedPane
决定何时需要更新其内容并执行新的布局操作,并根据需要调整组件的大小
您的示例均未显示选项卡式窗格已添加到父容器中...
用简单的测试更新...
以下示例基本上演示了何时调整组件的大小。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestTabSize {
public static void main(String[] args) {
new TestTabSize();
}
public TestTabSize() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JPanel panel = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
System.out.println("Resized to " + e.getComponent().getSize());
}
@Override
public void componentMoved(ComponentEvent e) {
System.out.println("Moved to " + e.getComponent().getLocation());
}
});
System.out.println("Before been added = " + panel.getSize());
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("test", panel);
System.out.println("Before been added to tab = " + panel.getSize());
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
System.out.println("Before been added to frame = " + panel.getSize());
frame.add(tabbedPane);
System.out.println("After been added to frame = " + panel.getSize());
frame.pack();
System.out.println("After been packed = " + panel.getSize());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println("After been visible = " + panel.getSize());
}
});
}
}
输出...
正如您从输出中看到的那样,在帧为 之前packed
,没有任何尺寸
Before been added = java.awt.Dimension[width=0,height=0]
Before been added to tab = java.awt.Dimension[width=0,height=0]
Before been added to frame = java.awt.Dimension[width=0,height=0]
After been added to frame = java.awt.Dimension[width=0,height=0]
After been packed = java.awt.Dimension[width=200,height=200]
After been visible = java.awt.Dimension[width=200,height=200]
Resized to java.awt.Dimension[width=200,height=200]
Moved to java.awt.Point[x=11,y=33]