我正在尝试创建一个宽度为500的JTable。问题是与表关联的JScrollPane不会出现在表的旁边。
以下是相关代码:
nodeList = document.getElementsByTagName("listColumns");
getListColumnsNodes(nodeList);
以下是截图:
当我摆脱界限时:
// 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);
然后表格返回到面板的整个宽度,所以看起来我需要这一行。
答案 0 :(得分:1)
BorderLayout
上的java文档声明:
根据组件的首选尺寸和组件布置组件 容器尺寸的限制。 NORTH和SOUTH组件 可以水平拉伸; EAST和WEST组件可能是 垂直拉伸; CENTER组件可以拉伸两者 水平和垂直填充剩余的空间。
您已使用authorsPanel.add(tableScroll)
将JScrollPane
添加到JPanel
。所以你基本上把它添加到中心。所以这将占据空置的整个空间。
问题的解决方案在于选择不同的布局。我可以推荐一种非常通用的MigLayout,你可以使用它来获得各种效果。
答案 1 :(得分:0)
将滚动窗格添加到具有BorderLayout的面板。 BorderLayout不关心首选大小。使用例如具有适当约束的GridBagLayout,或者您可以将BoxLayout(具有水平流)放置在第一个表格中,将第二个空面板放置为占位符。