3

I have a BoxLayout (in a panel of a BorderLayout) in which I've put a JTable and a button vertically. I would like the table to have a fixed width and that the height should resize itself up to filling the panel. At the moment, I'm fine with the displayed width but not that it's filling up the whole panel height. For example, if there are zero data in the table, I would like only the column names to be shown. I've tried things like setViewportView() and setPreferredSize(), but can't really make it work. Any suggestions? Is it in the layout or scrollpane?

String[] columnNames = { "Date", "Type"
    };
Object[][] data = { 
    };
JTable myTable = new JTable(data, columnNames);
JButton okButton = new JButton("OK");

JPanel panWest = new JPanel();
panWest.setLayout(new BoxLayout(panWest, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(myTable);
panWest.add(scrollPane);
panWest.add(okButton);

EDIT This is what ended up working:

Dimension dimension = new Dimension();
dimension.height =     (myTable.getRowCount()*myTable.getRowHeight())+
myTable.getTableHeader().getPreferredSize().height;
dimension.width = myTable.getColumnModel().getTotalColumnWidth();
scrollPane.setMaximumSize(dimension);
4

1 回答 1

1

我希望表格具有固定的宽度,并且高度应该自行调整大小以填充面板。

我有一个 BoxLayout(在 BorderLayout 的面板中),在其中垂直放置了一个 JTable 和一个按钮。

有三种(只提到简单的)方法

  • 使用内置LayoutManagerJPanel- FlowLayout( FLowLayout.CENTER),

    1. 覆盖FLowLayout.LEFTRIGHT在您想要 aling 的情况下,

    2. JComponent如果没有以编程方式更改并由&通知,则放置的FlowLayoutnever 将可调整大小,XxxSizerevalidaterepaint

    3. 通过 override 为 JScrollPane 设置适当的大小JTable.setPreferredScrollableViewportSize(new Dimension(int, int));

    4. JScrollPane 接受此 Dimension 作为初始大小,需要使用 JFrame.pack(),之前JFrame.setVisible(true)

  • BoxLayout接受min, max and preferred size,覆盖所有这三种尺寸JScrollPane

  • ( )half solution, but most comfortable更改LayoutManagerJPanel,BorderLayout

    1. 放在区域,JScrollPane_JTableBorderLayout.EAST/WEST

    2. 然后覆盖JTable.setPreferredScrollableViewportSize(new Dimension(int, int));

    3. JScrollPane将占据整个区域,BorderLayout.EAST/WEST并且只能在heights坐标上调整大小


  • 使用MigLayout, 这里有一些关于MigLayoutand JScrollPane(with JTextArea, JTable) 的帖子
于 2013-10-31T11:33:55.957 回答