如何在双击时定位(在 JXTable 中)不同行中的特定列值以打开新框架?
我现在有这个代码:
myTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JXTable target = (JXTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getTableColumn(3); //for example the third column
new Detail().setVisible(true);
}
}
});
使用此代码解决:
final JOptionPane pane = new JOptionPane((Frame) null, JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION);
final JDialog d = pane.createDialog((Frame) null, "Comments");
d.setModal(false);
d.setAlwaysOnTop(true);
d.pack();
myTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int row = myTable.rowAtPoint(e.getPoint());
Object value1 = myTable.getValueAt(row, 4);
pane.setMessage(value1);
if (!d.isVisible())
d.setLocationRelativeTo(myTable);
d.setVisible(true);
}
}
});
更新1:
正如@mKorbel所说,我想使用像this example这样的JPopupMenu (由@mKorbel 提供)。但是如何实现单击 JMenuItem 时打开的 JDialog。
private void createPopupMenu() {
JPopupMenu popup = new JPopupMenu();
JMenuItem MenuItemComments = new JMenuItem("Show Comments");
JMenuItem MenuItemReference = new JMenuItem("Show Reference");
popup.add(MenuItemComments);
popup.add(MenuItemReference);
MouseListener popupListener = new PopupListener(popup);
Table_Employee.addMouseListener(popupListener);
}
private class PopupListener extends MouseAdapter {
private JPopupMenu popup;
PopupListener(JPopupMenu popupMenu) {
popup = popupMenu;
}
@Override
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (Table_Employee.getSelectedRow() != -1) {
maybeShowPopup(e);
}
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
// get row that pointer is over
int row = Table_Employee.rowAtPoint(e.getPoint());
// if pointer is over a selected row, show popup
if (Table_Employee.isRowSelected(row)) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
最佳答案
不要在运行时创建新的
J(X)Frame
,该容器的内容将是相同的,没有理由,创建一次,重用该容器,为了在屏幕上可见(隐藏/显示)
,请使用setVisible(false/true)
不要创建
J(X)Frame
,而是创建一个J(X)Dialog
,其父级为JXTable
,那么对话框将以JXTables
为中心
您也可以使用
ListSelectionListener
,但使用单选模型阅读有关
JList
、JTable
和ListSelectionListener
的 Oracle 教程,SwingX 组件的逻辑是相同的
也是如此,我会使用JPopup as control for displaying the JDialog ,只是为了避免来自鼠标或键盘的烦人事件
编辑
必须添加
d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE)
,则JDialog
永远不会被关闭,只能改为setVisible(false);
必须对所选
JTable
行中的值进行编码,创建一个新的单独的 void,将
>JTable
行中的值填充到放入JDialog
中的JComponent
确保
J(X)Table
已将selectionMode
更改为单一选择
(非必须)现在您可以在屏幕上定位
JDialog
,JDialog
在屏幕上仍然不可见然后调用
d.setVisble(true)
,我建议将此代码行包装到invokeLater()
,然后JDialog
在所有更改完成后将可见,将此事件移动到事件调度线程的末尾
关于java - 定位特定的 JXTable 列值以在新框架中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11814998/