I have a JDialog with two panels: a JTable and a button. I want to set JDialog so that (maxHeight= 600 pixels
):
(1) If table height is less than maxLength
it shows table fully with no blank space, but all rows fit in.
(2) If the height is greater than maxHeight
it restricts the height to maxHeight
and shows scrollbar on the side.
So far I have most of the JDialog working, but I can't figure out how to control the height of the JTable.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestGUI {
public static void main(String[] args) {
int a=10;
Object[][] data = new Object[a][2]; //Fill table with some data
for (int i = 0; i < a; i++) {data[i][0]=i; data[i][1]=i*i; }
JDialog dialog = new JDialog();
dialog.setLayout(new BorderLayout());
String[] header = {"Number", "Square"};
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(450, 600));
table.setFillsViewportHeight(true);
JScrollPane js = new JScrollPane(table);
js.setVisible(true);
dialog.add(js, BorderLayout.CENTER);
JButton okButton = new JButton(new AbstractAction("OK") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(okButton);
dialog.add(buttonPanel, BorderLayout.SOUTH);
//dialog.setSize(new Dimension(300, 600));
dialog.setMinimumSize(new Dimension(255, 175));
dialog.setVisible(true);
}
}
Hard-coded pixel sizes are almost never a good idea. Other users won’t have the same fonts as you, and even those who do may be using different font sizes. (A 12 point font is a font whose lines of text are 12⁄72 inch high, so even if the user has the same font, the dot pitch of the user’s monitor may affect how many pixels each character uses.)
Instead of maxHeight, define a maxVisibleRows
variable. Your table should use getRowHeight to compute its size based on the desired number of rows:
int visibleRows = model.getRowCount();
visibleRows = Math.max(1, visibleRows);
visibleRows = Math.min(maxVisibleRows, visibleRows);
Dimension size = table.getPreferredScrollableViewportSize();
size.height = table.getRowHeight() * visibleRows;
table.setPreferredScrollableViewportSize(size);
Now your JTable, and its enclosing JScrollPane, will have a preferred size consistent with what I think you’re seeking, which means you can (and should) use pack().
dialog.pack();
dialog.setResizable(false);
If your table may potentially have a lot of rows, you should consider avoiding any restrictions on the size of the JDialog. If there are hundreds of rows, users will not appreciate being forced to look at only eight at a time.