【发布时间】:2021-08-12 18:32:03
【问题描述】:
我创建了一个带有JTable 的JScrollPane。当表格的高度大于滚动窗格的高度时,会出现一个滚动条。如果将JFrame最小化,虽然我没有改变它的大小,滚动条消失,滚动窗格向下延伸。
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Main {
static String columns[] = {"Date", "Price", "URL", "Expired"};
static String data[][] = new String[8][4];
/*
* The data that should be provided to the JTable is
* replaced with some example data because the method
* of getting this data is complicated and doesn't
* change anything at the outcome.
*/
public static void main(String[] args) {
loadGui();
}
public static void loadGui() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 4; j++) {
data[i][j] = "Example data " + i + " " + j;
}
}
JFrame mainFrame = new JFrame();
mainFrame.setSize(800, 300);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
JTable table = new JTable(data, columns);;
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane pane = new JScrollPane(table);
pane.setViewportView(table);
pane.setSize(785, 100);
mainFrame.add(pane);
table.getTableHeader().setReorderingAllowed(false);
table.setDefaultEditor(Object.class, null);
table.setFocusable(false);
table.setRowSelectionAllowed(false);
}
}
我正在寻找一种方法来阻止滚动窗格向下延伸并保持其大小。
【问题讨论】:
-
Swing 旨在与布局管理器一起使用。您不应该使用 setSize()。布局管理器将设置组件的大小/位置。恢复帧大小时会调用布局管理器,因此它会覆盖您的 setSize() 语句。不要使用 setSize()。您可以建议滚动窗格的视口大小,如本示例所示:stackoverflow.com/a/56877885/131872。您可能想要覆盖高度。此外,Swing 组件默认可见,不需要“pane.setVisible(true)”。如果您需要更多帮助,请发布适当的minimal reproducible example。
-
还在等你的minimal reproducible example...
-
抱歉,我来晚了,但现在您应该看到最小的可重现示例。
标签: java swing jtable jscrollpane