我有一个JTable,我想用鼠标光标调整行高(就像在excel中一样)。你能建议我如何实现这个任务。
答案 0 :(得分:2)
很久以前在Sun / Oracle论坛上发现了这段代码......
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
public class TableRowResizer extends MouseInputAdapter
{
public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
private int mouseYOffset, resizingRow;
private Cursor otherCursor = resizeCursor;
private JTable table;
public TableRowResizer(JTable table){
this.table = table;
table.addMouseListener(this);
table.addMouseMotionListener(this);
}
private int getResizingRow(Point p){
return getResizingRow(p, table.rowAtPoint(p));
}
private int getResizingRow(Point p, int row){
if(row == -1){
return -1;
}
int col = table.columnAtPoint(p);
if(col==-1)
return -1;
Rectangle r = table.getCellRect(row, col, true);
r.grow(0, -3);
if(r.contains(p))
return -1;
int midPoint = r.y + r.height / 2;
int rowIndex = (p.y < midPoint) ? row - 1 : row;
return rowIndex;
}
public void mousePressed(MouseEvent e){
Point p = e.getPoint();
resizingRow = getResizingRow(p);
mouseYOffset = p.y - table.getRowHeight(resizingRow);
}
private void swapCursor(){
Cursor tmp = table.getCursor();
table.setCursor(otherCursor);
otherCursor = tmp;
}
public void mouseMoved(MouseEvent e){
if((getResizingRow(e.getPoint())>=0)
!= (table.getCursor() == resizeCursor)){
swapCursor();
}
}
public void mouseDragged(MouseEvent e){
int mouseY = e.getY();
if(resizingRow >= 0){
int newHeight = mouseY - mouseYOffset;
if(newHeight > 0)
table.setRowHeight(resizingRow, newHeight);
}
}
}
答案 1 :(得分:1)
如果JTable本身不支持它,那么你运气不好,因为这项任务很难管理。
您实际需要做的是写一个或两个听众:
MouseMotionListener
,可以跟踪拖动鼠标MouseListener
,能够跟踪所有其他鼠标操作从此开始,您必须了解用户何时开始将鼠标悬停在行分隔线上,然后使用正确的方法:setRowHeight(int,int)
(针对特定行)或setRowHeight(int)
(对于所有行)。
这并不容易,它建议你不要试图动态(鼠标移动时高度会更新)。