My circles won't show. What am I missing here? - javafx-8

In Javafx, I am trying to create a pane where I can add points through a mouse click event. When you click on the pane a circle should appear at your mouse position. The circles are being created, as I am tracking them in the console, but they are not showing in the graphics.
I did a similar program to this that auto drew an image that resized with the stage/window, I am using all the same techniques but that project didn't include event handling.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.paint.Color;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
public class ClickToShape extends Application {
private ClickPane clickPane = new ClickPane();
#Override
public void start(Stage primaryStage) throws Exception {
Pane clickPane = new ClickPane();
clickPane.setOnMouseClicked(new ClickHandler());
// create the scene
Scene clickScene = new Scene(clickPane, 500, 500);
// set up the window/stage
primaryStage.setTitle("Click To Draw");
primaryStage.setScene(clickScene); // add the scene to the stage
primaryStage.show(); // fire it off
}
public static void main(String[] args) {
launch(args);
}
class ClickHandler implements EventHandler<MouseEvent> {
#Override
public void handle(MouseEvent e) {
System.out.println("MouseEvent occured");
clickPane.addPoint(e.getX(), e.getY());
}
}
}
class ClickPane extends Pane{
private ArrayList<Circle> points = new ArrayList<Circle>();
private Color color1 = Color.BLACK;
public void addPoint(double x, double y) {
System.out.println("A new point function ran");
Circle newPoint = new Circle (x, y, 300, color1 );
System.out.println(newPoint.toString());
points.add(newPoint);
getChildren().clear();
getChildren().add(newPoint);
}
}
There are no error messages.

the problem is that you instantiated two ClickPane objects, one outside the start method, and another inside the start method, you added the second one to the scene but used the first one to add points, and that's why points aren't showing in your scene
what you can do about this is delete the first line in your start method, so the application will be using the same instance to fire events as to add to the scene, the code would look like this
import java.util.ArrayList;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
public class ClickToShape extends Application {
private ClickPane clickPane = new ClickPane();
#Override
public void start(Stage primaryStage) throws Exception {
clickPane.setOnMouseClicked(new ClickHandler());
// create the scene
Scene clickScene = new Scene(clickPane, 500, 500);
// set up the window/stage
primaryStage.setTitle("Click To Draw");
primaryStage.setScene(clickScene); // add the scene to the stage
primaryStage.show(); // fire it off
}
public static void main(String[] args) {
launch(args);
}
class ClickHandler implements EventHandler<MouseEvent> {
#Override
public void handle(MouseEvent e) {
System.out.println("MouseEvent occured");
clickPane.addPoint(e.getX(), e.getY());
}
}
}
class ClickPane extends Pane{
private ArrayList<Circle> points = new ArrayList<Circle>();
private Color color1 = Color.BLACK;
public void addPoint(double x, double y) {
System.out.println("A new point function ran");
Circle newPoint = new Circle (x, y, 10, color1 );
System.out.println(newPoint.toString());
points.add(newPoint);
getChildren().setAll(newPoint);
}
}

Related

Javafx Stage is blank for a few seconds before showing elements

