0

另一个问题。我想双击打开带有表单的新窗口的 JTable。所以最后我做到了:

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
        public void valueChanged(ListSelectionEvent event){
            int viewRow = table.getSelectedRow();
            if(viewRow < 0)
                System.out.println("LOL");
            else{
                final int modelRow = table.convertRowIndexToModel(viewRow);
                table.addMouseListener(new MouseAdapter(){
                    public void mouseClicked(MouseEvent e){
                        if(e.getClickCount() == 2)
                            try {
                                new BookForm();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }

                    }
                });
            }   

        }
    });

它有效,但并不完美。第一次双击 JTable 时,它​​会打开 2 个窗口(为什么不打开一个?),下一次它会打开 4 个窗口,接下来会打开 6 个窗口,等等。有什么想法吗?也许我应该使用不同的方法?感谢帮助!

4

1 回答 1

2

花点时间看看你的代码......

每次选择更改时,您都会添加一个新的MouseListener

table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
    public void valueChanged(ListSelectionEvent event){
        int viewRow = table.getSelectedRow();
        if(viewRow < 0)
            System.out.println("LOL");
        else{
            // You add a new mouse listener...
            final int modelRow = table.convertRowIndexToModel(viewRow);
            table.addMouseListener(new MouseAdapter(){
                public void mouseClicked(MouseEvent e){
                    if(e.getClickCount() == 2)
                        try {
                            new BookForm();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }

                }
            });
        }   

    }
});

因此,当您“最终”双击一行时,您将MouseListener在表格中注册 1-n s...

您可以摆脱选择侦听器并简单地将其MouseListener直接添加到表中...

table.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
        if(e.getClickCount() == 2)
            int selectedRow = table.getSelectedRow();
            if (selectedRow > -1) {
                int modelRow = table.convertRowIndexToModel(selectedRow);
                try {
                    new BookForm();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
    }
});

还可以看看The Use of Multiple JFrames: Good or Bad Practice?在你用大量新窗口轰炸你的用户之前......

于 2013-08-12T01:51:25.717 回答