如何确定选择了 JTable 中的哪个单元格?
我在 GUI 中有一个 JTable
,我想根据用户单击的单元格的值返回一个数字。这是代码:
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));
}
});
我对此有几个问题。首先,这个方法使我的表格可编辑。在使用此方法之前,我无法编辑表格,但现在我可以删除条目。我查看了API,但不知道为什么会这样。其次,如果我单击第 3 行中的一个单元格,然后单击第 3 行中的另一行,则不会注册任何事件。如何通过单击当前选定行上的单元格来创建事件?
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. 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. 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. How can I make an event from clicking in a cell on the currently selected row?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种常见的方法是通过事件获取用户单击的点:
这是使用选择模式的第二个选项:
如果您选择:
那么您的 JTable 将不可编辑。
最后,为了获取您想要的值,您只需调用 JTable 模型的 getValueAt(row,col) 即可,或者获取如下内容:
A common method is to get the point where the user clicked through the event:
Here is a second option using selection mode:
If you go:
Then your JTable will not be editable.
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: