2017-09-27 3 views
0

私はキャンバス全体にランダムな四角形を生成するこのコードを持っています。私はまた、中央に1つの矩形を持っています。Javaの描画矩形

ユーザーがキャンバス上にマウスを置いたときに、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); 
} 

答えて

0

グラフィックスを動かす予定がある場合、なぜキャンバスから始めるのですか?キャンバスでは何度も何度も何度も何度も再描画しない限り、何も動かすことはできません。シーングラフに長方形を置くことは、この作業にはるかに適しています。

+0

大変ありがとうございます –