简体   繁体   English

通过单击鼠标获取JTable的特定单元格的值

[英]Get the value of a specific cell of JTable with mouse clicking

在此处输入图片说明 I have a JTable and Given such codes: 我有一个JTable并给出了以下代码:

jTable.addMouseListener(new MouseAdapter(){
               public void mouseClicked(MouseEvent e){

                   System.out.println(jTable.getRowCount());
                   System.out.println(jTable.getModel().getValueAt(jTable.getRowCount(), 0));
               }
           });

If I click on a certain row, like in the picture above, I clicked the second row, how can I get that row's content?(How to get the Canada)? 如果单击某行(如上图所示),则单击第二行,如何获得该行的内容?(如何获得加拿大)?

Personally, I use the Mouse Clicked event. 就个人而言,我使用Mouse Clicked事件。 You could try something like this inside your event method: 您可以在事件方法中尝试以下操作:

private void myTableMouseClicked(java.awt.event.MouseEvent evt) {                                          
    int row = this.myTable.getSelectedRow();
    int column = this.myTable.getSelectedColumn();
    this.myTable.getValueAt(selectedRow, selectedColumn);
} 

Be aware that the getValueAt method returns an Object. 请注意, getValueAt方法返回一个Object。 You probably will need to cast the Object returned into the object it is supposed to be. 您可能需要将Object返回的对象转换为应该是的对象。 And also you could have a global variable that's going to have the value returned by getValueAt for using it as you need. 而且,您还可以拥有一个全局变量,该变量将具有getValueAt返回的值,以便根据需要使用它。

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM