简体   繁体   English

如何确定JTable中的哪个单元格被选中?

[英]How can I determine which cell in a JTable was selected?

I have a JTable in a GUI and I want to return a number based on the value of the cell that a user clicks on. 我在GUI中有一个JTable ,我想根据用户点击的单元格的值返回一个数字。 This is the code: 这是代码:

ListSelectionModel newmodel = mytable.getSelectionModel();
newmodel.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
        int row = mytable.getSelectedRow();
        int column = mytable.getSelectedColumn();

        int cell = getNewNum();
        datefield.setText(String.valueOf(cell));
    }
});

I have a couple of problems with this. 我有几个问题。 Firstly this method makes my table editable. 首先,这种方法使我的表格可编辑。 Before I used this method I couldn't edit the table but now I can delete entries. 在我使用此方法之前,我无法编辑表,但现在我可以删除条目。 I looked in the API but I don't know why this is. 我查看了API,但我不知道为什么会这样。 Secondly, if I click on a cell in row 3, say, and then I click on another row in cell 3, no event is registered. 其次,如果我单击第3行中的单元格,然后单击单元格3中的另一行,则不会注册任何事件。 How can I make an event from clicking in a cell on the currently selected row? 如何通过单击当前所选行的单元格来创建事件?

A common method is to get the point where the user clicked through the event: 一种常见的方法是获取用户点击事件的点:

jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
    @Override
    public void mouseClicked(java.awt.event.MouseEvent evt) {
        int row = jTable1.rowAtPoint(evt.getPoint());
        int col = jTable1.columnAtPoint(evt.getPoint());
        if (row >= 0 && col >= 0) {
            ......

        }
    }
});

Here is a second option using selection mode: 以下是使用选择模式的第二个选项:

jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
       @Override
       public void mouseClicked(java.awt.event.MouseEvent evt) {
           ...
           int row = jTable1.getSelectedRow();
           int col = jTable1.getSelectedColumn());
           if (evt.getClickCount() > 1) { // double-click etc...
              ...

If you go: 如果你走的话:

public boolean isCellEditable(int row, int col) {
   return false;
}

Then your JTable will not be editable. 然后您的JTable将无法编辑。

Finally in order to get the value you want, you just need to call the getValueAt(row,col) of your JTable Model, or get the contents like this: 最后,为了获得您想要的值,您只需要调用JTable Model的getValueAt(row,col) ,或者获取如下内容:

Object foo = jTable1.getModel().getValueAt(row, col); 

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

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