我是使用Timer类的新手,因此在将其合并到我的项目之前尝试使用它.我想知道为什么这个程序在计数达到5时不会终止.即使不满足while循环的条件,程序也会继续运行.
package Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class demo {
private static int count;
public static void main(String[] args) {
ActionListener executeThis = new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Hello");
count++;
}
};
Timer timer = new Timer(500, executeThis);
timer.setInitialDelay(1000);
timer.start();
while(count < 5){
}
}
}
Run Code Online (Sandbox Code Playgroud) 我有一个程序,通过GridBagLayout布局管理器显示一个4x4的正方形网格.显示包含square.gif的16个JLabel.当点击其中一个矩形时,应该用包含图像的JLabel(例如帽子)替换它.因此,图像取代了单击的矩形.
但是,目前发生的情况是,单击的矩形有时会被替换.其他时候,矩形消失但图像不会取代它.其他时候,图像显示在之前单击过的矩形中,但仅在单击其他矩形后才显示.我在下面放置了最相关的代码.
public void displayGrid() {
c.gridx = 0;
c.gridy = 0;
try {
squareImage = ImageIO.read(this.getClass().getResource("stimulus(0).gif")); //line 37
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel squareLabel = new JLabel(new ImageIcon(squareImage));
for(int i = 0; i < 16; i++){
c.gridx = i % 4;
c.gridy = i / 4;
squareLabel = new JLabel(new ImageIcon(squareImage));
squareLabels[i] = squareLabel;
panel.add(squareLabels[i], c);
squareLabels[i].addMouseListener(this);
System.out.println(c.gridx + "" + c.gridy);
}
panel.validate();
}
public void mousePressed(MouseEvent e) {
for(int …Run Code Online (Sandbox Code Playgroud)