【发布时间】:2017-04-04 19:54:42
【问题描述】:
我对编程比较陌生,而且我很挣扎。我将非常非常感谢您的帮助。我正在尝试制作一个简单的程序,用户可以使用键盘上的数字 1 和 2 键更改透明舞台上显示的点的 Y 坐标,以上下移动它。问题是我在方法之外创建的 Y 值变量在按下键时不会更新。我知道实际的方法本身是有效的,因为我运行了打印线测试......除了该方法之外,我无法获得要在其他任何地方更新的值。有什么建议吗?
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
//Program where the user can adjust the Y Coordinate of a dot by
pressing 1 & 2 Keyboard Keys
public class Main extends Application implements EventHandler<KeyEvent> {
double x = 680; //The X Value of Dot (Never Changes)
double y = 380; //The Y Value of Dot (The value users can change)
@Override
public void start(Stage stage) {
//Root Properties
AnchorPane root = new AnchorPane();
root.getChildren().addAll(dot(), display());
root.setStyle("-fx-background-color: null;");
//Scene Properties
Scene scene = new Scene(root,1369, 715);
scene.setOnKeyPressed(this);
scene.setFill(null);
//Stage Settings
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
stage.setAlwaysOnTop(true);
}
@Override
//KeyEvent That Adjusts the Y Coordinate that Starts off at 380
public void handle (KeyEvent event){
KeyCode key = event.getCode();
if (key == KeyCode.DIGIT1){y = y + 100;}
if (key == KeyCode.DIGIT2){y = y - 100;}
System.out.println(y);
//A test to see if the method actually works (it does)
};
//Properties of the Dot
public Text dot(){
Text dot = new Text();
dot.setText(".");
dot.setFont(new Font (100));
dot.setFill(Color.RED);
dot.setX(x);
dot.setY(y);
return dot;}
//Displays the Value of Y on the Screen
public Text display(){
Text display = new Text(Double.toString(y));
display.setX(600);
display.setY(300);
return display;}
public static void main(String[] args) {launch(args);}
}
【问题讨论】:
-
您没有任何代码,例如在
y的值改变后更新display的文本。
标签: java javafx event-handling javafx-8 keycode