最近遇到个关于JTable列宽变动的需求:拖动改变JTable某一列的宽度后需要做一些业务处理。
JTable的ColumnModel有个监听列模型的方法(TableColumnModelListener),但这个是拖动时响应,且拿不到列信息,这不符合我想要的。
那只能从鼠标事件的语义去分析了,在拖动列的响应事件中判断是否是目标列,在结束拖动时鼠标的释放事件中去完成业务工作。
查看了下JTable的API,可以给JTableHeader加上鼠标监听。
下面代码即监听“C2”列的demo:
1 public class JTableTest extends JFrame{
2 JScrollPane sp1 = new JScrollPane();
3 JTable table = new JTable();
4 DefaultTableModel tm = new DefaultTableModel();
5 enum ColumnName {
6 C1,C2,C3
7 }
8
9 void doSomething(){
10 int colNum = tm.getColumnCount();
11 for( int i = 0; i < colNum; i++ ){
12 if( ColumnName.C2.name().equals( table.getColumnName( i ) ) ){
13 TableColumn tc = table.getColumnModel().getColumn( i );
14 System.out.println( "width: " + tc.getWidth() );
15 // TODO : do something what you wanna
16 }
17 }
18 }
19
20 public JTableTest(){
21 this.setSize( 400, 300 );
22 this.getContentPane().add( sp1, BorderLayout.CENTER );
23 sp1.getViewport().add( table );
24 for( ColumnName col : ColumnName.values() ){
25 tm.addColumn( col );
26 }
27 table.setModel( tm );
28 class ChangedColumn{
29 boolean changed = false;
30 boolean isChanged(){
31 return changed;
32 }
33 void setChanged( boolean changed ){
34 this.changed = changed;
35 }
36 }
37 final ChangedColumn c2 = new ChangedColumn();
38 table.getTableHeader().addMouseListener( new MouseListener(){
39 @Override
40 public void mouseReleased( MouseEvent e ){
41 System.out.println( "released" );
42 if( c2.isChanged() ){
43 doSomething();
44 c2.setChanged( false );
45 }
46 }
47 @Override
48 public void mousePressed( MouseEvent e ){}
49 @Override
50 public void mouseExited( MouseEvent e ){}
51 @Override
52 public void mouseEntered( MouseEvent e ){}
53 @Override
54 public void mouseClicked( MouseEvent e ){}
55 } );
56 table.getTableHeader().addMouseMotionListener( new MouseMotionListener(){
57 @Override
58 public void mouseMoved( MouseEvent e ){}
59 @Override
60 public void mouseDragged( MouseEvent e ){
61 System.out.println( "dragging" );
62 TableColumn changedColumn = ( (JTableHeader)e.getSource() ).getResizingColumn();
63 if( changedColumn != null
64 && ColumnName.C2.name().equals( changedColumn.getHeaderValue() ) ){
65 c2.setChanged( true );
66 }
67 }
68 } );
69 addWindowListener( new WindowAdapter(){
70 public void windowClosing( WindowEvent e ){
71 System.exit( 0 );
72 }
73 } );
74 setVisible( true );
75 }
76
77 public static void main( String[] args ){
78 new JTableTest();
79 }
80 }