I need to invert a Slider in javafx.
This is how I built the slider:
Slider slide = new Slider();
slide.setPrefHeight(height);
slide.setMin(0);
slide.setMax(100);
slide.setOrientation(javafx.geometry.Orientation.HORIZONTAL);
slide.setShowTickLabels(true);
slide.setShowTickMarks(true);
slide.setSnapToTicks(true);
This code creates a horizontally aligned slider from value 0 to 100.
But I would like to invert it. As in, place it horizontally but display values from 100 to 0. and not 0 to 100.
Any help? Thanks in advance.
One easy way to invert the slider, without actually doing it, is by using a custom label formatter. Then you just need to take the value and revert it too.
Something like this:
private final DecimalFormat df = new DecimalFormat( "#,##0.00" );
private final double MIN = 0d;
private final double MAX = 100d;
#Override
public void start(Stage primaryStage) {
VBox vbox=new VBox(20);
vbox.setPadding(new Insets(20));
Slider slide = new Slider();
slide.setPrefSize(300,100);
slide.setMin(MIN);
slide.setMax(MAX);
slide.setOrientation(javafx.geometry.Orientation.HORIZONTAL);
slide.setShowTickLabels(true);
slide.setShowTickMarks(true);
slide.setSnapToTicks(true);
slide.setLabelFormatter(new StringConverter<Double>(){
#Override
public String toString(Double object) {
return df.format(MAX-object+MIN);
}
#Override
public Double fromString(String string) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
Label label = new Label("Value: ");
slide.valueProperty().addListener((ov,n,n1)->
label.setText("Value: "+(MAX-n1.doubleValue()+MIN)));
vbox.getChildren().addAll(slide, label);
Scene scene = new Scene(vbox, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
Related
I'm a new JavaFX programmer and my question is I'm getting multiple decimal points in the slider and I only want one.
I'm getting like 99.99999999999 for each value within but I would love to get only one like 99.9
The thing is printf is not applicable here I guess and I only know that way >.<
private void createView() {
final GridPane radioGridPane = new GridPane();
final Label frequencyLabel = new Label("something");
final Slider sliderFrequency = new Slider(87.9, 107.9, 90);
frequencyLabel.textProperty().bind(sliderFrequency.valueProperty().asString());
radioGridPane.add(frequencyLabel, 2, 1);
radioGridPane.add(sliderFrequency, 3, 1);
this.setCenter(radioGridPane);
radioGridPane.setGridLinesVisible(true);
}
You were actually quite close. You can use asString method with the following signature:
javafx.beans.binding.NumberExpressionBase#asString(java.lang.String)
that accepts a format parameter.
Example usage:
public class FormatBindingSSCCE extends Application {
#Override
public void start(Stage stage) {
final Label frequencyLabel = new Label();
final Slider sliderFrequency = new Slider(87.9, 107.9, 90);
frequencyLabel.textProperty().bind(sliderFrequency.valueProperty().asString("%.1f"));
final GridPane radioGridPane = new GridPane();
radioGridPane.add(frequencyLabel, 2, 1);
radioGridPane.add(sliderFrequency, 3, 1);
final Scene scene = new Scene(radioGridPane);
stage.setScene(scene);
stage.show();
}
}
Is it possible to do a simple background "flash" effect with a gradual fade on an arbitrary Node/Region/Pane?
I just want to show a subtle/brief red/white "flash" effect on a VBox (containing a label) to draw attention to it when the label's value changes.
Edit: All examples of this nature I've found so far seem to use a "Shape" (which is a Node), but of course a VBox or a Pane aren't a Shape - so that doesn't help me too much. Calling getShape() on the VBox just returns a null, so that's no help (I guess layout code hasn't been executed yet).
Edit 2:
This ALMOST works, but this dang effect seems to be completely overwriting (I think) everything in the VBox, including the text Label.
ColorInput effect = new ColorInput(0, 0, 900, 25, Paint.valueOf("#FFDDDD"));
Timeline flash = new Timeline(
new KeyFrame(Duration.seconds(0.4), new KeyValue(effect.paintProperty(), Paint.valueOf("#EED9D9"))),
new KeyFrame(Duration.seconds(0.8), new KeyValue(effect.paintProperty(), Paint.valueOf("#E0DDDD"))),
new KeyFrame(Duration.seconds(1.0), new KeyValue(effect.paintProperty(), Paint.valueOf("#DDDDDD"))));
vbox.setEffect(effect);
flash.setOnFinished(e -> vbox.setEffect(null));
flash.play();
Best way would be to provide a custom animation, like this (elaborating on fabian's answer):
#Override
public void start(Stage primaryStage) {
Label label = new Label("Bla bla bla bla");
Button btn = new Button("flash");
VBox box = new VBox(10, label, btn);
box.setPadding(new Insets(10));
btn.setOnAction((ActionEvent event) -> {
//**************************
//this animation changes the background color
//of the VBox from red with opacity=1
//to red with opacity=0
//**************************
final Animation animation = new Transition() {
{
setCycleDuration(Duration.millis(1000));
setInterpolator(Interpolator.EASE_OUT);
}
#Override
protected void interpolate(double frac) {
Color vColor = new Color(1, 0, 0, 1 - frac);
box.setBackground(new Background(new BackgroundFill(vColor, CornerRadii.EMPTY, Insets.EMPTY)));
}
};
animation.play();
});
Scene scene = new Scene(box, 100, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
You could animate a effect, e.g. DropShadow:
#Override
public void start(Stage primaryStage) {
Label label = new Label("Bla bla bla bla");
DropShadow shadow = new DropShadow();
shadow.setColor(Color.RED);
shadow.setSpread(0.75);
Timeline shadowAnimation = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(shadow.radiusProperty(), 0d)),
new KeyFrame(Duration.seconds(0.15), new KeyValue(shadow.radiusProperty(), 20d)));
shadowAnimation.setAutoReverse(true);
shadowAnimation.setCycleCount(2);
Button btn = new Button("flash");
btn.setOnAction((ActionEvent event) -> {
Node target = label;
target.setEffect(shadow);
shadowAnimation.setOnFinished(evt -> target.setEffect(null));
shadowAnimation.play();
});
VBox box = new VBox(10, label, btn);
box.setPadding(new Insets(10));
Scene scene = new Scene(box, 100, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
You can create a fake shape and use the FillTransition Interpolator to apply the shape's fill to the control background.
public static void AnimateBackgroundColor(Control control, Color fromColor,Color toColor,int duration)
{
Rectangle rect = new Rectangle();
rect.setFill(fromColor);
FillTransition tr = new FillTransition();
tr.setShape(rect);
tr.setDuration(Duration.millis(duration));
tr.setFromValue(fromColor);
tr.setToValue(toColor);
tr.setInterpolator(new Interpolator() {
#Override
protected double curve(double t) {
control.setBackground(new Background(new BackgroundFill(rect.getFill(), CornerRadii.EMPTY, Insets.EMPTY)));
return t;
}
});
tr.play();
}
I'm making a battle card game for an uni project (Hearthstone)
The "minion" cards on board have health and attack, and those are constantly changing, I'm trying to make a compound component that would be a center ImageIcon with two "squares" at the bottom left and right, representing the card's current Health and Attack, and one at the top left, representing its cost, all these as StringProperty
I'm really clueless on how to approach this, maybe a coumpound component isn't even necessary
This is an example of how a hearthstone card looks :
Use a StackPane. Put the image on the bottom, and then an AnchorPane on the top. Put a Text in each of the three cornerns, and bind the textProperty() of each to one of the StringProperties. Something like this:
public class BattleCard extends Application {
private static Label label;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
label = new Label();
label.setText("Waiting...");
StackPane root = new StackPane();
root.getChildren().add(new CardPane());
primaryStage.setScene(new Scene(root, 350, 420));
primaryStage.show();
}
public class CardPane extends StackPane {
public CardPane() {
ImageView cardImage = new ImageView(new Image("http://i.stack.imgur.com/1ljQH.png"));
AnchorPane anchorPane = new AnchorPane();
getChildren().addAll(cardImage, anchorPane);
Text costText = new Text("Cost");
Text healthText = new Text("Health");
Text attackText = new Text("Attack");
AnchorPane.setTopAnchor(costText, 0d);
AnchorPane.setLeftAnchor(costText, 0d);
AnchorPane.setBottomAnchor(healthText, 0d);
AnchorPane.setLeftAnchor(healthText, 0d);
AnchorPane.setBottomAnchor(attackText, 0d);
AnchorPane.setRightAnchor(attackText, 0d);
anchorPane.getChildren().addAll(costText, healthText, attackText);
}
}
}
I'm using this to make a iOS-themed JavaFX2 (Java7) application with a frosted glass effect. The problem is that this code uses its effect on an ImageView. I'd like it to use its effect on whatever's behind the window, like this:
Is there anyway to do that? I'd also like that small drop-shadow effect you see around the above image.
To be clear, I don't want that slider or anything, just the effect of being able to see through the window and having that slight shadow around the edges. I want to use this iOS7-ish effect instead of aero, though.
This might be important: I'm using a modified version of Undecorator.
import javafx.animation.*;
import javafx.application.*;
import javafx.beans.property.*;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.effect.*;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.image.*;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
public class FrostyTech extends Application {
private static final double BLUR_AMOUNT = 10;
private static final Effect frostEffect =
new BoxBlur(BLUR_AMOUNT, BLUR_AMOUNT, 3);
private static final ImageView background = new ImageView();
private static final StackPane layout = new StackPane();
#Override public void start(Stage stage) {
layout.getChildren().setAll(background, createContent());
layout.setStyle("-fx-background-color: null");
Scene scene = new Scene(
layout,
200, 300,
Color.TRANSPARENT
);
Platform.setImplicitExit(false);
scene.setOnMouseClicked(event -> {
if (event.getClickCount() == 2) Platform.exit();
});
makeSmoke(stage);
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
stage.show();
background.setImage(copyBackground(stage));
background.setEffect(frostEffect);
makeDraggable(stage, layout);
}
// copy a background node to be frozen over.
private Image copyBackground(Stage stage) {
final int X = (int) stage.getX();
final int Y = (int) stage.getY();
final int W = (int) stage.getWidth();
final int H = (int) stage.getHeight();
try {
java.awt.Robot robot = new java.awt.Robot();
java.awt.image.BufferedImage image = robot.createScreenCapture(new java.awt.Rectangle(X, Y, W, H));
return SwingFXUtils.toFXImage(image, null);
} catch (java.awt.AWTException e) {
System.out.println("The robot of doom strikes!");
e.printStackTrace();
return null;
}
}
// create some content to be displayed on top of the frozen glass panel.
private Label createContent() {
Label label = new Label("Create a new question for drop shadow effects.\n\nDrag to move\n\nDouble click to close");
label.setPadding(new Insets(10));
label.setStyle("-fx-font-size: 15px; -fx-text-fill: green;");
label.setMaxWidth(250);
label.setWrapText(true);
return label;
}
// makes a stage draggable using a given node.
public void makeDraggable(final Stage stage, final Node byNode) {
final Delta dragDelta = new Delta();
byNode.setOnMousePressed(mouseEvent -> {
// record a delta distance for the drag and drop operation.
dragDelta.x = stage.getX() - mouseEvent.getScreenX();
dragDelta.y = stage.getY() - mouseEvent.getScreenY();
byNode.setCursor(Cursor.MOVE);
});
final BooleanProperty inDrag = new SimpleBooleanProperty(false);
byNode.setOnMouseReleased(mouseEvent -> {
byNode.setCursor(Cursor.HAND);
if (inDrag.get()) {
stage.hide();
Timeline pause = new Timeline(new KeyFrame(Duration.millis(50), event -> {
background.setImage(copyBackground(stage));
layout.getChildren().set(
0,
background
);
stage.show();
}));
pause.play();
}
inDrag.set(false);
});
byNode.setOnMouseDragged(mouseEvent -> {
stage.setX(mouseEvent.getScreenX() + dragDelta.x);
stage.setY(mouseEvent.getScreenY() + dragDelta.y);
layout.getChildren().set(
0,
makeSmoke(stage)
);
inDrag.set(true);
});
byNode.setOnMouseEntered(mouseEvent -> {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.HAND);
}
});
byNode.setOnMouseExited(mouseEvent -> {
if (!mouseEvent.isPrimaryButtonDown()) {
byNode.setCursor(Cursor.DEFAULT);
}
});
}
private javafx.scene.shape.Rectangle makeSmoke(Stage stage) {
return new javafx.scene.shape.Rectangle(
stage.getWidth(),
stage.getHeight(),
Color.WHITESMOKE.deriveColor(
0, 1, 1, 0.08
)
);
}
/** records relative x and y co-ordinates. */
private static class Delta {
double x, y;
}
public static void main(String[] args) {
launch(args);
}
}
Related Questions
Frosted Glass Effect in JavaFX?
How do I create a JavaFX transparent stage with shadows on only the border?
The visual effect that you want for OS dependent window decoration, can only be achieved through the APIs that OS provides. And thus was eliminated by StageStyle.TRANSPARENT below.
For JavaFX content itself, you can control the visuals of the stage > scene > root pane hierarchy. Stage and scene do not (and not aimed to) support advanced stylings so were eliminated by setting as transparent below.
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setStyle("-fx-background-color: null;");
root.setPadding(new Insets(10));
DoubleProperty doubleProperty = new SimpleDoubleProperty(0);
Region region = new Region();
region.styleProperty().bind(Bindings
.concat("-fx-background-radius:20; -fx-background-color: rgba(56, 176, 209, ")
.concat(doubleProperty)
.concat(");"));
region.setEffect(new DropShadow(10, Color.GREY));
Slider slider = new Slider(0, 1, .3);
doubleProperty.bind(slider.valueProperty());
root.getChildren().addAll(region, slider);
primaryStage.initStyle(StageStyle.TRANSPARENT);
Scene scene = new Scene(root, 300, 250);
scene.setFill(Color.TRANSPARENT);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
However the drop shadow effect does not play well with alpha value of the background color. You can observe it by changing the shadow's color to another contrast one.
Output:
To expand on Jewlsea's answer .. And using the above example with JavaFX ONLY ..
While the classes are not public API, it does avoid the AWT stack completely.
Here is a non public example :
// copy a background node to be frozen over.
private Image copyBackground(Stage stage) {
final int X = (int) stage.getX();
final int Y = (int) stage.getY();
final int W = (int) stage.getWidth();
final int H = (int) stage.getHeight();
final Screen screen = Screen.getPrimary();
try {
Robot rbt = com.sun.glass.ui.Application.GetApplication().createRobot();
Pixels p = rbt.getScreenCapture(
(int)screen.getBounds().getMinX(),
(int)screen.getBounds().getMinY(),
(int)screen.getBounds().getWidth(),
(int)screen.getBounds().getHeight(),
true
);
WritableImage dskTop = new WritableImage((int)screen.getBounds().getWidth(), (int)screen.getBounds().getHeight());
dskTop.getPixelWriter().setPixels(
(int)screen.getBounds().getMinX(),
(int)screen.getBounds().getMinY(),
(int)screen.getBounds().getWidth(),
(int)screen.getBounds().getHeight(),
PixelFormat.getByteBgraPreInstance(),
p.asByteBuffer(),
(int)(screen.getBounds().getWidth() * 4)
);
WritableImage image = new WritableImage(W,H);
image.getPixelWriter().setPixels(0, 0, W, H, dskTop.getPixelReader(), X, Y);
return image;
} catch (Exception e) {
System.out.println("The robot of doom strikes!");
e.printStackTrace();
return null;
}
}
Results with a small dropshadow added:
DropShadow shdw = new DropShadow();
shdw.setBlurType(BlurType.GAUSSIAN);
shdw.setColor(Color.GAINSBORO);
shdw.setRadius(10);
shdw.setSpread(0.12);
shdw.setHeight(10);
shdw.setWidth(10);
layout.setEffect(shdw);
The opacity is a property of Node, which is the parent class in JavaFX for things that show up on the screen. http://docs.oracle.com/javafx/2/api/javafx/scene/Node.html#opacityProperty
So you can just set the opacity on the object that you want to have fade away. You then have to add some sort of way to change the opacity on the desired object. Using the slider from your image is one way, but there are others.
Drop shadows can be done using the DropShadow effect... http://docs.oracle.com/javafx/2/api/javafx/scene/effect/DropShadow.html. I have never used it. This is a little high level but if there are follow up questions in the comments I can help answer them.
I want to handle click on ProgressBar like on slider. and learn a percent of track.
I would use slider instead progressbar but it doesn't have a highlighted track until thumb.
I need create something like a progress in a music player of playing song, and possibility to seek with a click on progress.
Do anybody have a tips how can i do it?
Here is another approach. Real hybrid of slider and progress bar :). Meet SlidoProgressBar!
public class SlidoProgressBarDemo extends Application {
#Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root);
scene.getStylesheets().add(this.getClass().getResource("style.css").toExternalForm());
stage.setScene(scene);
stage.setTitle("Progress Controls");
double sliderWidth = 200;
final Slider slider = new Slider();
slider.setMin(0);
slider.setMax(50);
slider.setMinWidth(sliderWidth);
slider.setMaxWidth(sliderWidth);
final ProgressBar pb = new ProgressBar(0);
pb.setMinWidth(sliderWidth);
pb.setMaxWidth(sliderWidth);
final ProgressIndicator pi = new ProgressIndicator(0);
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov,
Number old_val, Number new_val) {
pb.setProgress(new_val.doubleValue() / 50);
pi.setProgress(new_val.doubleValue() / 50);
}
});
StackPane pane = new StackPane();
pane.getChildren().addAll(pb, slider);
final HBox hb = new HBox();
hb.setSpacing(5);
hb.setAlignment(Pos.CENTER);
hb.getChildren().addAll(pane, pi);
scene.setRoot(hb);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
with style.css:
.slider .track {
-fx-background-color:null; /* Hide the track */
-fx-background-insets: 1 0 -1 0, 0, 1;
-fx-background-radius: 2.5, 2.5, 1.5;
-fx-padding: 0.208333em; /* 2.5 */
}
The basic logic is to put slider and progress into stackpane. Give them the same width. Bind the progress values of them. Hide the track of the slider.
Output:
i solved this problem with code :
progress.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton() == MouseButton.PRIMARY){
Bounds b1 = progress.getLayoutBounds();
double mouseX = event.getSceneX();
double percent = (((b1.getMinX() + mouseX ) * 100) / b1.getMaxX());
//correcting a percent, i don't know when it need
percent -= 2;
progress.setProgress((percent) / 100);
//do something with progress in percent
}
}
});
Just a tornadoFX example:
package bj
import javafx.application.Application
import javafx.geometry.Insets
import javafx.scene.control.ProgressBar
import javafx.scene.control.Slider
import javafx.scene.paint.Color
import tornadofx.*
/**
* Created by BaiJiFeiLong#gmail.com at 18-12-13 下午9:28
*/
class MainView : View() {
private lateinit var progressBar: ProgressBar
private lateinit var slider: Slider
override val root = vbox {
stackpane {
padding = Insets(100.0)
progressbar(initialValue = .0) {
progressBar = this
maxWidth = Double.MAX_VALUE
}
slider(max = 1, value = .0) {
slider = this
}
}
}
init {
progressBar.progressProperty().bind(slider.valueProperty())
progressBar.paddingLeftProperty.bind(progressBar.heightProperty().divide(2))
progressBar.paddingRightProperty.bind(progressBar.heightProperty().divide(2))
}
}
class MainStylesheet : Stylesheet() {
init {
slider {
track {
backgroundColor = MultiValue(arrayOf(Color.TRANSPARENT))
}
}
}
}
class App : tornadofx.App(MainView::class, MainStylesheet::class)
fun main(args: Array<String>) {
Application.launch(App::class.java, *args)
}