简体   繁体   English

当我在jscrollpane上添加jtable时,水平滚动条不起作用

[英]Horizontal scroll bar doesn't work when I add jtable on jscrollpane

I have a JTable on a JScrollPane. 我在JScrollPane上有一个JTable。 I want that table occupied the entire scroll. 我希望那个桌子占据整个滚动。 So I add this: table.setAutoResizeMode(JTable.AUTO_RESIZE_All_Columns); 所以我添加了这个: table.setAutoResizeMode(JTable.AUTO_RESIZE_All_Columns); It works good when there are only a few columns. 当只有几列时,它会很好地工作。 But when there are a lot of columns it looks like that: 但是,当有很多列时,它看起来像这样:

As you can see there are too narrow columns. 如您所见,列太窄。 I try to add this code for all columns: table.getColumnModel().getColumn(1).setMinWidth(75); 我尝试为所有列添加此代码: table.getColumnModel().getColumn(1).setMinWidth(75); It works. 有用。 And I added this code to JScrollPane: setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 然后我将此代码添加到JScrollPane中: setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); But horisontal scroll bar doesn't work: 但是水平滚动条不起作用:

You can see it, but it doesn't work. 您可以看到它,但是不起作用。 I know that I could solve all my problems with this code: 我知道我可以用以下代码解决所有问题:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)

But in this case my table doesn't occupied the entire scroll. 但是在这种情况下,我的表没有占据整个滚动。 So, I want that columns extended the full width of the scroll when there are only a few columns and I want that columns are not narrowed to less than a certain value when there are a lot of columns. 因此,当列数很少时,我希望这些列扩展滚动的整个宽度,并且当列数很多时,我希望这些列不缩小到小于某个值。 And I want to have a horizontal scroll bar. 我想要一个水平滚动条。 Is it possible to do that? 有可能这样做吗?

Sorry, it was a silly question. 抱歉,这是一个愚蠢的问题。 I could to do all what I want with this code: 我可以用这段代码来做所有我想做的事情:

if (getColumnModel().getColumnCount() > 13)
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
else
    setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

But if somebody kmows more elegant solution show it please. 但是,如果有人想出更优雅的解决方案,请显示它。 It will be really helpful for me. 这对我真的很有帮助。

Duplicate. 重复。
You can find here 2 elegant solutions. 您可以在这里找到 2种优雅的解决方案。
One of which is: 其中之一是:

jTable.getParent().addComponentListener(new ComponentAdapter() {
    @Override
    public void componentResized(final ComponentEvent e) {
        if (jTable.getPrefer1sredSize().width < jTable.getParent().getWidth()) {
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        } else {
            jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM