如何在java中为多个组件添加多个侦听器

时间:2014-07-28 13:06:20

标签: java swing jtable

我创建了一个包含多个jTable的java swing应用程序。我添加了多个鼠标监听器,用于使用匿名类创建上下文菜单。但每次动作侦听器仅指向第一个表。请帮忙。 每次获得的是第一张表的更新值。

  • 我有3个名为jTableNum1,jTableNum2,jTableNum3的Jtables。
  • 我想要的是在我的三个Jtables中为每个单元格剪切,复制,粘贴功能。
  • 所以我创造了popumenus&叫做:

     jTableNum1.addMouseListener(new MouseAdapter() {

               @Override
               public void mouseClicked(MouseEvent e) {
                     rowH = jTableNum1.getSelectedRow();
                    if (e.isPopupTrigger()) {
                       highlightRow(e);
                       doPopup(e);
                   }
               }

               @Override
               public void mouseReleased(MouseEvent e) {

                   if (e.isPopupTrigger()) {
                       highlightRow(e);

                       doPopup(e);
                   }
               }

               protected void doPopup(MouseEvent e) {
                  popupMenu.show(e.getComponent(), e.getX(), e.getY());
               }

               protected void highlightRow(MouseEvent e) {
                   JTable table = (JTable) e.getSource();
                   Point point = e.getPoint();
                   int row = table.rowAtPoint(point);
                   int col = table.columnAtPoint(point);

                   table.setRowSelectionInterval(row, row);
                   table.setColumnSelectionInterval(col, col);
               }

           });

   popupMenu1.add(new clearFuncs (1,rowH));// arg1=  tableNumber , arg2 = the highlighted row)

-

- //类似于jTableNum2& jTableNum3

   public class clearFuncs extends AbstractAction {
   int num;
   int rowH;
   public clearFuncs (int num,int r) {
        this.num = num;
        this.rowH = r;
    putValue(NAME, "Clear");
    }public clearFuncs (int num) {
        this.num = num;
    putValue(NAME, "Clear");
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        int row;
        switch(num){
        case 1: row = jTableNum1.getSelectedRow();
        System.out.println("row = "+rowH);
        jTableNum1.setValueAt("", row, 0);
                break;
        case 2: row = jTableNum2.getSelectedRow();
        System.out.println("row = "+row);
        jTableNum2.setValueAt("", row, 0);
        break;
        case 3: row = jTableNum3.getSelectedRow();
        System.out.println("row = "+row);
        jTableNum3.setValueAt("", row, 0);
        break;

        }          
    }

}               

-

1 个答案:

答案 0 :(得分:3)

我遇到的问题是你正在引用Action ClearFuncs中的第一个表。您可以轻松转换为将用于所有表的通用操作。与MouseAdapter一样。它可以很容易地重新配置为用于所有表,以避免重复。请参阅下面的示例,我这样做。如果您有任何问题,请发表评论。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TableContextMenuDemo {

    @SuppressWarnings("serial")
    private JTable createTableWithRandomData(int tableNumber) {
        String[] cols = { "col 1", "col 2", "col 3" };
        JTable table = new JTable(new DefaultTableModel(getRandomData(10,
                cols.length), cols)) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(200, 150);
            }
        };
        ClearFuncs action1 = new ClearFuncs(tableNumber, table);
        SayHelloAction action2 = new SayHelloAction();
        JPopupMenu popupMenu = createPopupMenu(action1, action2);
        PopupAdapter listener = new PopupAdapter(popupMenu);
        table.addMouseListener(listener);
        return table;
    }

    class SayHelloAction extends AbstractAction {
        public SayHelloAction() {
            putValue(NAME, "Hello");
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Hello World");

        }
    }

    private Integer[][] getRandomData(int rows, int cols) {
        Random random = new Random();
        Integer[][] data = new Integer[rows][cols];
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                data[i][j] = random.nextInt(Integer.MAX_VALUE);
            }
        }
        return data;
    }

    private JPopupMenu createPopupMenu(Action... actions) {
        JPopupMenu menu = new JPopupMenu();
        for (Action a : actions) {
            menu.add(a);
        }
        return menu;
    }

    class PopupAdapter extends MouseAdapter {
        JPopupMenu popupMenu;

        public PopupAdapter(final JPopupMenu popupMenu) {
            this.popupMenu = popupMenu;
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.isPopupTrigger()) {
                highlightRow(e);
                doPopup(e);
            }
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                highlightRow(e);
                doPopup(e);
            }
        }

        protected void doPopup(MouseEvent e) {
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }

        protected void highlightRow(MouseEvent e) {
            JTable table = (JTable) e.getSource();
            Point point = e.getPoint();
            int row = table.rowAtPoint(point);
            int col = table.columnAtPoint(point);

            table.setRowSelectionInterval(row, row);
            table.setColumnSelectionInterval(col, col);
        }

    }

    class ClearFuncs extends AbstractAction {
        int num;

        private JTable table;

        public ClearFuncs(int num, JTable table) {
            this.num = num;
            this.table = table;
            putValue(NAME, "Clear");
        }

        public ClearFuncs(int num) {
            this.num = num;
            putValue(NAME, "Clear");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int col = table.getSelectedColumn();
            int row = table.getSelectedRow();
            System.out.println("row = " + row + ", col = " + col + ", table: " + num);
            table.setValueAt("", row, col);
        }
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        for (int i = 1; i <= 3; i++) {
            JTable table = createTableWithRandomData(i);
            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane
                    .setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
            frame.add(scrollPane);
        }
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TableContextMenuDemo().createAndShowGui();
            }
        });
    }
}