Search code examples
javaswingresizejsplitpane

How to auto adjust JSplitPane?


In my Java Swing app there is a JSplitPane that splits vertically, top part is a JLabel which may change size when I click a button to update some info, bottom part is a JPanel that shows some results.

My code looks like this :

JLabel Top_Label=new JLabel();
Top_Label.setPreferredSize(new Dimension(1420,355));
JPanel Bottom_Panel=new JPanel();
Bottom_Panel.setPreferredSize(new Dimension(1420,445));
JSplitPane Results_Split_Pane=new JSplitPane(JSplitPane.VERTICAL_SPLIT,Top_Label,Bottom_Panel);

Top_Label contains an html table in it. When I click a button to update data, the Top_Label sometimes contain fewer lines of data in the html table and shows a lot of empty space.

Right now, when the Top_Label shows a small html table, it will remain its original size, and leave a lot of empty space, but after I adjust it to smaller space and click the button to update data to have a large html table, it won't enlarge the area to fit that larger html table, and yet when I manually move the split bar, it's intelligent enough to not go smaller than the html table's height, but if there is empty space, it will let me shrink the area.

How to let Results_Split_Pane auto adjust itself according to the height of Top_Label, so that when there is less content, the split bar will go higher to the height of the html table in Top_Label, when Top_Label contains more data, the Results_Split_Pane's split bar will go lower ?


Solution

  • Thanks to "camickr", I got the perfect answer for it, skip step 3 and use "-1" so that the JSplitPane will auto adjust to it's size, works great. Here is the listener :

              Results_Top_Label.addPropertyChangeListener(Property_Change_Listener);
    ...
              PropertyChangeListener propertyChangeListener=new PropertyChangeListener()
              {
                @Override
                public void propertyChange(PropertyChangeEvent event)
                {
            //    Out("[x] : "+event.getPropertyName());
                  if (event.getSource() instanceof JLabel && event.getPropertyName().equals("html")) 
                  {
            //      Out(((JLabel)event.getSource()).getName()+" : Height = "+Results_Top_Label.getPreferredSize().height);
                    Results_Split_Pane.setDividerLocation(-1);
                  }
                }
              };