It will be nice that when the frame is small, we can use the scroll bar to view the contents of the JTable and when the frame is larger than the JTable size, the table is able to automatically fill up the space. This can be achieved by the following methods
1. Override the method getScrollableTracksViewportWidth() and set the table's auto resize mode to AUTO_RESIZE_OFF.
JTable table = new JTable() {
private boolean doingLayout;
private boolean doingLayout;
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getWidth();
}
public void doLayout() {
if (getScrollableTracksViewportWidth()) {
autoResizeMode = AUTO_RESIZE_SUBSEQUENT_COLUMNS;
}
doingLayout = true;
super.doLayout();
doingLayout = false;
autoResizeMode = AUTO_RESIZE_OFF;
}
public void columnMarginChanged(ChangeEvent e) {
if (isEditing()) {
removeEditor();
}
TableColumn resizingColumn = getTableHeader().getResizingColumn();
// Need to do this here, before the parent's
// layout manager calls getPreferredSize().
if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF
&& !doingLayout) {
resizingColumn.setPreferredWidth(resizingColumn.getWidth());
}
resizeAndRepaint();
}
}
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane.add(scrollPane);
2. Use a ComponentListener to toggle the auto resize mode of the JTable between AUTO_RESIZE_OFF and AUTO_RESIZE_ALL_COLUMNS.
table.getParent().addComponentListener(new ComponentAdapter() {
public void componentResized(final ComponentEvent e) {
if (jTable.getPreferredSize().width < jTable.getParent().getWidth()) {
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
} else {
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
}
});
-------------------------------------------------------------------------
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
-----------------------------------------------------------------------------
Awesome, thanks!
ReplyDelete