java事件显示行列,Java:从popupmenu actionListener事件获取行数据

I'm having a little scenario here that maybe a duplicate. I have JTable where i show some data, i have a mouselistener that listens for right clicks on the table and displays a popup menu with one menuitem. My goal is that when the user clicks the menuitem, i get the values from the table and feed them into a custom dialog which has some fill in fields, so that the user doesn't have to feed the whole dialog by hand since i will feed the dialog with the values selected on the table. but my problem is that the menuitem actionevent doesn't have a way of getting the point so that i can use table.getRowAt(). i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable that can then be accessed by the actionlistener for the menuitem.

i want it to look like this

theScrollPane.getViewport().add(myJTable, null);

JMenuItem menuItem = new JMenuItem(clickMe);

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

menuItemActionPerformed(e);

}

});

MouseListener popupListener = new PopupListener();

popupMenu.add(menuItem);

myJTable.addMouseListener(popupListener);

protected void menuItemActionPerformed (ActionEvent e) {

// what to do here to get the table row data

// and send it to my custom dialog via it's constructor ???

}

// a simple nested class for the popup

class PopupListener extends MouseAdapter {

public void mousePressed(MouseEvent e) {

int row = myJTable.rowAtPoint(e.getPoint());

int selectedRow = myJTable.getSelectedRow();

// just to make sure the popup appears only where the row is

// selected

if (row == selectedRow) {

showPopup(e);

}

}

public void mouseReleased(MouseEvent e) {

int row = myJTable.rowAtPoint(e.getPoint());

int selectedRow = myJTable.getSelectedRow();

if (row == selectedRow) {

showPopup(e);

}

}

private void showPopup(MouseEvent e) {

if (e.isPopupTrigger()) {

popupMenu.show(e.getComponent(), e.getX(), e.getY());

}

}

}

so my question is, is saving the row number the only way that i can do this or is there a better way?

解决方案

i have read another comment (check here https://stackoverflow.com/a/4122082/1788917) where i have been told that i can save the row number in a variable

You read the wrong comment.

If you read the answer above that link (ie. the one with 7 votes) you will see the solution is to select the row you clicked on BEFORE showing the popup menu. Then in your menu item Action you can reference

table.getSelectedRow();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值