I am trying to create a game with JavaFX. I have created 2 stages, one is for the splashscreen, the second one is for the actual game itself. This is my first ever JavaFX program, i am a student learning JavaFX. The problem i am having is that when i hide the first stage and show the second one, the second stage stays blank for a few seconds and then continues to show all element(s). For now, there is only a gif showing in the stage with some music(which is not delayed in loading, because it is an instance variable). I don't want to create many instance variables for each of the elements i wish to put into the stage. Below is the code, where only the necessary code is shown to understand the problem:
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Main extends Application {
Dimension window = Toolkit.getDefaultToolkit().getScreenSize();
private double screenWidth = window.getWidth();
private double screenHeight = window.getHeight();
private boolean fullscreen = false;
private boolean music = false;
private double value = 0;
private Group root, root2;
private Image start;
private Image startHover;
private ImageView startViewer;
private Stage stage;
private boolean firstWindowExists = true;
private CheckBox full;
private CheckBox sound;
private Slider slider;
private Image BG;
private ImageView BGView;
private String path = "bin/Audio/8_bit_march.mp3";
private Media media;
private MediaPlayer player;
public static void main(String[] args) {
launch();
}
private void run() {
Image title = new Image("Title.png", 300, 0, true, true);
ImageView titleView= new ImageView();
titleView.setX(200);
titleView.setY(10);
titleView.setImage(title);
add(titleView);
start = new Image("Start1.png", 200, 0, true, true);
startHover = new Image("Start_Hover1.png", 200, 0, true, true);
startViewer= new ImageView();
startViewer.setX(250);
startViewer.setY(300);
startViewer.setOnMouseEntered(mouseEnter);
startViewer.setOnMouseExited(mouseExit);
startViewer.setOnMouseReleased(mouseReleased);
startViewer.setImage(start);
add(startViewer);
if (!firstWindowExists) {//this code works
Image title2 = new Image("BG.gif", (screenWidth/1.25) + 4, (screenHeight/1.25)+4, false, true);
ImageView titleView2= new ImageView();
titleView2.setX(-2);
titleView2.setY(-2);
titleView2.setImage(title2);
add2(titleView2);
}
}
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
if (sound.isSelected()) { // the checkbox is checked to be enabled
slider.setVisible(true);
}
else {
slider.setVisible(false);
}
}
};
EventHandler<MouseEvent> mouseEnter = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) { // irrelevant for this problem
startViewer.setImage(startHover);
}
};
EventHandler<MouseEvent> mouseExit = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
startViewer.setImage(start);
}
};
EventHandler<MouseEvent> mouseReleased = new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
stage.hide(); //hide first window
firstWindowExists = false;
Stage stage2 = new Stage(); // creating a new stage
root2 = new Group(); //creating new group
Scene scene2 = new Scene(root2, Color.WHITE);// creating a scene and adding the newly created Group
Canvas canvas2 = new Canvas(screenWidth/1.25, screenHeight/1.25); // creating a canvas for the screen
root2.getChildren().add(canvas2); // adding canvas to the group (window)
stage2.setTitle("Game"); // setting the title of the window
stage2.setScene(scene2); // Adds scene to the stage
stage2.setFullScreen(fullscreen);
stage2.show(); //after showing the screen here, it stays blank and then adds the title2 gif
stage2.centerOnScreen();
if (music) { //plays music
player.play();
player.setVolume(value);
player.setCycleCount(MediaPlayer.INDEFINITE);
}
run(); // runs the method with heavy lifting stuff
}
};
Timeline timeline = new Timeline(new KeyFrame(Duration.seconds(1), event -> {
}));
private void add(Node node) {
if (firstWindowExists) {
root.getChildren().add(node);
}
}
private void add2(Node node) {
root2.getChildren().add(node);
}
#Override
public void start(Stage stage) throws Exception { // main method which creates the first window
this.stage = stage;
stage.setTitle("Test GUI");
root = new Group();
Scene scene = new Scene(root, Color.DARKGRAY);
Canvas canvas = new Canvas(700, 350);
root.getChildren().add(canvas);
stage.setScene(scene);
stage.setResizable(false);
stage.show();
stage.centerOnScreen();
root.requestFocus();
run();
media = new Media(new File(path).toURI().toString());
player = new MediaPlayer(media);
}
}

Close event in Java FX when close button is pressed

Is there any event handler present in Java FX, if i close a window directly bt pressing [X] button on Top right side.
Which events gets fire in this case ?
Nothing is working so far , neither setOnHiding not setOnCloseRequest()
Please help.
Try this one
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Main extends Application {
#Override
public void start(Stage stage) {
Text text = new Text("!");
text.setFont(new Font(40));
VBox box = new VBox();
box.getChildren().add(text);
final Scene scene = new Scene(box,300, 250);
scene.setFill(null);
stage.setScene(scene);
stage.show();
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we) {
System.out.println("Stage is closing");
}
});
stage.close();
}
public static void main(String[] args) {
launch(args);
}
}
Source Stage close event : Stage « JavaFX « Java

JavaFX8 - How to draw random circles with random x/y centers?

