このコードは、仕切りが均等に配置されるように初期化する必要がある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) {
}
}
}