弹出菜单项在单击时没有响应

时间:2015-02-15 09:05:52

标签: java swing

我已经编写了这段代码,用弹出式菜单在我的表中添加和删除一行,但是当我点击弹出菜单上的相应选项(添加和删除)时,此代码既不删除也不添加行,请帮忙。

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


    public class B extends MouseAdapter {

        JFrame frame = new JFrame();
        Object rows[][] = new Object[5][3];
        String colums[] = {"A","B","C"};
        DefaultTableModel model = new DefaultTableModel(rows,colums);
        JTable table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);
        JPopupMenu popup = new JPopupMenu();
        JMenuItem item1 = new JMenuItem("ADD");
        JMenuItem item2 = new JMenuItem("DELETE");
        Object[] row = {"Column 1", "Column 2", "Column 3"};

        public static void main(String arg[]) {
            new B();
        }

        B() {
            frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            table.addMouseListener(this);
            item1.addMouseListener(this);
            item2.addMouseListener(this);
            popup.add(item1);
            popup.add(item2);
            table.add(popup);
            frame.add(scroll);
            frame.setVisible(true);
        }

        public void mouseClicked(MouseEvent click) {

            if(click.getSource()==table && click.getButton()==3)    
                popup.show(table,click.getX(),click.getY());
            else if(click.getSource()==item1)
                model.addRow(row);
            else if(click.getSource()==item2)
                model.removeRow( table.rowAtPoint(click.getPoint()) );
        }

    }

1 个答案:

答案 0 :(得分:0)

您应该使用equals方法,而不是使用==比较对象(比较两个组件的引用)。因此,请更改以下内容:

click.getSource()==table 

click.getSource().equals(table)