我有两个带有图像的jlabels..我尝试在单击另一个标签时更改标签中的图像..(例如游戏)..我有问题..当我写Thread.sleep时,图像不是更改..查看代码:
public class Game extends JFrame{
private JLabel l1,l2;;
private boolean isClicked = false ,isClicked2 = false;
public Game(){
setLayout(new FlowLayout());
l1 = new JLabel(new ImageIcon(getClass().getResource("image1.png")));
add(l1);
l2 = new JLabel(new ImageIcon(getClass().getResource("image1.png")));
add(l2);
l1.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {
if(isClicked2){
l1.setIcon(new ImageIcon(getClass().getResource("image2.png")));
try {
Thread.sleep(1000);
l1.setIcon(new ImageIcon(getClass().getResource("image1.png")));
l2.setIcon(new ImageIcon(getClass().getResource("image1.png")));
isClicked2 = false;
isClicked = false;
}catch(InterruptedException ex){}
}
else{
l1.setIcon(new ImageIcon(getClass().getResource("image2.png")));
isClicked = true;
}
}@Override public void mouseEntered(MouseEvent e){}@Override public void mouseExited(MouseEvent e){}
});
l2.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {
if(isClicked){
try {
l2.setIcon(new ImageIcon(getClass().getResource("image2.png")));
Thread.sleep(1000);
l2.setIcon(new ImageIcon(getClass().getResource("image1.png")));
l1.setIcon(new ImageIcon(getClass().getResource("image1.png")));
isClicked = false;
isClicked2 = false;
}catch(InterruptedException ex){}
}
else{
l2.setIcon(new ImageIcon(getClass().getResource("image2.png")));
isClicked2 = true;
}
}@Override public void mouseEntered(MouseEvent e){}@Override public void mouseExited(MouseEvent e){}
});
}
public static void main(String[] args) {
Game g = new Game();
g.setTitle("Fint the same");
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.pack();
g.setVisible(true);
}
}
运行它并首先单击第一个标签。单击第二个标签后,第一个标签将在 1 秒内更改图像,但 seconf 标签永远不会!