JavaFx, how to add menuBar and drawingPane - scroll

I'an busy with some demo, drawing some lines in a scroll window. So far so good, but now it's possible to draw lines on the menuBar, which should not be possible of course. See code below. Please help!
This is what happens:
See output here
The wrong code:
package Example12a;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class Example12a extends Application {
public static void main(String[] args) {
launch(args);
}
private Line curLine;
#Override
public void start(Stage stage) throws Exception {
Pane drawingPane = new Pane();
BorderPane theBorderPane = new BorderPane();
drawingPane.setPrefSize(800, 800);
drawingPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
MenuBar menuBar = new MenuBar();
// --- Menu File
Menu menuFile = new Menu("File");
MenuItem add = new MenuItem("Save");
add.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
System.out.println("Save");
}
});
menuFile.getItems().addAll(add);
//yOffset = (int)menuBar.getHeight();
Menu menuEdit = new Menu("Edit");
Menu menuView = new Menu("View");
menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
theBorderPane.setTop(menuBar);
ScrollPane scrollPane = new ScrollPane(theBorderPane);
scrollPane.setPrefSize(300, 300);
scrollPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
scrollPane.setStyle("-fx-focus-color: transparent;");
theBorderPane.setOnMousePressed(event -> {
if (!event.isPrimaryButtonDown()) {
return;
}
curLine = new Line(
event.getX(), event.getY(),
event.getX(), event.getY()
);
theBorderPane.getChildren().add(curLine);
});
theBorderPane.setOnMouseDragged(event -> {
if (!event.isPrimaryButtonDown()) {
return;
}
if (curLine == null) {
return;
}
curLine.setEndX(event.getX());
curLine.setEndY(event.getY());
double mx = Math.max(curLine.getStartX(), curLine.getEndX());
double my = Math.max(curLine.getStartY(), curLine.getEndY());
if (mx > theBorderPane.getMinWidth()) {
theBorderPane.setMinWidth(mx);
}
if (my > theBorderPane.getMinHeight()) {
theBorderPane.setMinHeight(my);
}
});
theBorderPane.setOnMouseReleased(event -> curLine = null);
theBorderPane.setCenter(drawingPane);
Scene scene = new Scene(scrollPane);
stage.setMinWidth(100);
stage.setMinHeight(100);
stage.setScene(scene);
stage.show();
}
}

Fixed your layout.
What i did was:
The BorderPane is now your root Pane.
The ScrollPane is the center of the BorderPane and its content is the drawingPane.
The MenuBar is still the the Top of the BorderPane.
I also changed the Mouse Events from borderPane to drawingPane and the lines are added to the drawingPane instead of the borderPane.
So its working fine.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class Example12a extends Application {
public static void main(String[] args) {
launch(args);
}
private Line curLine;
#Override
public void start(Stage stage) throws Exception {
Pane drawingPane = new Pane();
BorderPane theBorderPane = new BorderPane();
drawingPane.setPrefSize(800, 800);
drawingPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
MenuBar menuBar = new MenuBar();
// --- Menu File
Menu menuFile = new Menu("File");
MenuItem add = new MenuItem("Save");
add.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
System.out.println("Save");
}
});
menuFile.getItems().addAll(add);
//yOffset = (int)menuBar.getHeight();
Menu menuEdit = new Menu("Edit");
Menu menuView = new Menu("View");
menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
theBorderPane.setTop(menuBar);
ScrollPane scrollPane = new ScrollPane(drawingPane);
scrollPane.setPrefSize(300, 300);
scrollPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
scrollPane.setStyle("-fx-focus-color: transparent;");
drawingPane.setOnMousePressed(event -> {
if (!event.isPrimaryButtonDown()) {
return;
}
curLine = new Line(
event.getX(), event.getY(),
event.getX(), event.getY()
);
drawingPane.getChildren().add(curLine);
});
drawingPane.setOnMouseDragged(event -> {
if (!event.isPrimaryButtonDown()) {
return;
}
if (curLine == null) {
return;
}
curLine.setEndX(event.getX());
curLine.setEndY(event.getY());
double mx = Math.max(curLine.getStartX(), curLine.getEndX());
double my = Math.max(curLine.getStartY(), curLine.getEndY());
if (mx > drawingPane.getMinWidth()) {
drawingPane.setMinWidth(mx);
}
if (my > drawingPane.getMinHeight()) {
drawingPane.setMinHeight(my);
}
});
theBorderPane.setOnMouseReleased(event -> curLine = null);
theBorderPane.setCenter(scrollPane);
Scene scene = new Scene(theBorderPane);
stage.setMinWidth(100);
stage.setMinHeight(100);
stage.setScene(scene);
stage.show();
}
}
Note:
if your trying to make a Drawing Programm I would prevere to Render all Lines in a Canvas instead of using the Line class. The Canvas is much faster with many Lines.

