【问题标题】:JFrame Simple ApplicationJFrame 简单应用程序
【发布时间】:2014-05-31 02:37:13
【问题描述】:

我正在努力创建一个有趣的游戏,它基本上是进化的简单表示。

基本上,当我点击我的移动球时,它会改变颜色。目标是不断变化,直到它与背景颜色相匹配,这意味着球被成功隐藏。最终我会添加更多的球,但我试图弄清楚如何在鼠标点击时改变它的颜色。到目前为止,我已经创建了移动球动画。

当我点击小球时如何改变小球的颜色?

代码:

public class EvolutionColor
{
   public static void main( String args[] )
   {
       JFrame frame = new JFrame( "Bouncing Ball" );
       frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

       BallPanel bp = new BallPanel(); 
       frame.add( bp );

       frame.setSize( 1800, 1100 ); // set frame size
       frame.setVisible( true ); // display frame
       bp.setBackground(Color.YELLOW);
   } // end main
}

class BallPanel extends JPanel implements ActionListener
{       
    private int delay = 10;
    protected Timer timer;

    private int x = 0;      // x position
    private int y = 0;      // y position
    private int radius = 15;    // ball radius

    private int dx = 2;     // increment amount (x coord)
    private int dy = 2;     // increment amount (y coord)

    public BallPanel() 
    {
        timer = new Timer(delay, this);
        timer.start();      // start the timer
    }

    public void actionPerformed(ActionEvent e)
    // will run when the timer fires
    {
        repaint();
    }

    public void mouseClicked(MouseEvent arg0) 
    {
       System.out.println("here was a click ! ");
    }

    // draw rectangles and arcs
    public void paintComponent( Graphics g )
    {
        super.paintComponent( g ); // call superclass's paintComponent 
        g.setColor(Color.red);

        // check for boundaries
        if (x < radius)  dx = Math.abs(dx);
        if (x > getWidth() - radius)  dx = -Math.abs(dx);
        if (y < radius)  dy = Math.abs(dy);
        if (y > getHeight() - radius)  dy = -Math.abs(dy);

        // adjust ball position
        x += dx;
        y += dy;
        g.fillOval(x - radius, y - radius, radius*2, radius*2);
    }    

}

【问题讨论】:

    标签: java swing timer jpanel paintcomponent


    【解决方案1】:

    看看How to Write a Mouse Listener

    不要对paintComponent 中的视图状态做出决定,绘画可能由于多种原因而发生,其中许多原因是您无法控制的。相反,在TimeractionPerformed 方法中做出这些决定

    您可能还希望考虑稍微更改您的设计。与其将球设置为JPanels,不如创建一个球的虚拟概念,其中包含它所需的所有属性和逻辑,并使用JPanel 来绘制它们。然后您可以将它们存储在某种List 中,每次注册鼠标点击时,您都可以迭代List 并检查是否有任何球被点击

    Java Bouncing Ball为例

    【讨论】:

      【解决方案2】:

      与其硬编码颜色 (g.setColor(Color.red);),不如创建一个属性:

      g.setColor(currentColor);
      

      然后当你点击圆圈区域时,更改currentColor

      【讨论】:

      • 谢谢!我添加了鼠标监听器并更改了颜色。这样,当它重新绘制画布时,它会改变颜色。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      相关资源
      最近更新 更多