让所有按钮从一个循环中工作

getting all buttons to work from a loop

我正在尝试找出如何让每个按钮都给我圣诞节剩下多少天的消息。按钮是在 for 循环中制作的,所以这里对我来说棘手的部分是在制作按钮后打开它们。

int days = 24;
int i = 1;
JButton b1 = new JButton();
JLabel l1 = new JLabel("welcome to this year advent calendar");

public Oblig6(){
    this.add(l1);
    this.setTitle("advent calender");
    this.setLayout(new FlowLayout());
    this.setSize(230, 440);
    this.setVisible(true);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    for(i=1; i < 25;i++){
        b1.setText("Hatch "+i);
        this.add(b1);
        b1.setVisible(true);
        b1 = new JButton();
        b1.addActionListener(this); 
    }
}

@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.getSource().equals(b1)){
        JOptionPane.showMessageDialog(null, "it's only "+i+" days left for christmes");
    }
}}

如果您稍后需要引用这些按钮,请保留一组按钮,而不是只对最后创建的按钮使用一个变量 (b1)。此外,您错过了在第一个按钮上调用 b1.addActionListener(this) 的机会,因为它已被下一个按钮取代。您可以像这样定义一个按钮数组:

private JButton[] buttons = null;

然后在初始化期间:

buttons = new JButton[24];
for (int i=0; i<24; i++) {
    buttons[i] = new JButton();
    buttons[i].setActionListener(this);
    buttons[i].setText("Hatch "+(i+1));
    buttons[i].setVisible(true);
    this.add(buttons[i]);
}

稍后您可以根据需要通过 buttons 变量访问任何按钮。