Related

How to not let my image move out of scene

Here is my following code:
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
Scene scene = new Scene(root, 500, 500, Color.RED);
ImageView dice = new ImageView(new Image(getClass().getResourceAsStream("dice.jpeg")));
dice.setX(0);
dice.setY(300);
root.getChildren().add(dice);
scene.setOnKeyPressed(e -> {
if (dice.getX() >= 0 && dice.getX() <= 500 ) {
switch (e.getCode()) {
case RIGHT:
dice.setX(dice.getX() + KEYBOARD_MOVEMENT_DELTA);
break;
case LEFT:
dice.setX(dice.getX() - KEYBOARD_MOVEMENT_DELTA);
break;
}
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
In my code, my image dice can move left and right, but I don't want it to go outside the scene. I want it to not move once it reaches to end of the scene in both left and right. I tried doing it with if statement, but it doesn't work. Is there any way I can stop my image diceto not move out of scene? Any help is appreciated!
You have a couple of problems in your answer. Firstly, the way you check the boundaries. If the condition is met, your keys no longer control the ImageView. Secondly, using dice.getX() in your test condition. It's best if you use dice.getLayoutBounds().getMaxX() and dice.getLayoutBounds().getMinX(). Also, I recommend using scene.getWidth() instead of hard coding the width of the Scene, because the Scene width can be changed. <-(in your posted code).
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFxTestingGround extends Application {
double KEYBOARD_MOVEMENT_DELTA = 5;
#Override
public void start(Stage primaryStage) throws IOException {
Pane root = new Pane();
Scene scene = new Scene(root, 500, 500, Color.RED);
ImageView dice = new ImageView(createImage("https://cdn.discordapp.com/attachments/250163910454280192/296377451599364107/Untitled.png"));
dice.setFitHeight(100);
dice.setFitWidth(100);
dice.setX(0);
dice.setY(300);
root.getChildren().add(dice);
scene.setOnKeyPressed(e -> {
System.out.println(dice.getLayoutBounds().getMinX() + " : " + dice.getLayoutBounds().getMaxX() + " : " + scene.getWidth());
switch (e.getCode()) {
case RIGHT:
dice.setX(dice.getX() + KEYBOARD_MOVEMENT_DELTA);
break;
case LEFT:
dice.setX(dice.getX() - KEYBOARD_MOVEMENT_DELTA);
break;
}
if (dice.getLayoutBounds().getMinX() < 0)
{
dice.setX(0);
}
else if(dice.getLayoutBounds().getMaxX() > scene.getWidth() )
{
dice.setX(dice.getX() - KEYBOARD_MOVEMENT_DELTA);
}
});
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
Image createImage(String url)
throws IOException {
URLConnection conn = new URL(url).openConnection();
conn.setRequestProperty("User-Agent", "Wget/1.13.4 (linux-gnu)");
try (InputStream stream = conn.getInputStream()) {
return new Image(stream);
}
}
}

How to find index or information of clicked RadioButton

I was wondering if there was anyway to either find the index when a certain RadioButton is pressed or to pass myBuns.get(i) when the RadioButton. Using the code below to create the RadioButtons
RadioButton rButton;
for (i = 0; i < myBuns.size(); i ++){
rButton = new RadioButton("" + myBuns.get(i));
rButton.setToggleGroup(bunGroup);
rButton.setOnAction(this);
this.getChildren().add(rButton);
}
Thanks for any help or suggestions!
You can get the index of the selected toggle using:
toggleGroup.getToggles().indexOf(toggleGroup.getSelectedToggle());
And the text of the selected toggle using:
((RadioButton) toggleGroup.getSelectedToggle()).getText();
By placing the code in the change listener for the selected toggle property, you can monitor when the selected toggle changes and take action as appropriate.
Sample App
import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import java.util.stream.*;
public class ToggleIndexer extends Application {
#Override
public void start(final Stage stage) throws Exception {
ToggleGroup toggleGroup = new ToggleGroup();
ObservableList<RadioButton> buttons = IntStream.range(0, 5)
.mapToObj(i -> new RadioButton("Radio " + i))
.collect(Collectors.toCollection(FXCollections::observableArrayList));
toggleGroup.getToggles().setAll(buttons);
Label selectedIndex = new Label();
selectedIndex.setFont(Font.font("monospace"));
Label selectedItem = new Label();
selectedItem.setFont(Font.font("monospace"));
toggleGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
selectedIndex.setText("");
selectedItem.setText("");
} else {
final int selectedIndexValue =
toggleGroup.getToggles().indexOf(newValue);
selectedIndex.setText("Selected Index: " + selectedIndexValue);
final String selectedItemText =
((RadioButton) toggleGroup.getSelectedToggle()).getText();
selectedItem.setText( "Selected Item: " + selectedItemText);
}
});
VBox layout = new VBox(8);
layout.setPadding(new Insets(10));
layout.setPrefWidth(250);
layout.getChildren().setAll(buttons);
layout.getChildren().addAll(selectedItem, selectedIndex);
stage.setScene(new Scene(layout));
stage.show();
}
public static void main(String[] args) throws Exception {
launch(args);
}
}

Get row from selected cell in TableView in JavaFX when setCellSelectionEnabled(true)

I have the following code which works great when I have standard row selection (always single, never multi).
//This is needed to set the X & Y coordinates of the stage for edit.
myTable.setRowFactory(tableView -> {
TableRow<MyDTO> row = new TableRow<MyDTO>();
row.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
lastSelectedRow.set(row);
}
});
return row ;
});
I am using the row to get the bounds in parent so that when a user selects to edit that row, I can pop a modal window up under the row for them to edit this.
However, my table is also editable for the common fields where there is no look up needed, etc. In that case I want to edit in the table. All this is working, however to make it more user friendly, I want to have cell selection turned on, but when I do that, the row.selectedProptery() listener doesn't fire.
How can I accomplish that, without trying to listen to the selectedProperty() of each cell?
Thanks
I don't think there's a way to do this without registering a listener with the selection property of each cell, via a cell factory on each table column.
However, this isn't too difficult, and can be done both generically (i.e. with the same code no matter the type of the table column) and also respecting any other cell factory behavior you need. Here is a SSCCE:
import java.util.Random;
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;
public class SelectedTableCellTracking extends Application {
private final ObjectProperty<TableCell<?,?>> selectedCell = new SimpleObjectProperty<>();
#Override
public void start(Stage primaryStage) {
TableView<Item> table = new TableView<>();
TableColumn<Item, String> itemCol = column("Item", Item::nameProperty);
TableColumn<Item, Number> valueCol = column("Value", Item::valueProperty);
table.getColumns().add(itemCol);
table.getColumns().add(valueCol);
Random rng = new Random();
for (int i = 1 ; i <= 100; i++) {
table.getItems().add(new Item("Item "+i, rng.nextInt(1000)));
}
table.getSelectionModel().setCellSelectionEnabled(true);
Rectangle highlight = new Rectangle();
highlight.setManaged(false);
highlight.setHeight(12);
highlight.setFill(Color.CORAL);
StackPane root = new StackPane(table, highlight);
selectedCell.addListener((obs, oldCell, newCell) -> {
if (newCell == null) {
highlight.setVisible(false);
} else {
highlight.setVisible(true);
highlight.setX(newCell.localToScene(newCell.getBoundsInLocal()).getMinX());
highlight.setWidth(newCell.getWidth());
highlight.setY(newCell.localToScene(newCell.getBoundsInLocal()).getMaxY());
}
});
table.getColumns().forEach(this::addCellSelectionListenerToColumn);
Scene scene = new Scene(root, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
}
private <S,T> void addCellSelectionListenerToColumn(TableColumn<S,T> col) {
Callback<TableColumn<S,T>, TableCell<S,T>> currentCellFactory = col.getCellFactory();
col.setCellFactory(tc -> {
TableCell<S,T> cell = currentCellFactory.call(tc);
cell.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
if (isNowSelected) {
selectedCell.set(cell);
}
});
return cell ;
});
}
private static <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
TableColumn<S,T> col = new TableColumn<>(title);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col ;
}
public static class Item {
private final StringProperty name = new SimpleStringProperty();
private final IntegerProperty value = new SimpleIntegerProperty();
public Item(String name, int value) {
setName(name);
setValue(value);
}
public final StringProperty nameProperty() {
return this.name;
}
public final String getName() {
return this.nameProperty().get();
}
public final void setName(final String name) {
this.nameProperty().set(name);
}
public final IntegerProperty valueProperty() {
return this.value;
}
public final int getValue() {
return this.valueProperty().get();
}
public final void setValue(final int value) {
this.valueProperty().set(value);
}
}
public static void main(String[] args) {
launch(args);
}
}

