![](/img/trans.png)
[英]Doesn't show scroll in JScrollPane with JTable after Upgrade Java 7 to Java 8
[英]Java - JScrollPane Doesn't align with JTable
我试图制作一个宽度为500的JTable。问题是与表关联的JScrollPane不在表旁边。
以下是相关代码:
// Create authorsPanel
JPanel authorsPanel = new JPanel(new BorderLayout(5,5));
authorsPanel.setBorder( new TitledBorder("Author Selection") );
// Configure author table
DefaultTableModel authorstableModel = new DefaultTableModel(new String[80][1], new String[]{"Authors"}) {
@Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
JTable authorsTable = new JTable(authorstableModel);
authorsTable.getColumnModel().getColumn(0).setPreferredWidth(500);
authorsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try {
authorsTable.setAutoCreateRowSorter(true);
} catch(Exception continuewithNoSort) {
}
JScrollPane tableScroll = new JScrollPane(authorsTable);
Dimension tablePreferred = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(new Dimension(500, tablePreferred.height/3));
authorsPanel.add(tableScroll);
这是屏幕截图:
当我摆脱这条线:
authorsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
然后表格返回到面板的整个宽度,因此似乎我需要此行。
关于BorderLayout
的Java文档指出:
根据组件的首选大小和容器大小的限制来布局组件。 NORTH和SOUTH分量可以水平拉伸; EAST和WEST分量可以垂直拉伸; CENTER组件可以水平和垂直拉伸以填充剩余的任何空间。
您已经使用authorsPanel.add(tableScroll)
将JScrollPane
添加到JPanel
。 因此,您基本上是将其添加到中心 。 因此,这将占据整个空置的空间。
解决问题的办法在于选择不同的布局。 我建议使用MigLayout,它用途广泛,可以使用它获得各种效果。
您将滚动窗格添加到带有BorderLayout的面板中。 BorderLayout不在乎首选大小。 例如,使用具有适当约束的GridBagLayout,或者可以将BoxLayout(水平流动)放在第一位,然后将空白面板放在占位符上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.