0

我的函数绘制三个随机数,并根据这个数字为 JLabel 设置适当的图标(一、二、三)。我需要在 2 秒后更改此图标。

    public void random() {
    Random rand = new Random();
    num1 = rand.nextInt(3);
    num2 = rand.nextInt(3);
    num3 = rand.nextInt(3);   

    if (num1==0){
        one.setIcon(icon7);
    }
    if (num1==1){
        one.setIcon(icon8);
    }
    if (num1==2){
        one.setIcon(icon9);
    }

    if (num2==0){
        two.setIcon(icon7);
    }
    if (num2==1){
        two.setIcon(icon8);
    }
    if (num2==2){
        two.setIcon(icon9);
    }  

    if (num3==0){
        three.setIcon(icon7);
    }
    if (num3==1){
        three.setIcon(icon8);
    }
    if (num3==2){
        three.setIcon(icon9);
    }}

2秒后我想改变这样的图标:

    one.setIcon(icon10);
    two.setIcon(icon10);
    three.setIcon(icon10);

我不知道该怎么做,请帮助我:)

4

2 回答 2

3
final Timer timer = new Timer(2000, null);
ActionListener listener = new ActionListsner() {

@Override 
public void actionPerformed(ActionEvent e) {

        one.setIcon(icon10);
        two.setIcon(icon10);
        three.setIcon(icon10);
 }
};
timer.addActionListener(listener);
timer.start();

此代码每 2 秒调用一次 setIcon 函数,但如果您只想调用 1 或 2 次,您可以将条件置于 actionPerformed 函数下...希望对您有所帮助!..

于 2013-10-25T12:40:07.363 回答
0

我会先更改您的代码:

private static final Random rand = new Random();

//somewhere on init.
final JLabel[] myLabels = new JLabel[3];
for(int i = 0; i < myLabels.length; ++i) {
    myLabels[i] = new JLabel();
    //add to panel or whatever.
}

private void setIcon(final int value, final JLabel label) {
    switch(value) {
        case 0:
            label.setIcon(icon7);
            break;
        case 1:
            label.setIcon(icon8);
            break;
        case 2:
            label.setIcon(icon9);
            break;
        default:
            throw new IllegalArgumentException("Value must be between 0 and 2.");
    }
}

public void random() {
    for(int i = 0; i < myLabels.length; ++i) {
        setLabel(rand.nextInt(3), myLabels[i]);
    }
    scheduleReset();
}

然后我会编写scheduleReset使用非重复 swing 的方法Timer

public void scheduleReset() {
    final Timer timer = new Timer((int) TimeUnit.SECONDS.toMillis(2), new ActionListener() {
        @Override
        public void actionPerformed(final ActionEvent ae) {
            resetIcons();
        }
    });
    timer.setRepeats(false);
    timer.start();
}

public void resetIcons() {
    for(int i = 0; i < myLabels.length; ++i) {
        myLabels[i].setIcon(icon10);
    }
}
于 2013-10-25T14:21:18.097 回答