At http://docs.oracle.com/javafx/2/charts/pie-chart.htm Oracle suggests using
caption.setTranslateX(e.getSceneX());
caption.setTranslateY(e.getSceneY());
to place a Label where the mouse was clicked.. But this does not work at all. See this print screen for proof:
In the code for the example you cite, the PieChart and caption Label are both placed directly in a Group which is the root of the scene. The position of the Label before applying transformations is therefore (0,0) (the top left of the Scene), and so translating it by (e.getSceneX(), e.getSceneY()) moves it to the position of the mouse.
If your layout is different, then the same computation will not necessarily work. For a more general solution, put the chart and caption in a Group, and then call sceneToLocal(...) on the Group to translate the scene coordinates to the correct coordinates in the Group:
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class PieChartSample extends Application {
#Override
public void start(Stage stage) {
BorderPane root = new BorderPane();
ObservableList<PieChart.Data> pieChartData =
FXCollections.observableArrayList(
new PieChart.Data("Grapefruit", 13),
new PieChart.Data("Oranges", 25),
new PieChart.Data("Plums", 10),
new PieChart.Data("Pears", 22),
new PieChart.Data("Apples", 30));
final PieChart chart = new PieChart(pieChartData);
chart.setTitle("Imported Fruits");
final Label caption = new Label("");
caption.setTextFill(Color.DARKORANGE);
caption.setStyle("-fx-font: 24 arial;");
Group chartWithCaption = new Group(chart, caption);
for (final PieChart.Data data : chart.getData()) {
data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED,
new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent e) {
Point2D locationInScene = new Point2D(e.getSceneX(), e.getSceneY());
Point2D locationInParent = chartWithCaption.sceneToLocal(locationInScene);
caption.relocate(locationInParent.getX(), locationInParent.getY());
caption.setText(String.valueOf(data.getPieValue()) + "%");
}
});
}
root.setCenter(chartWithCaption);
// Just some stuff to change the overall layout:
HBox controls = new HBox(5);
controls.setPadding(new Insets(10));
controls.setAlignment(Pos.CENTER);
controls.getChildren().addAll(new Label("Some other stuff here"), new TextField(), new Button("OK"));
root.setTop(controls);
root.setPadding(new Insets(0, 0, 10, 40));
root.setLeft(new Circle(25, Color.SALMON));
Scene scene = new Scene(root);
stage.setTitle("Imported Fruits");
stage.setWidth(600);
stage.setHeight(500);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Related
I want a TextArea's font-size to increase or decrease depending on the width property of the Scene it's in. But I don't want the font-size to grow beyond 16px or shrink beyond 10px.
I found this older post that has the code for making TextArea's font-size grow and shrink from being binded to the Scene's width property but I'm not sure how to add the conditional Bindings for the functionality I want.
This is the code from that post which suits my needs:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class FontBind extends Application {
private DoubleProperty fontSize = new SimpleDoubleProperty(10);
private IntegerProperty blues = new SimpleIntegerProperty(50);
#Override
public void start(Stage primaryStage) {
Button btn = new Button("click me, I change color");
btn.setOnAction((evt)->{blues.set(blues.get()+20);});//max?
Label lbl = new Label("I'm a label");
TextArea ta = new TextArea("Lots of text can be typed\nand even number 1234567890");
HBox hbox = new HBox(new Label("I never change"));
VBox child = new VBox(btn, lbl, ta);
VBox root = new VBox(child, hbox);
Scene scene = new Scene(root, 300, 250);
fontSize.bind(scene.widthProperty().add(scene.heightProperty()).divide(50));
child.styleProperty().bind(Bindings.concat("-fx-font-size: ", fontSize.asString(), ";"
,"-fx-base: rgb(100,100,",blues.asString(),");"));
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Any help would be very much appreciated. I really want to learn more about using Bindings but I'm having trouble understanding how to implement the Bindings methods
This question already has an answer here:
How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?
(1 answer)
Closed 11 months ago.
I get the same error again and again when i try to add images to my JavaFX.
Error: at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
(more lines follow).
It must be related to the path to the images that I specified. I have already read through the general "path" tutorial on StackOverflow without success.
I just want to make a simple scrollBar which enables scrolling through some Images i added to a VBox.
Heres my directory:
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.Shadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class Scrollbar3 extends Application {
// Variablen
final ScrollBar scrollbar = new ScrollBar();
final String[] images = {
"Bilder/bild0.jpg", // 0
"Bilder/bild1.jpg",
"Bilder/bild2.jpg",
"Bilder/bild3.jpg",
"Bilder/bild4.jpg",
};
DropShadow shadow = new DropShadow();
final VBox vbox = new VBox();
#Override
public void start(Stage primaryStage) throws Exception {
// Scene / root
Group root = new Group();
Scene scene = new Scene(root, 400, 400);
root.getChildren().addAll(vbox, scrollbar);
// Effekt
shadow.setColor(Color.BLACK);
shadow.setOffsetX(10);
shadow.setOffsetY(10);
// VBox
vbox.setLayoutX(5);
vbox.setSpacing(10);
vbox.setPadding(new Insets(20));
// Scrollbar
scrollbar.setLayoutX(scene.getWidth() - scrollbar.getWidth());
scrollbar.setOrientation(Orientation.VERTICAL);
scrollbar.setPrefHeight(400);
scrollbar.setMax(2000);
// Bilder
for(int i = 0; i < images.length; i++) {
final ImageView imageView = new ImageView(new Image(images[i]));
imageView.setEffect(shadow);
vbox.getChildren().add(imageView);
}
// Eventhanlding / Listener
scrollbar.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, Number newValue) {
vbox.setLayoutY(-newValue.doubleValue());
}
});
// Stage
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
It looks like you are treating your images as resource images because they are contained in the source folder.
Change the line with the image creation to
final ImageView imageView = new ImageView(new Image(this.getClass().getResourceAsStream(images[i])));
and add an "/" in front of your image paths.
import javafx.animation.FillTransition;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.Timeline;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.effect.BoxBlur;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public class NewFXMain extends javafx.application.Application {
#Override
public void start(Stage primaryStage) {
var pane = new Pane();
var rectangle = new Rectangle(300, 100, 400, 400);
var text = new Text(100, 100, "Java");
rectangle.setOnMouseEntered((event) -> {
var fill = new FillTransition(Duration.millis(1000), rectangle, (Color) rectangle.getFill(), Color.GREEN);
var timeline = new Timeline(new KeyFrame(Duration.millis(1000), new KeyValue(text.effectProperty(), new BoxBlur(4, 4, 4))));
var transition = new ParallelTransition(fill, timeline);
transition.play();
});
pane.getChildren().addAll(rectangle, text);
Scene scene = new Scene(pane, 1000, 720, true, SceneAntialiasing.BALANCED);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This code should create an animation to change the color of the rectangle and blur the text.
However, while FillTransition works perfectly well, BoxBlur effect occurs without animation after 1 second.
How do I write effectProperty correctly to create an animation?
Please help.
Thank you
None of the Effect classes, as of JavaFX 12, implement Interpolatable. This means the animation can't gradually go from no effect to an end effect, thus your animation jumps from null to BoxBlur. You should animate the properties of the BoxBlur instance, rather than the effect property itself.
Here's an example:
import javafx.animation.FillTransition;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.effect.BoxBlur;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
public final class App extends Application {
#Override
public void start(Stage primaryStage) {
var rectangle = new Rectangle(150, 100);
var text = new Text("Hello, World!");
text.setFill(Color.WHITE);
var effect = new BoxBlur(0, 0, 1);
text.setEffect(effect);
var animation = new ParallelTransition(
new FillTransition(Duration.seconds(1), rectangle, Color.BLACK, Color.GREEN),
new Timeline(
new KeyFrame(Duration.ZERO,
new KeyValue(effect.widthProperty(), 0),
new KeyValue(effect.heightProperty(), 0)
),
new KeyFrame(Duration.seconds(1),
new KeyValue(effect.widthProperty(), 10),
new KeyValue(effect.heightProperty(), 10)
)
)
);
rectangle.setOnMouseEntered(event -> {
event.consume();
animation.setRate(1);
animation.play();
});
rectangle.setOnMouseExited(event -> {
event.consume();
animation.setRate(-1);
animation.play();
});
primaryStage.setScene(new Scene(new StackPane(rectangle, text), 500, 300));
primaryStage.show();
}
}
I am trying to create a start screen in javaFX and add a background to it to go behind the button and the text. It does not seem to work for me however, as the background doe not appear for my app. Would like to know what is wrong. Here is my code:
package calendar;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Calendar extends Application {
#Override
public void start(Stage primaryStage) throws IOException {
primaryStage.setTitle("JavaFX Welcome");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text scenetitle = new Text("Get Started");
scenetitle.setFont(Font.font("Bookman", FontWeight.BOLD, 30));
grid.add(scenetitle, 0, 0, 2, 1);
Button start = new Button("Start");
HBox hbStart = new HBox(10);
hbStart.setAlignment(Pos.CENTER);
hbStart.getChildren().add(start);
grid.add(hbStart, 1, 10);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
start.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
}
});
Scene scene = new Scene(grid, 800, 600);
primaryStage.setScene(scene);
scene.getStylesheets().add
(Calendar.class.getResource("background.css").toExternalForm());
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
The code for the css file is as follows:
.root { -fx-background-image: url("background.jpeg"); }
Any help would be appreciated. I am fairly certain that this is not a problem with me misplacing or misnaming the file.
How I will get white rectangle in the middle of scene. I wanna preserve my own code and the height and width of it. Probably it should be use to set X and Y layouts. but I do not know how. When I set them, it resize it from upper left corner.
Code:
Pane paneCanvas = new Pane();
final Canvas canvas = new Canvas();
paneCanvas.setStyle("-fx-background-color: white;");
canvas.setHeight(32);
canvas.setWidth(32);
paneCanvas.getChildren().add(canvas);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
Try this example ... for position in middle of scene you can calculate width this formula:
layoutxcanvas=(widthscene/2)-(widthcanvas/2)
layoutycanvas=(heightscene/2)-(heightcanvas/2)
import java.awt.Graphics2D;
import java.awt.Paint;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavaFXApplication1 extends Application {
#Override
public void start(Stage primaryStage) {
Pane paneCanvas = new Pane();
final Canvas canvas = new Canvas();
paneCanvas.setStyle("-fx-background-color: black;");
canvas.setHeight(32);
canvas.setWidth(32);
canvas.getGraphicsContext2D().setFill(Color.WHITE);
canvas.getGraphicsContext2D().fillRect(0, 0, 32, 32);
canvas.setLayoutX((300/2)-(32/2));
canvas.setLayoutY((300/2)-(32/2));
paneCanvas.getChildren().add(canvas);
Scene scene=new Scene(paneCanvas,300,300);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}