简体   繁体   中英

Double-click wrong behaviour at jtable

Good day!

i have a jTable, i am filling it by JButton listener. after jTable is filled by mouse double-click i invoke JOptionPane.showMessageDialog. After that problem is accured. After clicking on JButton again jTable is filled again. And if i double click on row\\cell again it will show me 2 messages by JOptionPane instead of one. As i understand i need to refresh model but i didn`t success.

My code:

Form.java

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

ExecButtonPressed.java

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();
        };

    }

//  

}

DoubleClicker.java

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();
                }
            }
        });
    }
}

I tried different options like

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

maybe i put it in wrong place? because every mouse click is registered twice at 2nd button execution.


Update: i added

System.out.println("table rows:" + Form.table.getRowCount());

right after public void actionPerformed(ActionEvent e) { and as i can see in console, Form.table.getRowCount() == 3 after second button execution. Also added

System.out.println("click:" + mouseEvent.getClickCount());

as the first line of public void mousePressed(MouseEvent mouseEvent) as i can see, after 2nd button execution in every click on table is done twice i got : click:1 click:1 at the first execution it`s just click:1

It seems like there is one view after another.

the entire Form.java in case someone would be generous to compile

    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);




    }
}

Got an answer at coderanch forum, decided to submit it there. maybe some one will need it in the future.

The solution is to add the MouseListener should be added to the table when you create the table (not in the actionPerformed() method of the ActionListener).

so i've transfer DoubleClicker.whattodo(); // class of double-click behavior logic DoubleClicker.whattodo(); // class of double-click behavior logic from ExecButtonPressed.java to Form.java:

table = new JTable();
scrollPane.setViewportView(Form.table);
DoubleClicker.whattodo(); // class of double-click behavior logic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM