gpt4 book ai didi

java - 为什么当我添加 for 循环时我的 jframe 变黑?

转载 作者:行者123 更新时间:2023-12-02 04:45:00 30 4
gpt4 key购买 nike

我试图通过创建颜色列表,然后使用 for 循环循环它们,然后重新绘制来在 jframe 中制作闪烁的灯光。但是当我在代码中添加一个 for 循环时,整个事情就出错了,我得到一个黑屏并且它变得不稳定。为什么会发生这种情况?

 public class bb {

static Color colors[] = {Color.ORANGE, Color.GRAY};
public static void main(String[] args) {

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(400, 525);

JPanel panel = new JPanel() {

@Override
public void paintComponent(Graphics g) {

JButton smallerButton = new JButton("Flash");
JButton largerButton = new JButton("Steady");

JPanel southPanel = new JPanel();
southPanel.add(smallerButton);
southPanel.add(largerButton);
frame.add(southPanel, BorderLayout.SOUTH);

super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(180, 110, 10, 30);
g.drawRect(180, 140, 9, 30);
g.fillRect(180, 170, 10, 30);
g.drawRect(180, 200, 9, 30);
g.fillRect(180, 230, 10, 30);
g.drawRect(180, 260, 9, 30);
g.fillRect(180, 290, 10, 30);
g.drawRect(180, 310, 9, 30);
g.fillRect(180, 340, 10, 30);

int i = 0;
g.setColor(colors[i]);

for(i=0; i <= colors.length; i++){

g.fillOval(160, 70, 50, 50);
if (i ==colors.length){
i=0;
}
frame.repaint();
}

smallerButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{

String action = e.getActionCommand();
if (action.equals("Flash")){
}
}
});
}
};

frame.add(panel);
frame.validate();
}
}

最佳答案

此语句将循环索引重置为 0,导致其无限循环,从而阻塞 EDT

if (i == colors.length) {
i = 0;
}

因为您超出了 for 语句中的最后一个数组索引。

看看如何使用 Swing Timer来实现这个功能。

关于java - 为什么当我添加 for 循环时我的 jframe 变黑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29729346/

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