onKeyPressed function not working in JavaFX

I am trying to pause the PathTransition and restart it using the keyboard key P.
And also I am trying to increase and decrease the animation speed using UP/Down keys.
But when I run the code, these buttons dont seem to work. What am I doing wrong?
package exercise_15_29;
import javafx.animation.Animation;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.input.KeyCode;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Exercise_15_29 extends Application {
Group car = new Group();
Circle wheel1 = new Circle(15,95,5);
Circle wheel2 = new Circle(35,95,5);
Polygon body1 = new Polygon();
Rectangle body2 = new Rectangle(0.0,80.0,50,10);
Line path = new Line(0,90,500,90);
int speed = 4000;
boolean play = true;
#Override
public void start(Stage primaryStage) {
body1.getPoints().addAll(new Double[]{
10.0, 80.0,
20.0, 70.0,
30.0, 70.0,
40.0, 80.0
});
body1.setFill(Color.BLUE);
body2.setFill(Color.SKYBLUE);
path.setVisible (false);
car.getChildren().addAll(wheel1,wheel2,body1,body2);
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(speed));
pt.setPath(path);
pt.setNode(car);
pt.setCycleCount(Timeline.INDEFINITE);
pt.setAutoReverse(false);
pt.play();
Pane root = new Pane();
root.getChildren().add(car);
root.getChildren().add(path);
Scene scene = new Scene(root, 500, 100);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
root.setOnKeyTyped(e -> {
if(e.getCode() == KeyCode.P) {
if(play == true)
pt.stop();
else
pt.play();
play = !play;
}
});
root.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.UP)
pt.setDuration(Duration.millis(++speed));
else if(e.getCode() == KeyCode.DOWN)
pt.setDuration(Duration.millis(--speed));
});
}
public static void main(String[] args) {
launch(args);
}
}
this code works for me:
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Exercise_15_29 extends Application {
Group car = new Group();
Circle wheel1 = new Circle(15, 95, 5);
Circle wheel2 = new Circle(35, 95, 5);
Polygon body1 = new Polygon();
Rectangle body2 = new Rectangle(0.0, 80.0, 50, 10);
Line path = new Line(0, 90, 500, 90);
int speed = 4000;
boolean play = true;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
body1.getPoints().addAll(new Double[]{
10.0, 80.0,
20.0, 70.0,
30.0, 70.0,
40.0, 80.0
});
body1.setFill(Color.BLUE);
body2.setFill(Color.SKYBLUE);
path.setVisible(false);
car.getChildren().addAll(wheel1, wheel2, body1, body2);
PathTransition pt = new PathTransition();
pt.setDuration(Duration.millis(speed));
pt.setPath(path);
pt.setNode(car);
pt.setCycleCount(Timeline.INDEFINITE);
pt.setAutoReverse(false);
pt.play();
Pane root = new Pane();
root.getChildren().add(car);
root.getChildren().add(path);
Scene scene = new Scene(root, 500, 100);
scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
System.out.println("P");
if (e.getCode() == KeyCode.P) {
if (play)
pt.stop();
else
pt.play();
play = !play;
}
});
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
// root.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
// if (e.getCode() == KeyCode.P) {
// if (play == true)
// pt.stop();
// else
// pt.play();
// play = !play;
// }
// });
scene.setOnKeyPressed(e -> {
System.out.println("UP");
if (e.getCode() == KeyCode.UP)
pt.setDuration(Duration.millis(++speed));
else if (e.getCode() == KeyCode.DOWN)
pt.setDuration(Duration.millis(--speed));
});
// root.setOnKeyPressed(e -> {
// if(e.getCode() == KeyCode.UP)
// pt.setDuration(Duration.millis(++speed));
// else if(e.getCode() == KeyCode.DOWN)
// pt.setDuration(Duration.millis(--speed));
// });
}
}
I changed KeyTyped event to KEY_PRESSED (I recommend this), and also used scene.addEventFilter instead of root.setOnKeyPressed according to https://stackoverflow.com/a/24126049/3291867 and at last you can't change speed of car, you can't change Animation duration after or on playing it (as I know), you can use AnimationTimer for this.

