【问题标题】:What if we want to use mouseClick Method many times with different implementation如果我们想多次使用不同实现的 mouseClick 方法怎么办
【发布时间】:2020-06-19 08:38:17
【问题描述】:

我们如何在不同的实现中使用相同的方法(相同的参数和返回类型) 换句话说,在 java Gui 中,我想在一个类中以多种不同的方式使用 mouseClick 方法,这怎么可能?

【问题讨论】:

    标签: java user-interface interaction


    【解决方案1】:

    您将实现不同的 MouseListeners 并将它们添加到您想要不同 mouseClick 行为的每个组件中。

    编辑:我在下面添加了一个示例。

    public void example() {
    
        JPanel panel1 = new JPanel();
        panel1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                /* your code here, what should happen when the mouse clicked the panel */
            }
        });
    
        JTable table1 = new JTable();
        table1.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                /* your code here, what should happen when the mouse clicked the table */
            }
        });
    }
    

    这里我使用new MouseAdapter() more here 而不是new MouseListener(),它实现了MouseListener,因为这允许您只实现MouseListener 接口的一个方法。

    【讨论】:

    • 你能给我一个简单的例子吗?
    • 当然,我在上面添加了一个示例。
    • 不用担心。如果这回答了您的问题,请务必将其标记为解决方案。 :)
    猜你喜欢
    • 2019-12-19
    • 2020-06-10
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多