此代码应生成一个带有 2 个垂直拆分窗格的框架,这些窗格应进行初始化,以便均匀放置分隔线。
但是,这仅在帧大小固定时才有效。这似乎是因为拆分窗格的首选高度总和对于我的屏幕(1280x1024)来说太大了。getSize() 报告的 JFrame 高度最终大于我的屏幕高度,因此分隔线放置不当。
使用 frame.pack() 时应该怎么做?
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TestSplitPanels extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
TestSplitPanels tps = new TestSplitPanels();
frame.setContentPane(tps);
frame.pack();
// uncomment this and the dividers are nicely positioned
// frame.setSize(600,600);
frame.setVisible(true);
}
public TestSplitPanels() {
JTable jt1 = new JTable();
JTable jt2 = new JTable();
JTable jt3 = new JTable();
// wrap every JTable in a scroll pane
JScrollPane jsr1 = new JScrollPane();
jsr1.setViewportView(jt1);
JScrollPane jsr2 = new JScrollPane();
jsr2.setViewportView(jt2);
JScrollPane jsr3 = new JScrollPane();
jsr3.setViewportView(jt3);
final JSplitPane jsl1 = new JSplitPane();
final JSplitPane jsl2 = new JSplitPane();
/*
* Make a vertical split pane who's top component is
* is the first scroll pane and bottom component is
* another scroll pane. Try to set the divider location
* at a third of the height of the parent component,
* when that value is known
*/
jsl1.setOrientation(JSplitPane.VERTICAL_SPLIT);
jsl1.setTopComponent(jsr1);
jsl1.setBottomComponent(jsl2);
jsl1.addAncestorListener(new BaseAncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
jsl1.setDividerLocation(getSize().height/3);
}
});
/*
* Set components and set the divider position as before
* for the second split pane
*/
jsl2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jsl2.setTopComponent(jsr2);
jsl2.setBottomComponent(jsr3);
jsl2.addAncestorListener(new BaseAncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
jsl2.setDividerLocation(getSize().height/3);
}
});
setLayout(new BorderLayout());
add(jsl1, BorderLayout.CENTER);
}
public static class BaseAncestorListener
implements AncestorListener {
@Override
public void ancestorAdded(AncestorEvent event) {
}
@Override
public void ancestorRemoved(AncestorEvent event) {
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
}
}