84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
两个类,分别的两个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