我是OOP / Java编程第二级的学生。我们分配了一个简单的JavaFX接口,使用户可以使用箭头键在窗格中进行绘制。它让我想起了蚀刻画。该程序运行良好,但是我想在底部添加按钮以清除屏幕,以便用户可以在不关闭程序和退出按钮的情况下重新开始,尽管在窗格的右上角X有点多余。在测试中,向下箭头的按键进入按钮的HBox窗格,使按钮起作用并中断绘图功能。之后,按向上箭头键不会将光标返回到绘图窗格。此外,按左箭头或右箭头(一旦按下按钮)将在按钮之间移动焦点。我正在寻找一种将按键事件限制在绘图窗格中的方法。我粘贴了下面没有导入库的代码,但是其中有15个,包括LineTo,MoveTo,Button,Path ...我可以根据需要粘贴。
****编辑的代码以反映Slaw建议的有效更改我现在知道btClear按钮的代码不会清除窗格,并允许用户使用干净的面板开始绘制。
public class LineToDrawPath extends Application { private double bX = 100.0, bY = 100.0; private double segment = 20.0; @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Pane pane = new Pane(); HBox hBox = new HBox(); hBox.setPadding(new Insets(15,12,15,12)); hBox.setSpacing(20); hBox.setAlignment(Pos.CENTER); Button btClear = new Button("Clear"); btClear.setFocusTraversable(false); // effective solution Button btExit = new Button ("Exit"); btExit.setFocusTraversable(false); // effective solution hBox.getChildren().addAll(btClear, btExit); // Creating a Path object Path path = new Path(new MoveTo(bX, bY)); path.setStrokeWidth(1.7); path.setStroke(Color.CHOCOLATE); pane.getChildren().add(path); path.setOnKeyPressed(e ->{ if (e.getCode().isArrowKey()){ switch (e.getCode()){ case DOWN: bY += segment; break; case UP: bY -= segment; break; case LEFT: bX -= segment; break; case RIGHT: bX += segment; break; } path.getElements().add(new LineTo (bX, bY)); } }); BorderPane borderPane = new BorderPane(); borderPane.setCenter(pane); borderPane.setBottom(hBox); BorderPane.setAlignment(pane, Pos.CENTER); btClear.setOnAction(e -> { pane.getChildren().clear(); pane.getChildren().add(path); }); btExit.setOnAction(e -> System.exit(0) ); // Create the scene object Scene scene = new Scene(borderPane, 400, 400); // places the pane in the scene primaryStage.setTitle("Draw a line with arrow keys"); primaryStage.setScene(scene); // places the scene in the stage primaryStage.show(); // shows the window path.requestFocus(); primaryStage.setResizable(false); // prevent user from resizing the window } public static void main(String[] args) { launch(args); }
}
我是OOP / Java编程第二级的学生。我们分配了一个简单的JavaFX接口,使用户可以使用箭头键在窗格中进行绘制。它让我想起了...
这里是我的蚀刻素描的绘制控制器