我想发布图片,但我在此网站上没有声誉,但我在下面描述了我的问题:
| Name | Grade | __________________ | Febri | 60| <---- if this is a cell (row0,column1), I can't retrieve data on this cell if cursor is still pointing inside that cell. take a look : System.out.println(mytable.getValueAt(0,0)); --> output : Febri System.out.println(mytable.getValueAt(0,1)); -- > output : that's because my mouse's cursor is still pointing inside that cell .. Any suggestions? Is this problem related to mouse listener? Please help , thx.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class myTable extends JFrame {
String heads[] = { "Name", "Grade" };
Object[][] data = { { "Febri", "60" } };
JTable table;
JButton button;
JScrollPane scroll;
public myTable() {
setLayout(new FlowLayout());
table = new JTable(data, heads);
scroll =new JScrollPane(table);
button = new JButton("Retrieve Data");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println(table.getValueAt(0, 0));
System.out.println(table.getValueAt(0, 1));
}
}
});
add(scroll);
}
public static void main(String args[])
{
myTable tbl = new myTable();
tbl.setVisible(true);
tbl.setSize(500, 400);
} }
最佳答案
您的示例(大部分)运行良好。
我假设您的意思是,当单元格可编辑时,它不会返回编辑器显示的值?
这是有道理的,因为编辑器包含的值尚未提交给模型。
如果表处于编辑模型中,您可以做的是停止当前编辑过程,这会将编辑器中的值提交到模型,然后您可以读取该值...
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
// Is the table in edit mode?
if (table.isEditing()) {
// Get the current editor
TableCellEditor editor = table.getCellEditor();
if (editor != null) {
// Try and stop the cell editing process
if (!editor.stopCellEditing()) {
// Cancel the editing if can't be stopped...
// You could handle an error state here instead...
editor.cancelCellEditing();
}
}
}
System.out.println(table.getValueAt(0, 0));
System.out.println(table.getValueAt(0, 1));
}
}
当然,这一切都取决于您想要实现的目标......
关于java - JTable,当光标仍指向单元格内部时无法检索特定单元格上的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975124/