1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.RowSorter;
import javax.swing.JPanel;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.HeadlessException;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.BorderLayout;
/**
* @author bebe
*/
public class MyTableTest extends JFrame {
public MyTableTest() throws HeadlessException {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = GridBagConstraints.REMAINDER;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.weightx = 1.;
gbc.insets = new Insets(5, 5, 0, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
MyTableModel myFirstModel = new MyTableModel("table1");
MyTableModel mySecondModel = new MyTableModel("table2");
MyTableModel myThirdModel = new MyTableModel("table3");
JTable tableWithoutScrollPane = new JTable(myFirstModel);
JTable wichtounetTable = new JTable(mySecondModel);
JTable tableWithScrollPane = new JTable(mySecondModel);
/* no scrollpane */
add(tableWithoutScrollPane, gbc);
/* wichtounet's solution */
RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(mySecondModel);
wichtounetTable.setRowSorter(sorter);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(wichtounetTable.getTableHeader(), BorderLayout.PAGE_START);
panel.add(wichtounetTable, BorderLayout.CENTER);
add(panel, gbc);
/* with scroll pane */
int preferedHeight = tableWithScrollPane.getTableHeader().getHeight() + tableWithScrollPane.getRowHeight() * tableWithScrollPane.getModel().getRowCount();
tableWithScrollPane.setPreferredScrollableViewportSize(new Dimension(0, preferedHeight));
sorter = new TableRowSorter<TableModel>(myThirdModel);
tableWithScrollPane.setRowSorter(sorter);
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.NORTH;
add(new JScrollPane(tableWithScrollPane), gbc);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
MyTableTest t = new MyTableTest();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setSize(800, 600);
t.setLocationRelativeTo(null);
t.setVisible(true);
}
});
}
} |