gpt4 book ai didi

java - 在 JTable 中鼠标悬停时创建信息面板?工具提示可能不够

转载 作者:行者123 更新时间:2023-11-30 05:52:36 27 4
gpt4 key购买 nike

我想使用 Java SwingJTable 单元格上显示一个信息框,所以有多个部分

  1. 如何捕捉表格单元格中的鼠标悬停事件?我必须能够设置单元格内容,然后获取数据。
  2. 如何在将鼠标悬停在该单元格上时显示带有动态服务器数据的面板/框?
  3. 如何缓存信息面板/框,这样我就不必在每次鼠标悬停时都查询服务器?

例子:

在表格单元格中,我输入:94903。按 Tab 键或输入后,单元格设置为数字。鼠标悬停时,它会显示一个包含姓名、地址、电话号码、电子邮件等的框。

谢谢!

最佳答案

您可以使用 HTML 格式化工具提示文本,这将允许您向工具提示提供复杂的信息结构,而无需编写您自己的解决方案,也无需为此付出代价。唯一的问题是工具提示将被自动丢弃。

如果还是不行,你可以试试:

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.*;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.Timer;

public class TestTable {

private Timer showTimer;
private Timer disposeTimer;
private JTable table;
private Point hintCell;
private MyPopup popup; // Inherites from JPopupMenu

public TestTable() {

showTimer = new Timer(1500, new ShowPopupActionHandler());
showTimer.setRepeats(false);
showTimer.setCoalesce(true);

disposeTimer = new Timer(5000, new DisposePopupActionHandler());
disposeTimer.setRepeats(false);
disposeTimer.setCoalesce(true);

table.addMouseMotionListener(new MouseMotionAdapter() {

@Override
public void mouseMoved(MouseEvent e) {

Point p = e.getPoint();
int row = table.rowAtPoint(p);
int col = table.columnAtPoint(p);

if ((row > -1 && row < table.getRowCount()) && (col > -1 && col < table.getColumnCount())) {

if (hintCell == null || (hintCell.x != col || hintCell.y != row)) {

hintCell = new Point(col, row);
Object value = table.getValueAt(row, col);
// Depending on how the data is stored, you may need to load more data
// here...
// You will probably want to maintain a reference to the object hint data

showTimer.restart();

}

}

}
});

}

protected MyPopup getHintPopup() {

if (popup == null) {

// Construct the popup...

}

return popup;

}

public class ShowPopupActionHandler implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {

if (hintCell != null) {

disposeTimer.stop(); // don't want it going off while we're setting up

MyPopup popup = getHintPopup();
popup.setVisible(false);

// You might want to check that the object hint data is update and valid...
Rectangle bounds = table.getCellRect(hintCell.y, hintCell.x, true);
int x = bounds.x;
int y = bounds.y + bounds.height;

popup.show(table, x, y);

disposeTimer.start();

}

}
}

public class DisposePopupActionHandler implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {

MyPopup popup = getHintPopup();
popup.setVisible(false);

}
}
}

现在,我还没有构建弹出窗口,我也会使用 Bob Sinclar 的回答中的弹出菜单

关于java - 在 JTable 中鼠标悬停时创建信息面板?工具提示可能不够,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531010/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com