I've been having trouble making a JFrame that holds a JTable in a JScrollPane, where I set the size of the JTable to be close to the size of the JFrame. Basically, I thought I would be able to listen for the event of resizing, get the new height and width and set the table to that width and that height, minus a little bit for an okay button on the bottom of the panel. However, while I am able to find the size of the window as it resizes, it simply seems that setSize and the assoicated methods do not have the intended effect on my JTable. I've tried a number of things, but it just resizes it to the incorrect number. That is, I can table.setSize(x, y) and then table.getSize() returns values different from the x and y I just found!!
I've written a really simple program that demonstrates the problem. It does occur in this code, but it isn't nearly as severe:
package src;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import javax.swing.JTable;
public class Test extends JFrame {
public static void main(String args[]) {
new Test();
}
private Container c;
private GridBagConstraints constraints = new GridBagConstraints();
private GridBagLayout layout = new GridBagLayout();
private JTable table;
public Test() {
setSize(300, 400);
constraints.insets = new Insets(4, 4, 4, 4);
constraints.fill = GridBagConstraints.BOTH;
c = getContentPane();
c.setLayout(layout);
setTitle("table.setSize() does not work as expected. Resize this window to see.");
table = new JTable();
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(ComponentEvent event) {
System.out.println("Window resized to " + getWidth() + " , " + getHeight());
Dimension size = new Dimension(getWidth() - 20, getHeight() / 2);
//table.setMaximumSize(size);
//table.setPreferredSize(size);
//table.setMinimumSize(size);
table.setSize(size); //toggle some of these on and off to get closer to having it do what it should.
validate();
System.out.println("Tried to set to " + size + " but is now " + table.getSize());
}
});
addComponent(table, 0, 0, 4, 3);
pack();
show();
}
private void addComponent(Component component, int row, int column, int width, int height) {
constraints.gridx = column;
constraints.gridy = row;
constraints.gridwidth = width;
constraints.gridheight = height;
layout.setConstraints(component, constraints);
c.add(component);
}
}
Thanks in advance!
Andy