我有两个JTable,他们必须互相同步。 这两个JTable是允许设置录制的。
所以我想知道在移动列时如何同步JTableHeader行为。
非常感谢,伙计。
答案 0 :(得分:1)
为此,您可以使用TableColumnModelListener
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.DefaultTableModel;
public class Example {
public static void main(String[] args) {
new Example();
}
public Example() {
JFrame frame = new JFrame("Rotation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable t = new JTable(new DefaultTableModel(new Object[][]{{1,2}},new Object[]{"1","2"}));
final JTable t1 = new JTable(new DefaultTableModel(new Object[][]{{1,2}},new Object[]{"1","2"}));
frame.getContentPane().add(new JScrollPane(t),BorderLayout.WEST);
frame.getContentPane().add(new JScrollPane(t1),BorderLayout.EAST);
t.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
@Override
public void columnSelectionChanged(ListSelectionEvent arg0) {
}
@Override
public void columnRemoved(TableColumnModelEvent arg0) {
}
@Override
public void columnMoved(TableColumnModelEvent arg0) {
int fromIndex = arg0.getFromIndex();
int toIndex = arg0.getToIndex();
t1.moveColumn(fromIndex, toIndex);
}
@Override
public void columnMarginChanged(ChangeEvent arg0) {
}
@Override
public void columnAdded(TableColumnModelEvent arg0) {
}
});
frame.pack();
frame.setVisible(true);
}
}
。这允许您根据源表交换其他表中的列。示例代码:
{{1}}
答案 1 :(得分:0)
我的代码如下
public static void syncTableColumnOrder(final JTable main, final JTable... tables) {
/* if table is not reordering-allowed, this method is meaningless */
if (!main.getReorderingAllowed())
return;
/* if two tables trigger event each other, it'll be infinite loop */
for (JTable table : tables) {
if (table == null) continue;
table.setReorderingAllowed(false);
}
/* when main table moves coloumn, effect others */
main.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
@Override
public void columnAdded(TableColumnModelEvent e) {}
@Override
public void columnRemoved(TableColumnModelEvent e) {}
@Override
public void columnMoved(TableColumnModelEvent e) {
for (JTable table : tables) {
table.moveColumn(e.getFromIndex(), e.getToIndex());
}
}
@Override
public void columnMarginChanged(ChangeEvent e) {}
@Override
public void columnSelectionChanged(ListSelectionEvent e) {}
});
}