我的函数绘制三个随机数,并根据此数字为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);
我不知道,怎么做,请帮帮我:)。
答案 0 :(得分: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函数,但如果你只想调用一次或两次,你可以将条件置于actionPerformed函数下...希望对你有帮助!..
答案 1 :(得分: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
方法来使用非重复摆动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);
}
}