如何在Java中为多个组件添加多个侦听器 [英] How to add multiple listeners for multiple components in java

查看:99
本文介绍了如何在Java中为多个组件添加多个侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有多个jTable的Java swing应用程序.我添加了多个鼠标侦听器,以使用匿名类制作上下文菜单.但是每次动作侦听器仅指向第一个表时.请帮忙. 每次获取iam都是第一个表的更新值.

i created a java swing application that have multiple jTables. I added multiple mouse listeners for making context menu with anonymous classes. But each time the action listeners are pointing to the first table only. Please help. Each time iam getting is the updated value for first table .

    我有3个JTable,分别名为jTableNum1,jTableNum2,jTableNum3.
  • 我想对三个Jtables中的每个单元格进行剪切,复制,粘贴功能.
  • 所以我创建了popumenus&叫做:
  • i have 3 Jtables named jTableNum1, jTableNum2, jTableNum3.
  • what i want is cut, copy, paste function for each cell in my three Jtables.
  • so i created popumenus & called like:
     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)

-

   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;

        }          
    }

}               

-

推荐答案

我看到的问题是您正在引用Action ClearFuncs中的第一个表.您可以轻松地将其转换为将用于所有表的通用Action.也与MouseAdapter相同.它可以很容易地重新配置为用于 all 表,从而避免重复.请参见下面的示例.如有任何疑问,请发表评论.

I problem I see is that you are referencing the first table in the Action ClearFuncs. You could easily convert to a generic Action the will be used for all tables. Also same with the MouseAdapter. It couls easily be reconfigured to be used for all the tables, so to avoid repetition. See the example below where I do this. Leave a comment if you have any questions.

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

这篇关于如何在Java中为多个组件添加多个侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