java - 可以将此更改为某种颜色

标签 java user-interface awt

我试图在球击中墙壁的任何一侧时改变球的颜色。 我可以让它改变颜色,但之后它又回到原来的颜色。

这是我正在处理的代码部分。我需要一些帮助。有没有办法保持颜色变化?

如果你一直查看代码,你可以看到注释部分//initial ball color。我确信部分代码是它返回到原始颜色并且不改变颜色的原因。有没有办法保持它撞到墙上时颜色也改变?

public void paint (Graphics g) {
    g.drawRect(rectLeftX, rectTopY,
               rectRightX - rectLeftX, rectBottomY - rectTopY);

    r=new Random();

    for (int n = 1; n < 500 ; n++) {

        Color backgroundColour = getBackground();
        g.setColor(backgroundColour);
        g.fillOval(x, y, diameter, diameter);

        if (x + xChange <= rectLeftX)
        {
            xChange = -xChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.fillOval (x, y, diameter, diameter);

        }
        if(x+xChange + diameter >= rectRightX)
        {
            xChange = -xChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.fillOval (x, y, diameter, diameter);
        }

        if (y+yChange <= rectTopY)
        {
            yChange = -yChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
           g.fillOval (x, y, diameter, diameter);
        }
        if(y + yChange + diameter >= rectBottomY)
        {
            yChange = -yChange;
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
           g.fillOval (x, y, diameter, diameter);
        }

        x = x + xChange;
        y = y + yChange;     


        // initial ball color
         g.setColor(get()); 
         g.fillOval (x, y, diameter, diameter);


        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            g.drawString("sleep exception", 20, 20);
        }

    } 
} 

最佳答案

我认为这段代码可以满足您的需求。

Ball

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class CGBouncingBall extends JFrame {

    // Define named-constants
    private static final int CANVAS_WIDTH = 640;
    private static final int CANVAS_HEIGHT = 480;
    private static final int UPDATE_INTERVAL = 50; // milliseconds
    Random r;
    Color ballColor = Color.BLUE;

    private DrawCanvas canvas;  // the drawing canvas (an inner class extends JPanel)

    // Attributes of moving object
    private int x = 100;     // top-left (x, y)
    private int y = 100;
    private int size = 250;  // width and height
    private int xSpeed = 3;  // moving speed in x and y directions
    private int ySpeed = 5;  // displacement per step in x and y

    // Constructor to setup the GUI components and event handlers
    public CGBouncingBall() {
        canvas = new DrawCanvas();
        canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
        this.setContentPane(canvas);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.pack();
        this.setTitle("Bouncing Ball");
        this.setVisible(true);

        // Create a new thread to run update at regular interval
        Thread updateThread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    update();   // update the (x, y) position
                    repaint();  // Refresh the JFrame. Called back paintComponent()
                    try {
                        // Delay and give other thread a chance to run
                        Thread.sleep(UPDATE_INTERVAL);  // milliseconds
                    } catch (InterruptedException ignore) {
                }
            }
        }
    };
    updateThread.start(); // called back run()
}

// Update the (x, y) position of the moving object
public void update() {
    x += xSpeed;
    y += ySpeed;
    r=new Random();
    if (x > CANVAS_WIDTH - size || x < 0) {
        xSpeed = -xSpeed;
        ballColor = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
    }
    if (y > CANVAS_HEIGHT - size || y < 0) {
        ySpeed = -ySpeed;
        ballColor = new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256));
    }
}

// Define Inner class DrawCanvas, which is a JPanel used for custom drawing
class DrawCanvas extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // paint parent's background
        setBackground(Color.BLACK);
        g.setColor(ballColor);
        g.fillOval(x, y, size, size);  // draw a circle
    }
}

// The entry main method
public static void main(String[] args) {
    // Run GUI codes in Event-Dispatching thread for thread safety
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new CGBouncingBall(); // Let the constructor do the job
        }
    });
}
}

关于java - 可以将此更改为某种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45249849/

相关文章:

java - 对需要频繁更新的应用使用JSP热部署

java - jpa-springEntitymanager.find超时不起作用

user-interface - 单选按钮与真/假/空选项的复选框

c++ - Xcode 和 wxWidgets 框架

Java:不用aw创建图形?

java - 无法使用 Robot 在 Selenium WebDriver 中拖放

java - 获取 url.getContent() 时出现问题

java - 复制栈顶元素Java

javascript - Uncaught Error : DOM element with id x in Element cache is not same as element in DOM

java - 使用 java.awt.Dimension 类