CypherAJ
CypherAJ

Reputation: 47

How to set size of Dialog to match size of JTable?

I have a JDialog with a JTable in it. What I want is a dialog window with size equal to that of a table (if it doesn't go over maximal size). And in a table I want any cell to have size 80*25 pixels. Here is the code I have now:

JTable table = new JTable(res, varnames);
table.setRowHeight(25);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
for (int i = 0; i <= nvars; i++) {
    table.getColumnModel().getColumn(i).setMinWidth(80);
    table.getColumnModel().getColumn(i).setMaxWidth(80);
    table.getColumnModel().getColumn(i).setPreferredWidth(80);
}
JScrollPane tableSP = new JScrollPane(table);
out.getContentPane().add(tableSP);
table.setEnabled(false);
out.pack();
out.setVisible(true);

What I get is a dialog with properly sized table in it. But the dialog itself is too big and has a lot of empty space. How can this be done?

Edit: found a problem which caused extra space. JScrollPane for some reason takes much more space than table itself. But I need ScrollPane for header. Is where a way to make it take less space?

Upvotes: 0

Views: 1298

Answers (2)

camickr
camickr

Reputation: 324147

What I want is a dialog window with size equal to that of a table

JTable table = new JTable(...);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
dialog.add( scrollPane );
dialog.pack();
dialog.setVisible( true );

Upvotes: 0

kleopatra
kleopatra

Reputation: 51535

The extra area you are seeing is the scrollPane's: it respects its view's preferredScrollableViewportSize (if it implement Scrollable). A plain JTable returns that property as a (rather arbitrary) hardcoded size. So the solution is to subclass and implement the method to return something reasonable, f.i. in terms of visibleRows:

JTable table = new JTable(10, 5) {
    // make this a property in a custom table
    int visibleRows = 10;
    /**
     * Overridden to exactly fit a given number of rows/columns
     */
    @Override
    public Dimension getPreferredScrollableViewportSize() {
        int height = visibleRows * getRowHeight();
        int width = getPreferredSize().width;
        return new Dimension(width, height);
    }

};

Or use JXTable (part of the SwingX project) which already provides the properties visibleRows/-Columns.

Upvotes: 1

Related Questions