当前位置: 首页 > 知识库问答 >
问题:

在jtable上双击错误行为

孔运良
2023-03-14

日安!

我有一个jTable,我正在用JButton监听器填充它。在通过鼠标双击填充jTable之后,我调用JoptionPane.ShowMessageDialog。在那个问题解决之后。再次单击JButton后,jTable将再次填充。如果我再次双击Row\Cell,它将显示JOptionPane的2条消息,而不是一条。据我所知,我需要刷新模型,但我没有成功。

我的代码:

form.java

    btnExec = new JButton("Exec");
    table = new JTable();
    scrollPane.setViewportView(table);
    // Create Button Listener
    ActionListener startProcess = new ExecButtonPressed();
    btnExec.addActionListener(startProcess);
public class ExecButtonPressed implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
            try {
                System.out.println("table rows:" + Form.table.getRowCount());
                DefaultTableModel tableModel = new DefaultTableModel();
                prepare(tableModel); // create headers
                fill(tableModel);   // add rows

                Form.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                Form.table.setModel(tableModel);

                sortresize(Form.table); //resize width of columns + sort by id desc
                Form.table.setDefaultEditor(Object.class, null);


                DoubleClicker.whattodo(); // class of double-click behavior logic


            }catch (Exception e1) {
                e1.printStackTrace();
            }

    }

//
    private void prepare(DefaultTableModel tableModel) throws Exception {
        try {
            tableModel.addColumn("id");
            tableModel.addColumn("name");
            tableModel.addColumn("age");
        }catch (Exception e1) {
            e1.printStackTrace();
        }
    }


//
    private void fill(DefaultTableModel tableModel) {
        Object [] line = {"01", "Qw" , "20"};
        tableModel.addRow(line);
        Object [] line2 = {"02", "As" , "21"};
        tableModel.addRow(line2);
        Object [] line3 = {"03", "Zx" , "22"};
        tableModel.addRow(line3);
    }

//
    private void sortresize(JTable table) {
        //Resize width
        for (int column = 0; column < table.getColumnCount(); column++) {
            TableColumn tableColumn = table.getColumnModel().getColumn(column);
            if (column  == 0) {
                tableColumn.setPreferredWidth( 45 ); 
            } else if (column   == 1){
                tableColumn.setPreferredWidth( 50 ); 
            } else if (column   == 2){
                tableColumn.setPreferredWidth( 55 ); 
            } 
        }


        //Sort table.
        if (table.getRowCount() > 1){
            TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
            table.setRowSorter(sorter);
            List<RowSorter.SortKey> sortKeys = new ArrayList<>();

            int columnIndexToSort = 0;
            sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.DESCENDING));

            sorter.setSortKeys(sortKeys);
            sorter.sort();
        };

    }

//  

}
public class DoubleClicker {

    public static void whattodo() {
        Form.table.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent mouseEvent)  {
                try {
                    System.out.println("click:" + mouseEvent.getClickCount());
                    Form.table = (JTable) mouseEvent.getSource();
                    Point point = mouseEvent.getPoint();
                    int row = Form.table.rowAtPoint(point);
                    int columnid = Form.table.columnAtPoint(point);

                    Form.table.convertRowIndexToModel(row);
                    Form.table.convertColumnIndexToModel(columnid);

                    if (mouseEvent.getClickCount() == 2 && Form.table.getSelectedRow() != -1) {
                        if (Form.table.getColumnName(columnid).equalsIgnoreCase("name")) {
                            JOptionPane.showMessageDialog(null, 
                              (String) Form.table.getValueAt(row,columnid), "Selected name", 1);
                        }
                    }

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }
}

我试过不同的选择

tableModel.setRowCount(0); 
tableModel.getDataVector().removeAllElements(); 
tableModel.fireTableDataChanged();

也许我放错地方了?因为每次鼠标点击都会在执行第二个按钮时注册两次。

更新:我已添加

System.out.println("table rows:" + Form.table.getRowCount());
System.out.println("click:" + mouseEvent.getClickCount());
    public class Form {

    private JFrame frame;
    public static JTable table;
    public static JButton btnExec;
    public static JScrollPane scrollPane;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Form window = new Form();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Form() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        btnExec = new JButton("Exec");
        btnExec.setBounds(10, 11, 89, 23);
        frame.getContentPane().add(btnExec);

        scrollPane = new JScrollPane();
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(10, 45, 369, 174);
        frame.getContentPane().add(scrollPane);

        table = new JTable();
        scrollPane.setViewportView(table);


        // Create Button Listener
        ActionListener startProcess = new ExecButtonPressed();
        btnExec.addActionListener(startProcess);




    }
}

共有1个答案

洪楷
2023-03-14

在coderanch论坛上得到了一个答案,决定在那里提交。也许将来会有人需要它。

解决方案是在创建表时(而不是在ActionListener的actionPerformed()方法中)添加应该添加到表中的MouseListener。

因此,我转移了doubleClicker.WhatToDo();//双击行为逻辑类从ExecButtonPressed.java到Form.java

table = new JTable();
scrollPane.setViewportView(Form.table);
DoubleClicker.whattodo(); // class of double-click behavior logic
 类似资料:
  • 问题内容: 这几乎使我失败了。 在XP和早期版本的Windows上,您可以自定义“打开方式”文件类型以包含java-jar“ myjar.jar”,但是在Vista上,此功能似乎已删除。我当然可以创建一个.bat文件来启动我的应用程序,但是可以使Vista根据需要执行.jar吗? 问题答案: 您可以从命令行使用2个实用程序来执行此操作。 第一个是ASSOC,用于创建文件关联。要验证是否为JAR类型

  • 我在JTable上遇到了问题。当我以固定长度的文本字段作为编辑器在单元格中键入时,当达到长度时,我会自动跳到下一行。那样的话,我就可以继续写下去了。之后,当我想更改第一行中的一些文本并双击单元格时,文本将消失。 奇怪的是,当我按“Enter”转到下一行,双击第一行时,文本并没有消失。

  • 问题内容: 我有一个使用自定义RowSorter可排序列的JTable。我假设RowSorter类自动将自身作为MouseListener添加到表的ColumnHeader中,因为它无需执行任何自定义鼠标侦听代码即可自动执行排序。这很完美。 我还添加了一些代码(基于此示例),该代码允许用户通过双击列标题中的表之间的空间来调整表列的大小(模仿Excel的行为)。问题是,当用户双击标题以调整列的大小时

  • 问题内容: 我有一个叫其IS 我想计算每个单词的。 我的问题是,返回 我不明白为什么每学期都会回来。我如何解决它? 我应该得到类似 问题答案: 您正在执行整数除法,然后键入强制转换: 类型转换将除法中的元素之一转换为浮点除法:

  • 问题内容: 我有一个JTable,我需要删除一行,即选定的行。 所以首先,我得到表模型: 然后是选定的行(如果选择了第二行,则返回1,这是可以理解的,因为行从零开始): 然后,我尝试删除该行: 然后我再次设置表模型: 这实现的是删除完全随机的行。我根本不明白为什么。我已经使用table.setRowSorter(sorter)对表进行了排序,但是我不知道为什么这应该是一个问题。如果绝对需要SSCC

  • 问题内容: 经过一番工作后,我的路线申请工作正常。我唯一想添加的就是双击放大功能,但我不知道如何操作。 你能给我一个提示吗? 问题答案: 实现GestureListener来接收doubleTap事件。