【问题标题】:Drawing rectangles in java在java中绘制矩形
【发布时间】:2017-09-27 06:58:30
【问题描述】:

我有这段代码,我在整个画布上生成随机矩形。我在中心也有 1 个矩形。

当用户将鼠标悬停在画布上时,我需要让中心的 1 个矩形移动。

这是我的代码

package sample;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Random;


public class Main extends Application {

private static final int DRAW_WIDTH  = 800;
private static final int DRAW_HEIGHT = 500;

private Animation myAnimation;
private Canvas canvas;
private GraphicsContext gtx;

@Override
public void start(Stage stage) throws Exception
{

    stage.setTitle("tRIPPy BoXXX");

    canvas = new Canvas(DRAW_WIDTH, DRAW_HEIGHT);
    gtx = canvas.getGraphicsContext2D();
    gtx.setLineWidth(3);
    gtx.setFill(Color.BLACK);
    gtx.fillRect(0, 0, DRAW_WIDTH, DRAW_HEIGHT);


    VBox vBox = new VBox();
    vBox.getChildren().addAll(canvas);
    Scene scene = new Scene(vBox, DRAW_WIDTH, DRAW_HEIGHT);
    stage.setScene(scene);
    stage.show();
    myAnimation = new Animation();
    myAnimation.start();
}


class Animation extends AnimationTimer
{
    @Override

    public void handle(long now)
    {

        Random rand = new Random();
        double red   = rand.nextDouble();
        double green = rand.nextDouble();
        double blue  = rand.nextDouble();
        Color boxColor = Color.color(red,green,blue);
        gtx.setStroke(boxColor);
....

这是我想用用户鼠标移动的框。我自己尝试了一些事情,但是我无法让 rect 保持它在代码中的样子。

      .....
      int rectX = 800 / 2;
      int rectY = 500 / 2;
      for (int side = 10; side <= 100; side += 10) {
        gtx.strokeRect(rectX - side / 2, rectY - side / 2, side, side);
      }


      int centerX = (int)(Math.random()*800);
      int centerY = (int)(Math.random()*800);
      for (int side = (int)(Math.random()*100); side <= Math.random()* 100; side += Math.random()*100)

      {
        gtx.strokeRect(centerX - side / 2, centerY - side / 2, side, side);

      }
    }
}


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

【问题讨论】:

    标签: java animation javafx javafx-2


    【解决方案1】:

    如果您打算移动一些图形,为什么要从画布开始?在画布上你不能移动任何东西,除非你不断地想一次又一次地重绘所有东西。将矩形放入场景图中更适合这项任务。

    【讨论】:

      猜你喜欢
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2014-03-22
      • 1970-01-01
      • 2014-01-13
      • 2011-06-05
      • 1970-01-01
      相关资源
      最近更新 更多