JSplitPane เป็น subclass ของ JComponent จัดเรียง components สองตัวติดกัน horizontally หรือ vertically ใน pane เดียว พื้นที่แสดงผลปรับได้ที่ runtime โดย user เมธอดสำคัญของ JSplitPane ได้แก่ remove(), removeAll(), resetToPreferredSizes() และ setDividerLocation() JSplitPane สร้าง PropertyChangeListener interface เราสามารถซ่อน pane หนึ่ง (left หรือ right) โดยโปรแกรมได้โดยคลิกที่ left button หรือ right button และสร้าง action listeners สำหรับปุ่มเหล่านั้น
ตัวอย่าง
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JSplitPaneHideTest extends JFrame {
private JButton leftBtn, rightBtn;
private JSplitPane jsp;
public JSplitPaneHideTest() {
setTitle(" JSplitPaneHide Test");
leftBtn = new JButton("Left Button");
rightBtn = new JButton("Right Button");
jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftBtn, rightBtn);
jsp.setResizeWeight(0.5);
// Implementation code to hide left pane or right pane
ActionListener actionListener = new ActionListener() {
private int loc = 0;
public void actionPerformed(ActionEvent ae) {
JButton source = (JButton) ae.getSource();
if (jsp.getLeftComponent().isVisible() && jsp.getRightComponent().isVisible()) {
loc = jsp.getDividerLocation();
jsp.setDividerSize(0);
jsp.getLeftComponent().setVisible(source == leftBtn);
jsp.getRightComponent().setVisible(source == rightBtn);
} else {
jsp.getLeftComponent().setVisible(true);
jsp.getRightComponent().setVisible(true);
jsp.setDividerLocation(loc);
jsp.setDividerSize((Integer) UIManager.get("SplitPane.dividerSize"));
}
}
};
rightBtn.addActionListener(actionListener);
leftBtn.addActionListener(actionListener);
add(jsp, BorderLayout.CENTER);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JSplitPaneHideTest();
}
}
Output


