drawingPanel颜色随位移而变化

时间:2017-10-16 20:55:51

标签: java swing colors jgrasp custom-painting

我正在使用JGrasp,在drawingPanel中,我试图创建一个在屏幕上移动时改变颜色的球。现在,我得到了:

for (int i = 10; i<=i; i++) {
    Color c = new Color(i*i, 0, 0);
    pen.setColor(c);

我的完整简化代码是:

import java.awt.*;
import java.util.*;
import java.awt.Color;

public class BallSample {
   public static final int SIZE = 30;
   public static final int HALF = SIZE / 2;

   public static void main(String[] args) {
      Scanner console = new Scanner(System.in);

      DrawingPanel panel = new DrawingPanel(1000, 1000);
      panel.setBackground(Color.CYAN);
      Graphics pen = panel.getGraphics();

      for (int i = 10; i<=i; i++) {
         Color c = new Color(i*i, 0, 0);
         pen.setColor(c);
         pen.fillOval(500 - HALF, 500 - HALF, SIZE, SIZE);

         double xDisplacement = 30 * Math.cos(30);
         double yDisplacement = 30 * Math.sin(30) * -1;
         double x = 500.0;
         double y = 500.0;

         for (int j = 1; j <= 100; j++) {
            x = x + xDisplacement;
            y = y + yDisplacement;
         if (x <= 0 || x >= 1000) {
            xDisplacement = xDisplacement * -1;
         }
         if (y <= 0 || y >= 1000) {
            yDisplacement = yDisplacement * -1;
         }
            pen.fillOval((int) x - HALF, (int) y - HALF, SIZE, SIZE);

            panel.sleep(50);
         }      
      }
   }
}

我希望这已经足够简化了。

1 个答案:

答案 0 :(得分:0)

在以下代码中使用some issues后,我能够创建一个变色球示例。

首先,panel.sleep(50);让我思考(我在评论中发布的DrawingPanel类链接确认)可能会变得危险,最好使用{{3}相反,我不会假装使用或阅读所有课程太长,所以在这里发布的示例我将使用Swing Timer方法。

此外,我不确定为什么使用随机int(0到255之间)调用Swing Timer构造函数并不会更新或创建新的Color这些设置,然后在阅读new Color(int rgb)和另一个(我丢失了链接,抱歉)后,您可以使用this answer,因此您可以使用最多256的随机数。< / p>

您还可以将您的方法建立在MVC模式的基础上,拥有一个模型Ball类,其中包含coords和它将拥有的Color,一个将绘制球的视图JPanel随着时间的推移和一个控制器将改变球的坐标和颜色加班。

免责声明:此示例只是水平移动球并且无法验证它是否在屏幕上,您需要根据自己的需要调整此示例。 / p>

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ChangingColorBall {
    private JFrame frame;
    private Timer timer;
    private BallPane ballPane;
    private Ball ball;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ChangingColorBall()::createAndShowGui); //We place our program on the EDT
    }

    private void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());
        ball = new Ball();
        ballPane = new BallPane(ball);

        timer = new Timer(100, e -> { //This Timer will execute every 100ms and will increase ball's X coord and paint it again.
            ball.increaseX(); //This method increases X coord and changes ball's color on the model
            ballPane.revalidate();
            ballPane.repaint();
        });

        frame.add(ballPane);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        timer.start(); //We start the timer
    }

    class Ball {
        private int xCoord;
        private static final int Y = 50;
        private static final int SIZE = 20;
        private Color color;
        private Random r;

        public void increaseX() {
            xCoord += 10; //Increases X coord
            r = new Random();
            color = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256)); //Generates a new random color
        }

        public int getXCoord() {
            return xCoord;
        }

        public void setXCoord(int xCoord) {
            this.xCoord = xCoord;
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }
    }

    @SuppressWarnings("serial")
    class BallPane extends JPanel {
        private Ball ball;

        public BallPane(Ball ball) {
            this.ball = ball;
        }

        @Override
        protected void paintComponent(Graphics g) { //This method paints the ball according to the color it has and the actual coords it has
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(ball.getColor());
            g2d.fillOval(ball.getXCoord(), Ball.Y, Ball.SIZE, Ball.SIZE);
        }

        @Override
        public Dimension getPreferredSize() { //We should not call `.setSize(...)` method, so we override this one and call `.pack();` 
            return new Dimension(200, 100);
        }
    }
}

注意

请注意不要将您的同意电话称为xy,或至少不要将其作为getX()getY()或其他人context打电话给您遇到我在这个答案开始时链接的问题。

以下是GUI的示例,我不能在我的计算机上执行GIF,但如果您复制粘贴代码并查看其工作原理,则会更好。

new Color(float r, float g, float b)

要深入了解自定义绘画在Swing中的工作原理,请查看Oracle的enter image description hereLesson: Performing Custom Painting教程。