![](/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.