我的列表中有动态数量的 JButton,需要帮助将它们连接到 actionListener
我首先根据名为 alt 的列表创建按钮:
for(int i =0;i<alt.size();i++) {
JButton button = new JButton (alt.get(i));
button.addActionListener(this);
buttonList.add(button);
}
后来我添加了这样的按钮
private void gui(List<JButton> bList) {
f = new JFrame("window");
f.setLayout(new BorderLayout());
f.setVisible(true);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.PAGE_AXIS));
for(int i =0;i<bList.size();i++) {
buttonPane.add(bList.get(i));
}
f.add(buttonPane, BorderLayout.SOUTH);
}
我知道按钮的数量永远不会超过 4 个。那么如何连接到 ActionListener 中的右侧按钮?没有在 gui 范围之外声明它们或单独命名它们?
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ?) {
} else if (e.getSource() == ?) {
} else if (e.getSource() == ?){
}else if (e.getSource() == ?){
}
}
最佳答案
如果您的按钮正在执行操作,则应该为每个按钮实现单独的操作监听器,否则在您的 e.getSource() == ?
中,?
应该是JButton实例,例如:e.getSource() == bList.get(0)
关于java - 如何将 JButtons 从列表连接到 actionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59896597/