[英]how to connect JButtons from a list to actionListener
I have a dynamic number of JButtons in a list and need help to connect them to the actionListener我在列表中有动态数量的 JButton,需要帮助将它们连接到 actionListener
I first create the buttons based on a list called alt:我首先根据名为 alt 的列表创建按钮:
for(int i =0;i<alt.size();i++) {
JButton button = new JButton (alt.get(i));
button.addActionListener(this);
buttonList.add(button);
}
Later I add the buttons like this后来我添加了这样的按钮
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);
}
I know there will never be more than 4 buttons.我知道永远不会有超过 4 个按钮。 So how can I connect to the right button in the ActionListener ?
那么如何连接到 ActionListener 中的右侧按钮? without them being declared outside the scope of gui or individually named?
没有将它们声明在 gui 范围之外或单独命名?
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ?) {
} else if (e.getSource() == ?) {
} else if (e.getSource() == ?){
}else if (e.getSource() == ?){
}
}
If your buttons are doing actions, you should implement separate Action Listeners for each button, otherwise in your e.getSource() == ?
如果您的按钮正在执行操作,您应该为每个按钮实现单独的 Action Listeners,否则在您的
e.getSource() == ?
the ?
?
should be a JButton instance, for example : e.getSource() == bList.get(0)
应该是一个 JButton 实例,例如:
e.getSource() == bList.get(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.