开发者

Calculating "nice" looking position for divider in JSplitPane

I'm trying to use setDividerLocation on JSplitPane to size the two panels in a "best size" fashion so that the vertical scroll bar doesn't appear in the top panel. The split location should be just after the last of the data in the top panel.

Using jSplitPane1.setResizeWe开发者_如何学编程ight(1D) reserves too much space for the top component, resulting in empty space beneath the data.

I'm trying to get it just right!

Calculating "nice" looking position for divider in JSplitPane


I assume you have a JTable as main component in upper side of the splitpane? If so you could do like this:

int location = (int) table.getPreferredSize().getHeight();
location += splitPane.getDividerSize() * 2;
splitPane.setDividerLocation(location);


I would suggest avoiding moving the JSplitPane around while the user may want to interact with it. I can imagine it would be rather annoying to see the pane jump a few pixels before/after dragging it.

Nevertheless, you might want to take a look at obtaining the dimensions of the scrollbar, and offsetting the divider location by that amount. For instance, say you have constructed the JTable as follows:

JTable table = new JTable(myTableModel);
final JScrollPane scrollPane = new JScrollPane(table);
scrollPane
        .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane
        .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

You could then add a listener to the table to determine when the horizontal scroll bar is displayed, and add some offset to the JSplitPane as needed:

table.addComponentListener(new ComponentListener() {
    @Override
    public void componentShown(ComponentEvent e) {}
    @Override
    public void componentResized(ComponentEvent e) {
        System.out
            .println(scrollPane.getHorizontalScrollBar().getHeight());
    }
    @Override
    public void componentMoved(ComponentEvent e) {}
    @Override
    public void componentHidden(ComponentEvent e) {}
});

Bear in mind that by changing the divider location, table will resize, causing a loop, so this construction is not ideal.


You can set the divider location to zero then set the divider size to 0. This will have the effect of just showing the bottom panel. Is that what you are looking for?

jSplitPane1.setDividerLocation(0);
jSplitPane1.setDividerSize(0);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