我需要这样的行为:当鼠标光标指向JTable
单元格时 - 需要显示弹出菜单或类似的东西。没有单击单元格上的鼠标。有什么建议吗?
答案 0 :(得分:3)
JB Nizet有一个很好的观点。 OTOH,我准备了这个例子,'我们有技术'。
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
class TimesTable {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JTable t = new JTable(new TimesTableModel());
t.setDefaultRenderer(Object.class, new TimesTableRenderer());
JOptionPane.showMessageDialog(null, t);
}
});
}
}
class TimesTableRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
Component c = super.getTableCellRendererComponent(
table,value,isSelected,hasFocus,row,column);
JComponent jc = (JComponent)c;
jc.setToolTipText(
(row+1) + "x" + (column+1) + "=" + ((row+1)*(column+1)));
return jc;
}
}
class TimesTableModel extends DefaultTableModel {
@Override
public int getColumnCount() {
return 7;
}
@Override
public int getRowCount() {
return 5;
}
@Override
public Object getValueAt(int row, int column) {
return new Integer((row+1)*(column+1));
}
}
答案 1 :(得分:0)
感谢大家的关注。我需要更改单元格中的数据,但这样做只有一次鼠标点击!一个来自变体,我如何在上面说过。我有两个按钮弹出菜单:“访问”和“禁止”。而我想出了这样的解决方案......
public class PopupMenuMouseMotionListener implements MouseMotionListener {
private JXTreeTable jxTreeTable;
private TreeTableModel model;
private JPopupMenu popupMenu;
private boolean inCell = false;
private Rectangle r = null;
private boolean visible = false;
private long startTime = 0L;
private Component[] buttons;
PopupMenuMouseMotionListener(JXTreeTable jxTreeTable, TreeTableModel model, JPopupMenu popupMenu) {
this.jxTreeTable = jxTreeTable;
this.model = model;
this.popupMenu = popupMenu;
this.buttons = popupMenu.getComponents();
}
public void mouseDragged(MouseEvent event) {
//Does nothing
}
public void mouseMoved(MouseEvent event) {
Point point = event.getPoint();
int row = jxTreeTable.rowAtPoint(point);
int column = jxTreeTable.columnAtPoint(point);
double time = 0.0;
if (column >= 1) {
if (startTime == 0L) {
startTime = System.currentTimeMillis();
};
long ms = System.currentTimeMillis() - startTime;
time = ms / 1000 + ms % 1000;
if (r == null) {
r = jxTreeTable.getCellRect(row, column, false);
};
inCell = true;
Component c = event.getComponent();
if (inCell && r.contains(point)) {
if (time >= 100.50 && visible == false) {
popupMenu.show(c, r.x, r.y);
visible = true;
}
} else {
popupMenu.setVisible(false);
inCell = false;
startTime = 0L;
r = null;
visible = false;
}
} else popupMenu.setVisible(false);
}
}
你怎么看?