我正在尝试创建一个方法,在用户单击舞台中的矩形后返回 . 但是,当单击矩形时调用wait()然后再调用notify()时,程序会冻结 . 如何在javafx中创建showAndWait()方法?
我正在尝试创建一个类,询问多项选择问题,然后返回结果,下面的代码是这个类,并在我试图放置等待和通知调用的位置进行评论 .
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
public class Question{
int answer; //refers to the answer in the order of strings given
// a = 1, b = 2, c = 3, d = 4
String question;
String a,b,c,d;
public Question(String question, String a, String b, String c, String d, int answer){
this.question = question;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.answer = answer;
}
private final double sideLength = 500;
private volatile byte complete; //0 = no, 1 = true, -1 = false
public synchronized boolean showAndWait(){
complete = 0;
Stage stage = new Stage();
Pane pane = new Pane();
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.setResizable(false);
stage.setMaxHeight(sideLength);
stage.setMinHeight(sideLength);
stage.setMaxWidth(sideLength);
stage.setMinWidth(sideLength);
double width = sideLength/3;
double height = sideLength/5;
double firstX = sideLength/9;
double secondX = width + sideLength/9*2;
double firstY = height + sideLength*2/5/3;
double secondY = firstY * 2;
Color base = Color.AQUAMARINE;
Color wrong = Color.RED;
Color right = Color.GREEN;
Pane questionPane = makeAnswer(0,0,sideLength,sideLength/5, question, base, base);
Pane ansA = makeAnswer(firstX, firstY, width, height,a,base, wrong);
Pane ansB = makeAnswer(secondX, firstY, width, height,b,base, wrong);
Pane ansC = makeAnswer(firstX, secondY, width, height,c,base, wrong);
Pane ansD = makeAnswer(secondX, secondY, width, height,d,base, wrong);
pane.getChildren().addAll(questionPane, ansA, ansB, ansC, ansD);
stage.show();
//wait here, check to see if completed
System.out.println(complete);
return complete == 1;
}
private double textShiftX = 30;
private double textShiftY = 30;
private int characterLimit = 20;
private double textChangeY = 10;
private synchronized Pane makeAnswer(double x, double y,double width, double height, String s, Color base, Color afterClick){
Pane temp = new Pane();
temp.setLayoutX(x);
temp.setLayoutY(y);
Rectangle rD = new Rectangle(0, 0, width, height);
rD.setFill(base);
temp.getChildren().add(rD);
for(int i=0;s.length() > 0;i++){
String sTemp;
if(s.length()>characterLimit){
sTemp = s.substring(0,characterLimit);
while(sTemp.charAt(sTemp.length()-1) != ' ')
sTemp = sTemp.substring(0,sTemp.length()-1);
}
else
sTemp = s;
s = s.substring(sTemp.length());
Text t = new Text(textShiftX, textShiftY + textChangeY*i, sTemp);
temp.getChildren().add(t);
}
rD.setOnMouseClicked(
(e)->{
((Rectangle)e.getSource()).setFill(afterClick);
complete = 1;
//notify
});
return temp;
}