gpt4 book ai didi

java - 如何更改计时器内部油漆的颜色

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:08:41 26 4
gpt4 key购买 nike

这是我关心的代码部分,当我尝试使用计时器再次更改 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;
}
}
}
}

澄清一下,这些方法在不同的类中,第一个在名为 GUI 的类中,而第二个在名为 SquareObjects 的类中

最佳答案

问题是 yInterceptLocation 从未设置回 0,因此当程序重新绘制时,它继续添加 8,从而使屏幕空白,因为它超出了帧边界。

@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println("Beginning of paintComponent");

System.out.println("Completed making the Graphics objects");
//yIntercept needs to be reinitialized when the repaint(); is called again
if(yInterceptLocation == 1080){
yInterceptLocation = 0;
}

for(int i = 0;i<(x*y)/64;i++){
if(xInterceptLocation == 0){//If i == 0 then it wont add 8 first (thus preventing a gap)
g.fillRect(xInterceptLocation, yInterceptLocation, 8, 8);
xInterceptLocation += 8;
}else{//Any other time we want to add 8 to space out the squares
Color newColor = changingColors();
g.setColor(newColor);
g.fillRect(xInterceptLocation, yInterceptLocation, 8, 8);
xInterceptLocation += 8;
if(xInterceptLocation == 1920){//if xInterceptLocation = 1920 then it adds 8 to yIntercept and sets x to 0 (creating a new line)
xInterceptLocation = 0;
yInterceptLocation += 8;
}
}
}
}

感谢 HoverCraft Full Of Eels,注意到它没有重新初始化

关于java - 如何更改计时器内部油漆的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17263522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com