两个类,分别的两个jpanel,一个panel为jlist监听,一个里边是button,想实现jlist 触发按钮的状态改变,大概的思路是什么?
学习是最好的投资!
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"); }); } }
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