代码如下:
public class TableRowHeightFrame extends JFrame { private Vector<String> col = new Vector<String>(); private DefaultTableModel dm = new DefaultTableModel(col,0); private JScrollPane jScrollPane1 = new JScrollPane(); private JTable table = new JTable(dm); public TableRowHeightFrame() { try { jbInit(); loadata(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { TableRowHeightFrame frm = new TableRowHeightFrame(); frm.setBounds(400,300,600,400); frm.setVisible(true); } private void jbInit() throws Exception { this.getContentPane().add(jScrollPane1, BorderLayout.CENTER); jScrollPane1.getViewport().add(table, null); MouseAdapterListener listener = new MouseAdapterListener(); table.addMouseListener(listener); table.addMouseMotionListener(listener); col.add( "编号 "); col.add( "告警名称"); col.add( "告警等级 "); col.add( "已处理"); dm.setColumnIdentifiers(col); } void loadata(){ dm.addRow(new Object[]{ "1001", "设备离线", "2", "已处理"}); dm.addRow(new Object[]{ "1002", "卡拔出", "3 ", "已处理"}); dm.addRow(new Object[]{ "1003", "光信号丢失", "2 ", "未处理"}); dm.addRow(new Object[]{ "1004", "网络错误", "4 ", "已处理"}); dm.addRow(new Object[]{ "1004", "网络错误", "4 ", "已处理"}); dm.addRow(new Object[]{ "1004", "网络错误", "4 ", "已处理"}); dm.addRow(new Object[]{ "1004", "网络错误", "4 ", "已处理"}); } class MouseAdapterListener extends java.awt.event.MouseMotionAdapter implements MouseListener{ int oldY = 0; int newY = 0; int row = 0; int oldHeight = 0; boolean drag = false; int increase = 0; public MouseAdapterListener(){ } public void mouseMoved(MouseEvent e) { int onRow = table.rowAtPoint(e.getPoint()); int height=0; for(int i = 0; i <= onRow;i++){ height = height+table.getRowHeight(i); } if(height - e.getY() < 3){ drag = true; table.setCursor(new Cursor(Cursor.N_RESIZE_CURSOR)); } else{ drag = false; table.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } public void mouseDragged(MouseEvent e) { if(drag){ int value = oldHeight+e.getY()-oldY; if(value<10) table.setRowHeight(row,10); else table.setRowHeight(row,oldHeight+e.getY()-oldY); } } public void mousePressed(MouseEvent e){ oldY = e.getY(); row = table.rowAtPoint(e.getPoint()); oldHeight = table.getRowHeight(row); } public void mouseReleased(MouseEvent e) { newY = e.getY(); table.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } public void mouseClicked(MouseEvent e){ } public void mouseEntered(MouseEvent e){ } public void mouseExited(MouseEvent e){ } } }
运行结果: