2011-08-29 64 views
1

我试图学习如何绘制一个形状,并能够a)绘制它,“冻结”该过程,绘制它的背景颜色,然后重新绘制原始颜色和b )绘制一个形状并改变它的颜色。所有我至今是(对于闪烁):如何在Java中使形状“闪烁”或更改颜色?

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Carlight extends JPanel{ 
    Thread th=new Thread(); 
    public void paintComponent (Graphics g){ 
     super.paintComponents(g); 
     g.setColor(Color.yellow); 
     g.fillOval(25, 25, 10, 10); 
     try{ 
      th.sleep(10); 
     }catch(InterruptedException e){} 
     repaint(); 
     g.setColor(Color.yellow); 
     g.fillOval(25, 25, 10, 10); 
     try{ 
      th.sleep(10); 
     }catch(InterruptedException e){} 
     repaint(); 
     g.setColor(Color.yellow); 
     g.fillOval(25, 25, 10, 10); 
    } 
    public Carlight(){ 
     JFrame frame=new JFrame(); 
     frame.setTitle("Carlights"); 
     frame.add(this); 
     frame.setBackground(Color.black); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(100,150); 
     frame.setVisible(true); 
    } 
    public static void main(String[] args){ 
     new Carlight(); 
    } 
} 

如何使此代码的工作,我如何得到一个形状改变颜色?

回答

1
import java.awt.Color; 
import java.awt.Graphics; 
import java.util.concurrent.Executors; 
import java.util.concurrent.ScheduledExecutorService; 
import java.util.concurrent.TimeUnit; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class carlight extends JPanel 
{ 
    private Color lastColor = Color.YELLOW; 
    // For telling the panel to be repainted at regular intervals 
    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 

    @Override 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponents(g); 
     if(lastColor.equals(Color.YELLOW)) 
     { 
      lastColor = Color.GREEN; 
     } 
     else 
     { 
      lastColor = Color.YELLOW; 
     } 
     g.setColor(lastColor); 
     g.fillOval(25, 25, 10, 10); 
    } 

    public carlight() 
    { 
     JFrame frame = new JFrame(); 
     frame.setTitle("Carlights"); 
     frame.add(this); 
     frame.setBackground(Color.black); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(100, 150); 
     frame.setVisible(true); 
     service.scheduleAtFixedRate(new Runnable() 
     { 
      public void run() 
      { 
       repaint(); 
      } 
     }, 0, 1, TimeUnit.SECONDS); 
    } 

    public static void main(String[] args) 
    { 
     new carlight(); 
    } 
} 

好吧,

  • 不要在通话的paintComponent期间把睡眠通话。这意味着你是 迫使用户界面挂起/失速。这真是太糟了。
  • 我创建了一个ScheduledExecutorService,用于定期调用repaint方法。
  • paint方法更改lastColor的颜色。大多数情况下,您会查看某种模型以找出它的状态,以选择您应该使用的颜色。
  • 如果问题是你并不是要改变颜色,而是一个关闭/开启的情况,你应该有一个布尔表示状态,并且只有当它打开时才画圆。
+0

太棒了!非常感谢! – tussya

+0

如果这回答了你所有的问题,你可能应该接受它作为答案。 – pimaster

+0

这就是为什么javax.swing.Timer存在的原因,顺便说一句(如果我忘记了正确的Java命名方法无效名称和Executor)+1 – mKorbel