转自:http://blog.csdn.net/sun1956/article/details/8237682
1、禁止分隔条:Java中分割面板是个不错的应用,可以将一个面板分隔成两个部分,一部分可以当作菜单,另一部分可以当作点击菜单项时的响应界面。
JSplitPane中的setDividerLocation(百分比);方法可以随意的设置自己想要的百分比。但是某些时候我们设置好百分比之后,想要禁止分隔条拖动。
可以采用setEnabled(false)禁止拖动。
2、如果想要让分隔条随着窗口大小变化,而保持比例,可以为该窗口添加监听器,在监听器里面重新设置百分比,这样分隔条就随着窗口大小变化而变化了。setDividerLocationpublic void setDividerLocation(double proportionalLocation) 这个方法一定要放在frame.setVisible(true);之后才有效
设置分隔条的位置为 JSplitPane 大小的一个百分比。
根据 setDividerLocation(int) 来实现此方法。此方法以分隔窗格的当前大小为基础迅速改变窗格的大小。如果分隔窗格没有正确地实现并且不显示在屏幕上,此方法将不产生任何影响
3、JSplitPane把面板分隔成两部分,但这两部分只能分别添加一个组件,如果想要添加多个组件,要设置一个新的JPanel对象添加进去,再向JPanel中添加组件,这样就可以添加多个组件了。
测试代码:
- import java.awt.event.ComponentAdapter;
- import java.awt.event.ComponentEvent;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JRadioButton;
- import javax.swing.JSplitPane;
- public class SplitPane extends JFrame{
- /**
- * @author Sun
- */
- private static JSplitPane splitPane = new JSplitPane();
- private JLabel jbtTop = new JLabel("left:");
- private JLabel jbtBottom = new JLabel("right:");
- private JPanel panel1,panel2;
- private JRadioButton jrb1,jrb2;
- public SplitPane () {
- jrb1 = new JRadioButton("jrb1");
- jrb2 = new JRadioButton("jrb2");
- panel1 = new JPanel();
- panel2 = new JPanel();
- splitPane.setTopComponent(panel1); //添加面板对象,这里添加组件的方法要注意,不是add
- panel1.add(jbtTop); //在面板对象中添加组件
- panel1.add(jrb1);
- splitPane.setBottomComponent(panel2);
- panel2.add(jbtBottom);
- panel2.add(jrb2);
- splitPane.setOneTouchExpandable(true); //设置分割面板显示UI小部件,就是分隔条上的小三角
- add(splitPane);
- splitPane.setEnabled(false); //设置分隔条禁止拖动
- }
- public static void main(String[] args) {
- JFrame frame = new SplitPane();
- frame.setTitle("SplitPane");
- frame.setSize(300,200);
- frame.setLocationRelativeTo(null);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- //为frame窗口添加监听器,实现保持面板两部分的比例
- frame.addComponentListener(new ComponentAdapter(){
- public void componentResized(ComponentEvent e) {
- splitPane.setDividerLocation(0.4);}
- });
- //这里是面板第一次显示的时候,frame没有事件,所以要设置一次
- splitPane.setDividerLocation(0.4); //设置分割比,一定要在frame.setVisible(true);之后才有效
- }
- }