这是我关心的代码部分,当我尝试使用 Timer 再次更改 squaresToDisplay 对象的颜色时,它会使框架变为白色(空白),但它只能工作 1 次。所以当我运行这段代码时,它会做我想做的 1 次然后让屏幕空白。我想知道具体是什么原因造成的。我自己的假设是,当我启动 SQTimer 时,我可能会阻塞 EDT,在这种情况下,我会不知所措,因为我不知道足够的 java 来解决这个问题:/
private Timer SQTimer;
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Code that removes unrelated things from the frame
final SquareObjects squaresToDisplay = new SquareObjects(x,y);//Creates the Object based on GUI width and height
squaresToDisplay.setFocusable(true);
squaresToDisplay.setVisible(true);//Allows it to be visible
frame.add(squaresToDisplay);//Adds it to the frame
SQTimer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
squaresToDisplay.repaint();
System.out.println("Repainted");
}
});
System.out.println("Completed adding pixels");
SQTimer.setRepeats(true);
SQTimer.start();
}
});
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println("Beginning of paintComponent");
System.out.println("Completed making the Graphics objects");
for(int i = 0;i<(x*y)/64;i++){
if(xInterceptLocation == 0){
g.fillRect(xInterceptLocation, yInterceptLocation, 8, 8);
xInterceptLocation += 8;
}else{
Color newColor = changingColors();
g.setColor(newColor);
g.fillRect(xInterceptLocation, yInterceptLocation, 8, 8);
xInterceptLocation += 8;
if(xInterceptLocation == 1920){
xInterceptLocation = 0;
yInterceptLocation += 8;
}
}
}
}
只是为了澄清,这些 to 方法在单独的类中,第一个在名为 GUI 的类中,而第二个在名为 SquareObjects 的类中