Java 递归有问题吗

Java 递归有问题吗,java,Java,我的目标是让斗牛士的颜色来回切换。但是,颜色不会切换,而是生成新的颜色。更紧迫的问题是当我试图以任何方式重复它时。运行程序时出现的屏幕为空,不执行任何操作。当没有环路时,靶心就会出现 import java.awt.Color; import java.awt.Graphics; import java.util.Random; import javax.swing.JPanel; public class BullSEye extends JPanel { public void pa

我的目标是让斗牛士的颜色来回切换。但是,颜色不会切换,而是生成新的颜色。更紧迫的问题是当我试图以任何方式重复它时。运行程序时出现的屏幕为空,不执行任何操作。当没有环路时,靶心就会出现

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;

public class BullSEye extends JPanel
{
   public void paintComponent( Graphics g )
   {

    super.paintComponent( g );
    Random rand = new Random();

    int top = 2;
    int r = rand.nextInt(256);
    int b = rand.nextInt(256);
    int h = rand.nextInt(256);
    int t = rand.nextInt(256);
    int u = rand.nextInt(256);      
    int v = rand.nextInt(256);

    Color randomColor = new Color(r, h, b);
    Color randColor = new Color(t,u,v);

    //sets colors for first bullseye
    g.setColor(randomColor);    
    g.fillOval( 10, 10, 200, 200 );
    g.setColor(randColor);
    g.fillOval( 35, 35, 150, 150 );
    g.setColor(randomColor);
    g.fillOval(60, 60, 100, 100);
    g.setColor(randColor);
    g.fillOval( 85, 85, 50, 50 );

    try
    {
       Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
    }
    catch(InterruptedException e)
    {
       e.printStackTrace();
    }

    //sets colors for second bullseye
    g.setColor(randColor);
    g.fillOval( 10, 10, 200, 200 );
    g.setColor(randomColor);
    g.fillOval( 35, 35, 150, 150 );
    g.setColor(randColor);
    g.fillOval(60, 60, 100, 100);
    g.setColor(randomColor);
    g.fillOval( 85, 85, 50, 50 );

    //recursive call to repeat the back and forth colors
    paintComponent(g);

   }

}

import javax.swing.JFrame;

public class BullSEyeTest 
{

   public static void main( String args[] )    
   {

      BullSEye panel = new BullSEye();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      application.add( panel );
      application.setSize( 230, 250 );
      application.setVisible( true );

   }

}

这里有几个问题可能是导致您的问题的原因

首先,为颜色生成随机数,这就是为什么每次运行程序时都会得到不同的颜色(没有递归调用)

如果你每次都想要相同的颜色,你不需要随机数生成器,它们只是常量

其次,递归不是在Swing中重新呈现UI的正确方法。Swing在JComponent上提供了一个“重新绘制”方法,通常您可以从从计时器触发的动作侦听器调用该重新绘制方法,而不是递归地调用该方法。此外,您得到的UI没有响应,因为您告诉线程睡眠

希望这有助于回答你的问题。有关如何实现此功能的更多信息,请查看此帖子:


您能用循环显示代码吗?因为没有循环(我想是“有效”的代码),所以您不应该调用
Thread.sleep()
在EDT中。即您正在绘制的位置。线程应完全从EDT中删除。要触发重新绘制,您应使用背景线程。在EDT线程中睡眠时,您会阻止事件处理,因此无法输入。