java - JTable,当光标仍指向单元格内部时无法检索特定单元格上的数据

标签 java swing jtable tablecelleditor

我想发布图片,但我在此网站上没有声誉,但我在下面描述了我的问题:

| 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/

相关文章:

java - 我可以向 JAX-RS 方法添加自定义注释以验证访问吗?

java - 为什么以相反的执行顺序处理 try-with-resource 的抑制异常?

java - 制作两个选项窗口的最佳方法是什么?

java - 如何让jtable成为jtree的一个节点

java - JTable 排序 - 选择一行

java - 为什么我在 Java/Android 中得到空 SQLite 字段的 "0.0"?

java - 错误: on a null object reference

java - 与网页通信

java - 如何防止 LayoutManager 过度收缩我的组件?

java - 图像未显示在 JPanel 上?