ฉันกำลังพยายามเรียนรู้ Java จากหลักสูตร Udemy และถูกขอให้สร้างงานก่อนที่จะย้ายไปยังส่วนต่อไปนี้
งานที่ได้รับมอบหมายคือการเขียนแอปพลิเคชัน JavaFX ที่แสดงวงกลมและปุ่ม และทุกครั้งที่กดปุ่มดังกล่าว วงกลมควรถูกย้ายไปยังตำแหน่งสุ่ม
จนถึงตอนนี้ ฉันได้สร้างโค้ดที่นับจำนวนครั้งที่ฉันคลิกปุ่มแล้ว ตอนนี้ฉันต้องการย้ายวงกลมไปพร้อมกับการนับ:
public class CircleJumper extends Application {
// Declare Variables
private int count;
private Circle initCircle;
private Button initButton;
private Text countText;
/*
*
* Write function here
*
*/
@Override
public void start(Stage primaryStage){
// Initiate Variables
count = 0;
initCircle = new Circle(30, -50, 30);
initButton = new Button("Click Me!");
countText = new Text("Clicks: 0");
// Here its where I built the click counter
initButton.setOnAction((event) -> {
count++;
countText.setText("Pushes: " + count);
});
;
Group baseDemo = new Group(initButton, countText);
FlowPane pane = new FlowPane(baseDemo, initCircle);
pane.setAlignment(Pos.CENTER);
pane.setHgap(20);
pane.setStyle("-fx-background-color: cyan");
Scene scene = new Scene(pane, 600, 300);
primaryStage.setTitle("Draw a Circle when Button is Pressed");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
launch(args);
}
}
อัปเดต: ฉันตัดสินใจประกาศการนับตัวแปรของฉันเป็น = Math.random(); และสร้างวงกลมขึ้นมา หลังจากนั้นการคลิกปุ่มควรได้รับ Math.random ที่สร้างขึ้นและวางไว้ใน setTranslate ใช่ไหม?
public void start(Stage primaryStage){
// Initiate Variables
count = Math.random();
initCircle = new Circle(30, 50, 30);
initButton = new Button("Click Me!");
Group circlePos = new Group(initCircle);
circlePos.setTranslateX(10);
circlePos.setTranslateY(10);
initButton.setOnAction((event) -> {
count++;
circlePos.setTranslateY(count);
circlePos.setTranslateX(count);
});
Group baseDemo = new Group(initButton);
FlowPane pane = new FlowPane(baseDemo, initCircle);
pane.setAlignment(Pos.CENTER);
pane.setHgap(20);
pane.setStyle("-fx-background-color: cyan");
Scene scene = new Scene(pane, 600, 300);
primaryStage.setTitle("Draw a Circle when Button is Pressed");
primaryStage.setScene(scene);
primaryStage.show();
}
Math#random()
หรือjava.util.Random
. แบบแรกจะส่งกลับค่าในช่วง[0.0,1.0)
ซึ่งคุณสามารถคูณด้วยความกว้าง/ความสูงของพาเรนต์ของวงกลมเพื่อให้ได้จุดศูนย์กลางใหม่ x/y หลังมีเมธอดที่สามารถส่งคืนขอบเขตint
s (ในช่วง[0,bound)
) - person Slaw   schedule 19.09.2019