Add EventHandler to ImageView contained in TilePane contained in VBox?

I have the following schema:
A VBox, containing a HBox and a TilePane.
In HBox are buttons, labels, and text fields.
Every time I click on the root (HBox), I should add a ImageView to the tile pane. This ImageView shold contain an image (example: "2.jpg"). Maximum of tile pane components is 5.
Every time I click the image, i should load a new image to the clicked ImageView, exemple "1.jpg". It is not working. When I click on my image it is like i'm clicking on the root so it creates another cell of TilePane. Here's the code, can you help me?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dadao1;
import java.util.HashSet;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
/**
*
* #author Ambra
*/
public class Dadao1 extends Application {
VBox root;
HashSet dadi = new HashSet();
//static int numeroDadi = 0;
#Override
public void start(Stage primaryStage) {
setGui();
Scene scene = new Scene(root, 300, 300);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
*This private method sets up the GUI.
* No parameters are required
*/
private void setGui(){
root = new VBox();
HBox buttons = new HBox();
final Button newGame = new Button("New Game");
final Button print = new Button("Print");
final Button animation = new Button("Moving");
animation.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
// this button is labeled "Moving" at the begin. If pressed it changes its label to "Dissolving" and viceversa.
#Override
public void handle(ActionEvent event) {
if (animation.getText().equals(new String("Moving")))
animation.setText("Dissolving");
else animation.setText("Mooving");
}
});
final Label score = new Label("Total");
final TextField points = new TextField();
final Label pointsLabel = new Label("Score");
root.setStyle("-fx-background-color: green");
buttons.getChildren().addAll(newGame,print,animation,score,points,pointsLabel);
final TilePane dadiPane = new TilePane();
dadiPane.setVgap(10);
dadiPane.setHgap(10);
root.getChildren().addAll(buttons, dadiPane);
root.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if(dadi.size()<5){
System.out.println("Adding img");
final ImageView img = new ImageView("2.jpg");
// should I put final in front of ImageView?
img.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
// I want that when a tile is pressed an event occours.
// that event should be "add a new image to the ImageView just clicked",
// for example: img is not "2.jpg" but "3.jpj", by the way, I'm not able neither
// to to print the folowing messagge :(
// It's like my root is pressed even if my mouse ha clicked at the image in img var.
System.out.println("Tile pressed ");
}
});
dadi.add(img);
dadiPane.getChildren().add(img);
}else System.out.println("You cannot create more than 5 dices");
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
ImageViews don't generate ActionEvents; so it is no surprise that your event handler is never invoked. Since the mouse event is not processed by the ImageView, it propagates up to the container.
Try
img.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
System.out.println("Tile pressed ");
event.consume();
}
});
#James_D is correct; but note for Java 8 you can use the simpler syntax:
img.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
System.out.println("Tile pressed ");
event.consume();
});
Note that MouseEvent.MOUSE_CLICKED is a class from javafx, not from java.awt.event package
imgView. addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, event -> {
//event clicked here
});
For someone who mistakenly import java.awt.event.MouseEvent class

Resources