我想张贴一张照片,但我在这个网站上没有声望,但我在下面描述了我的问题:
| 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);
} }
答案 0 :(得分:3)
您的示例(大部分)工作正常。
我假设您的意思是在单元格可编辑时它不会返回编辑器显示的值吗?
这是有道理的,因为编辑器包含的值尚未提交给模型。
如果表格在编辑模型中,您可以做的是停止当前的编辑过程,这会将编辑器中的值提交给模型,然后您可以阅读...
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));
}
}
当然,这一切都取决于你想要实现的目标......
答案 1 :(得分:2)
您需要停止编辑单元格。 Table Stop Editing显示了两种方法。 MadProgrammer演示的另一个允许您在JTable上设置属性。