Question

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);
Was it helpful?

Solution

I would like the table to have a fixed width and that the height should resize itself up to filling the panel.

and

I have a BoxLayout (in a panel of a BorderLayout) in which I've put a JTable and a button vertically.

there are three (mentioned only simple) ways

  • use built_in LayoutManager for JPanel - FlowLayout (FLowLayout.CENTER),

    1. override FLowLayout.LEFT or RIGHT in the case that you want to aling,

    2. JComponent laid by FlowLayout never will be resizable without programatically to change XxxSize and notified by revalidate & repaint,

    3. set proper size for JScrollPane by override JTable.setPreferredScrollableViewportSize(new Dimension(int, int));,

    4. JScrollPane accepts this Dimension as initial size, required is usage of JFrame.pack(), before JFrame.setVisible(true)

  • BoxLayout accepts min, max and preferred size, override all these three sizes for JScrollPane

  • (half solution, but most comfortable) change LayoutManager for JPanel to BorderLayout,

    1. put JScrollPane with JTable to BorderLayout.EAST/WEST area,

    2. then override JTable.setPreferredScrollableViewportSize(new Dimension(int, int));,

    3. JScrollPane will occupy whole area for BorderLayout.EAST/WEST and will be resizeable only on heights coordinates


  • use MigLayout, here are a few posts about MigLayout and JScrollPane (with JTextArea, JTable)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top