I am trying to draw random circles with random x/y centers, but the result of my code is only one circle at the center of the stage (window).
I use Task class to update my UI every 1 second.
This is my code:
package javafxupdateui;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class JavaFXUpdateUI extends Application {
private Stage window;
private StackPane layout;
private Scene scene;
#Override
public void start(Stage primaryStage) {
window = primaryStage;
window.setTitle("JavaFX - Update UI");
layout = new StackPane();
scene = new Scene(layout, 500, 500);
window.setScene(scene);
window.show();
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
}
Task task = new Task<Void>() {
#Override
protected Void call() throws Exception {
while (true) {
Platform.runLater(new Runnable() {
#Override
public void run() {
drawCircles();
}
});
Thread.sleep(1000);
}
}
};
public void drawCircles() {
Circle circle;
float x = (float)(Math.random()*501);
float y = (float)(Math.random()*501);
circle = new Circle(x, y, 25, Color.RED);
layout.getChildren().add(circle);
scene.setRoot(layout);
window.setScene(scene);
}
public static void main(String[] args) {
launch(args);
}
}
The result of the above code is:
Result GUI
What is going wrong
StackPane is a layout pane, it centers everything by default. As you want to manually place the circles at random locations, you don't want to use a pane which manages the layout for you.
How to fix it
Use a Pane or a Group instead of StackPane. Neither Pane nor Group manage the layout of items for you, so children you add to them at specific locations will remain at those locations.
Aside
You might wish to use a Timeline for your periodic updates rather than a Task with runLater (though the later will still work OK, with a Timeline you don't have to deal with additional complexities of concurrent code).

Can I select text within a label in JavaFX 8 [duplicate]

I just want to create copiable label in JavaFX.
I have tried to create TextField that have no background, have no focus border and default background color, but I have no success.
I have found a lot of questions how to remove focus background from control but all of that looks like "hacks".
Is there are any standard solution to implement copyable text?
You can create a TextField without the border and background color with css:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CopyableLabel extends Application {
#Override
public void start(Stage primaryStage) {
TextField copyable = new TextField("Copy this");
copyable.setEditable(false);
copyable.getStyleClass().add("copyable-label");
TextField tf2 = new TextField();
VBox root = new VBox();
root.getChildren().addAll(copyable, tf2);
Scene scene = new Scene(root, 250, 150);
scene.getStylesheets().add(getClass().getResource("copyable-text.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
and
copyable-text.css:
.copyable-label, .copyable-label:focused {
-fx-background-color: transparent ;
-fx-background-insets: 0px ;
}
This is the solution I used, where there is a small button besides the label to be able to copy the text:
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.Glyph;
import java.util.Locale;
public class CopiableLabel extends Label
{
public CopiableLabel()
{
addCopyButton();
}
public CopiableLabel(String text)
{
super(text);
addCopyButton();
}
public CopiableLabel(String text, Node graphic)
{
super(text, graphic);
}
private void addCopyButton()
{
Button button = new Button();
button.visibleProperty().bind(textProperty().isEmpty().not());
button.managedProperty().bind(textProperty().isEmpty().not());
button.setFocusTraversable(false);
button.setPadding(new Insets(0.0, 4.0, 0.0, 4.0));
button.setOnAction(actionEvent -> AppUtils.copyToClipboard(getText()));
Glyph clipboardIcon = AppUtils.createFontAwesomeIcon(FontAwesome.Glyph.CLIPBOARD);
clipboardIcon.setFontSize(8.0);
button.setGraphic(clipboardIcon);
setGraphic(button);
setContentDisplay(ContentDisplay.RIGHT);
}
}

How to firing Zoomevent in Javafx 8

I'm working on a very simple program. I have an ImageView and I want to firing to this ImageView a ZoomEvent that I created. In Javafx 8 there 2 constructor that I can use to create ZoomEvent. But the listeners doesn't catch the event.
StackPane root = new StackPane();
final ImageView img = new ImageView(url);
img.setOnZoom(new EventHandler<ZoomEvent>() {
#Override
public void handle(ZoomEvent t) {
System.out.println("Zoom!");
}
});
img.setOnZoomStarted(new EventHandler<ZoomEvent>() {
#Override
public void handle(ZoomEvent t) {
System.out.println("Zoom Started!");
}
});
img.setOnZoomFinished(new EventHandler<ZoomEvent>() {
#Override
public void handle(ZoomEvent t) {
System.out.println("Zoom finished!");
}
});
ZoomEvent evt = new ZoomEvent(ZoomEvent.ANY, 200,200,200,200,false,false,false,false,false, false, 5.0,5.0, null);
root.getChildren().add(img);
Scene scene = new Scene(root, 600, 600);
primaryStage.setTitle("Zoom Sample");
primaryStage.setScene(scene);
primaryStage.show();
This is my code so far and I can't figure out what is wrong. There isn't any output.
You never fired the event with ZoomEvent.fireEvent(target, event) or stage.fireEvent(event).
You created the wrong type of event (create a ZoomEvent.ZOOM, not a ZoomEvent.ANY).
You didn't set the event screen co-ordinates correctly.
Working sample:
import javafx.application.Application;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.input.ZoomEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Zoom extends Application {
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage stage) {
final ImageView img = new ImageView(
"http://icons.iconarchive.com/icons/kirei-kaze/kikis-delivery-service/256/jiji-icon.png" // image license: License: Free for non-commercial use. The products or characters depicted in these icons are © by Studio Ghibli. Linkback: http://www.iconarchive.com/artist/kirei-kaze.html
);
img.setOnZoom(e -> System.out.println("Zoom!"));
StackPane layout = new StackPane(img);
stage.setScene(new Scene(layout, 600, 600));
stage.show();
Point2D screenCoords = layout.localToScreen(300, 300);
ZoomEvent evt = new ZoomEvent(
ZoomEvent.ZOOM,
300, 300,
screenCoords.getX(), screenCoords.getY(),
false,false,false,false,false, false, 5.0,5.0, null
);
ZoomEvent.fireEvent(img, evt);
}
}