java swing类之间监听问题
PHPz
PHPz 2017-04-18 09:48:29
0
1
748

两个类,分别的两个jpanel,一个panel为jlist监听,一个里边是button,想实现jlist 触发按钮的状态改变,大概的思路是什么?

PHPz
PHPz

学习是最好的投资!

reply all(1)
PHPzhong

If both JPanels are instantiated in a JWindow/JFrame, button and list can definitely access each other.

If they are inherited separately, just add an interface or make a proxy in the JPanel where the button is located. I wrote a note for you

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyPanel extends JPanel {
    JButton button;

    public MyPanel() {
        button = new JButton("Add To List");
    }

    // 方法二,直接把 button 暴露出来
    public JButton getButton() {
        return button;
    }

    // 方法一,做个 button.addActionListner 的代理
    public void addButtonListener(ActionListener listener) {
        button.addActionListener(listener);
    }
}

class ListPanel extends JPanel {
    public void addToList(String item) {
        // TODO
    }
}

public class Test {
    MyPanel myPanel;
    ListPanel listPanel;

    // ....

    void setupEvents() {
        // 方法一实现
        myPanel.addButtonListener(e -> {
            listPanel.addToList("hello");
        });

        // 方法二实现
        myPanel.getButton().addActionListener(e -> {
            listPanel.addToList("world");
        });
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!