I want to show a progress bar indicating loading application at the beginning.
How can that be done? I have created a gauge but I think it cannot be implemented in LWUIT form..
Based on my comment, You can use progress bar. And also you can use slider component for instead of showing progress bar in LWUIT.
The best way is to use canvas. You can reuse the class in all your apps and it is very efficient. Create a class, say like a class named Splash:
public class Splash extends Canvas {
private final int height;
private final int width;
private int current = 0;
private final int factor;
private final Timer timer = new Timer();
Image AppLogo;
MayApp MIDlet;
/**
*
* #param mainMIDlet
*/
public Splash(MyApp mainMIDlet) {
this.MIDlet = mainMIDlet;
setFullScreenMode(true);
height = getHeight();
width = this.getWidth();
factor = width / 110;
repaint();
timer.schedule(new draw(), 1000, 01);
}
/**
*
* #param g
*/
protected void paint(Graphics g) {
try {//if you want to show your app logo on the splash screen
AppLogo = javax.microedition.lcdui.Image.createImage("/appLogo.png");
} catch (IOException io) {
}
g.drawImage(AppLogo, getWidth() / 2, getHeight() / 2, javax.microedition.lcdui.Graphics.VCENTER | javax.microedition.lcdui.Graphics.HCENTER);
g.setColor(255, 255, 255);
g.setColor(128, 128, 0);//the color for the loading bar
g.fillRect(30, (height / 2) + 100, current, 6);//the thickness of the loading bar, make it thicker by changing 6 to a higher number and vice versa
}
private class draw extends TimerTask {
public void run() {
current = current + factor;
if (current > width - 60) {
timer.cancel();
try {
//go back to your midlet or do something
} catch (IOException ex) {
}
} else {
repaint();
}
Runtime.getRuntime().gc();//cleanup after yourself
}
}
}
and in your MIDlet:
public class MyApp extends MIDlet {
Splash splashScreen = new Splash(this);
public MyApp(){
}
public void startApp(){
try{
Display.init(this);
javax.microedition.lcdui.Display.getDisplay(this).setCurrent(splashScreen);
//and some more stuff
} catch (IOException ex){}
}
//continue
Related
I am trying to set up the buttons on the following program, but they will not control the program properly. I am not sure why they are not working. The reverse button works, but the start and stop buttons do not.
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ch30 extends Application {
#Override // Override the start method in the Application class
public void start(Stage primaryStage) {
FanPane fan = new FanPane();
HBox hBox = new HBox(5);
Button btPause = new Button("Pause");
Button btResume = new Button("Resume");
Button btReverse = new Button("Reverse");
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(btPause, btResume, btReverse);
BorderPane pane = new BorderPane();
pane.setCenter(fan);
pane.setBottom(hBox);
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 200, 200);
primaryStage.setTitle("Exercise15_28"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
//Runnable first = new Begin();
//Thread first = new Thread();
//t1.start();
Thread first = new Thread(new Runnable() {
#Override public void run() {
while (true) {
try {
//Pause
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
Platform.runLater(new Runnable() {
#Override public void run() {
fan.move();
}
});
}
}
});
first.start();
//Timeline animation = new Timeline(
//new KeyFrame(Duration.millis(100), e -> fan.move()));
//animation.setCycleCount(Timeline.INDEFINITE);
//animation.play(); // Start animation
scene.widthProperty().addListener(e -> fan.setW(fan.getWidth()));
scene.heightProperty().addListener(e -> fan.setH(fan.getHeight()));
//btPause.setOnAction(e -> first.wait());
btResume.setOnAction(e -> first.start());
btReverse.setOnAction(e -> fan.reverse());
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
}
class FanPane extends Pane {
private double w = 200;
private double h = 200;
private double radius = Math.min(w, h) * 0.45;
private Arc arc[] = new Arc[4];
private double startAngle = 30;
private Circle circle = new Circle(w / 2, h / 2, radius);
public FanPane() {
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
getChildren().add(circle);
for (int i = 0; i < 4; i++) {
arc[i] = new Arc(w / 2, h / 2, radius * 0.9, radius * 0.9, startAngle + i * 90, 35);
arc[i].setFill(Color.RED); // Set fill color
arc[i].setType(ArcType.ROUND);
getChildren().addAll(arc[i]);
}
}
private double increment = 5;
public void reverse() {
increment = -increment;
}
public void move() {
setStartAngle(startAngle + increment);
}
public void setStartAngle(double angle) {
startAngle = angle;
setValues();
}
public void setValues() {
radius = Math.min(w, h) * 0.45;
circle.setRadius(radius);
circle.setCenterX(w / 2);
circle.setCenterY(h / 2);
for (int i = 0; i < 4; i++) {
arc[i].setRadiusX(radius * 0.9);
arc[i].setRadiusY(radius * 0.9);
arc[i].setCenterX(w / 2);
arc[i].setCenterY(h / 2);
arc[i].setStartAngle(startAngle + i * 90);
}
}
public void setW(double w) {
this.w = w;
setValues();
}
public void setH(double h) {
this.h = h;
setValues();
}
}
This should be done with a Timeline, I know it's your homework and for some crazy reason your homework has been specified to not use a Timeline. But for anybody else, don't do it this way, just use a Timeline.
That said...
You mention start and stop buttons of which you have none. I assume start means resume and stop means pause as those are the buttons you do have. So I will answer accordingly.
The easiest way to deal with this is to use a boolean variable to control whether or not the fan is moving.
Define a member of your application:
private boolean paused = false;
In your thread only move the fan if not paused:
Platform.runLater(() -> { if (!paused) fan.move(); });
Configure your buttons to set your flag:
btPause.setOnAction(e -> paused = true);
btResume.setOnAction(e -> paused = false);
I've just put the pause variable directly in the calling application, but you could encapsulate the pause status inside the fan object if you wished.
Normally when dealing with multi-threaded stuff you have to be careful about data getting corrupted due to race-conditions. For example, you would use constructs like AtomicBoolean or synchronized statements. But runLater puts everything on to the JavaFX application thread, so you don't necessarily need to worry about that.
There are alternate mechanisms you could use to ensure that your thread didn't keep looping and and sleeping, such as wait/notify or Conditions, but for a sample like this, you probably don't need that here.
Updated Application
Updated sample demonstrating the suggested modifications, tested on JDK 8u60, OS X 10.11.4.
public class ch30 extends Application {
private boolean paused = false;
#Override
public void start(Stage primaryStage) {
FanPane fan = new FanPane();
HBox hBox = new HBox(5);
Button btPause = new Button("Pause");
Button btResume = new Button("Resume");
Button btReverse = new Button("Reverse");
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(btPause, btResume, btReverse);
BorderPane pane = new BorderPane();
pane.setCenter(fan);
pane.setBottom(hBox);
Thread first = new Thread(() -> {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
break;
}
Platform.runLater(() -> { if (!paused) fan.move(); });
}
});
first.setDaemon(true);
first.start();
btPause.setOnAction(e -> paused = true);
btResume.setOnAction(e -> paused = false);
btReverse.setOnAction(e -> fan.reverse());
Scene scene = new Scene(pane, 200, 200);
scene.widthProperty().addListener(e -> fan.setW(fan.getWidth()));
scene.heightProperty().addListener(e -> fan.setH(fan.getHeight()));
primaryStage.setScene(scene);
primaryStage.show();
}
}
Aside
Set the daemon status of your thread so that your application shuts down cleanly when somebody closes the main stage.
first.setDaemon(true);
I've been trying to create a program that displays a ball in the center of a window, with 4 buttons titled Up, Down, Left and Right at the bottom. When you press the buttons the ball moves in the corresponding direction. I've got that part figured out, but I also need to figure out how to make it so if making the ball go in a certain direction obscures it from view, it stops it from going in that direction. I need to find a way to detect the boundaries of the window, and stopping the ball from being able to go outside of the boundary. Here's what I have so far:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Ball extends Application {
private BallControl circle = new BallControl();
#Override
public void start(Stage primaryStage) {
HBox pane = new HBox();
pane.setSpacing(10);
pane.setAlignment(Pos.CENTER);
Button btUp = new Button("UP");
Button btDown = new Button("DOWN");
Button btLeft = new Button("LEFT");
Button btRight = new Button("RIGHT");
pane.getChildren().add(btLeft);
pane.getChildren().add(btRight);
pane.getChildren().add(btUp);
pane.getChildren().add(btDown);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(circle);
borderPane.setBottom(pane);
BorderPane.setAlignment(pane, Pos.CENTER);
btUp.setOnAction(new UpHandler());
btDown.setOnAction(new DownHandler());
btLeft.setOnAction(new LeftHandler());
btRight.setOnAction(new RightHandler());
Scene scene = new Scene(borderPane, 250, 250);
primaryStage.setTitle("Ball"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show();
}
class UpHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
circle.up();
System.out.println("Up Button Pressed");
}
}
class DownHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
circle.down();
System.out.println("Down Button Pressed");
}
}
class LeftHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
circle.left();
System.out.println("Left Button Pressed");
}
}
class RightHandler implements EventHandler<ActionEvent> {
public void handle(ActionEvent e) {
circle.right();
System.out.println("Right Button Pressed");
}
}
public static void main(String[] args) {
launch(args);
}
}
class BallControl extends Pane {
public final double radius = 20;
private double x = radius, y = radius;
private double dx = 1, dy = 1;
private Circle circle = new Circle();
public BallControl() {
getChildren().add(circle);
circle.setCenterX(125.0f);
circle.setCenterY(115.0f);
circle.setRadius(25.0f);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
}
protected void moveBall() {
// Check boundaries
if (x < radius || x > getWidth() - radius) {
dx = 0; // Change ball move direction
}
if (y < radius || y > getHeight() - radius) {
dy = 0; // Change ball move direction
}
// Adjust ball position
x += dx;
y += dy;
circle.setCenterX(x);
circle.setCenterY(y);
}
public void up() {
circle.setCenterY(circle.getCenterY() - 10);
}
public void down() {
circle.setCenterY(circle.getCenterY() + 10);
}
public void left() {
circle.setCenterX(circle.getCenterX() - 10);
}
public void right() {
circle.setCenterX(circle.getCenterX() + 10);
}
}
Here is the part that I was hoping would make the program check for boundaries, but it doesn't seem to work:
protected void moveBall() {
// Check boundaries
if (x < radius || x > getWidth() - radius) {
dx = 0; // Change ball move direction
}
if (y < radius || y > getHeight() - radius) {
dy = 0; // Change ball move direction
}
// Adjust ball position
x += dx;
y += dy;
circle.setCenterX(x);
circle.setCenterY(y);
Someone else already asked a very similar question How to make the ball bounce off the walls in JavaFX?
Nevertheless, all you were missing was a check method before making the next move. I added moveAcceptable() and deleted BallControl for simplicity.
public class Ball extends Application
{
Circle circle = new Circle();
Pane bc = new Pane();
public BorderPane borderPane;
#Override
public void start(Stage primaryStage)
{
bc.getChildren().add(circle);
circle.setCenterX(125.0f);
circle.setCenterY(115.0f);
circle.setRadius(25.0f);
circle.setStroke(Color.BLACK);
circle.setFill(Color.WHITE);
HBox pane = new HBox();
pane.setSpacing(10);
pane.setAlignment(Pos.CENTER);
Button btUp = new Button("UP");
Button btDown = new Button("DOWN");
Button btLeft = new Button("LEFT");
Button btRight = new Button("RIGHT");
pane.getChildren().add(btLeft);
pane.getChildren().add(btRight);
pane.getChildren().add(btUp);
pane.getChildren().add(btDown);
borderPane = new BorderPane();
borderPane.setCenter(bc);
borderPane.setBottom(pane);
BorderPane.setAlignment(pane, Pos.CENTER);
btUp.setOnAction(new UpHandler());
btDown.setOnAction(new DownHandler());
btLeft.setOnAction(new LeftHandler());
btRight.setOnAction(new RightHandler());
Scene scene = new Scene(borderPane, 250, 250);
primaryStage.setTitle("Ball"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show();
}
class UpHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
if (moveAcceptable("up"))
circle.setCenterY(circle.getCenterY() - 10);
System.out.println("Up Button Pressed");
}
}
class DownHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
if (moveAcceptable("Down"))
circle.setCenterY(circle.getCenterY() + 10);
System.out.println("Down Button Pressed");
}
}
class LeftHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
if (moveAcceptable("Left"))
circle.setCenterX(circle.getCenterX() - 10);
System.out.println("Left Button Pressed");
}
}
class RightHandler implements EventHandler<ActionEvent>
{
public void handle(ActionEvent e)
{
if (moveAcceptable("Right"))
circle.setCenterX(circle.getCenterX() + 10);
System.out.println("Right Button Pressed");
}
}
public boolean moveAcceptable(String direction)
{
final Bounds bounds = borderPane.getLayoutBounds();
if (direction.equalsIgnoreCase("up"))
{
return (circle.getCenterY() > (bounds.getMinY() + circle.getRadius()));
} else if (direction.equalsIgnoreCase("down"))
{
return circle.getCenterY() < (bounds.getMaxY() - circle.getRadius());
} else if (direction.equalsIgnoreCase("right"))
{
return circle.getCenterX() < (bounds.getMaxX() - circle.getRadius());
} else //left
{
return circle.getCenterX() > (bounds.getMinX() + circle.getRadius());
}
}
public static void main(String[] args)
{
launch(args);
}
}
I found this example of Internal Frames
http://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html
Is it possible to make the same internal Frames in JavaFX?
With JFXtras there is a Window control, where you can add content and handle the internal window behavior.
First you will need to put in your classpath the jfxtras library. They have some instructions where you can get the library. If you are using maven, just need to add:
<dependency>
<groupId>org.jfxtras</groupId>
<artifactId>jfxtras-labs</artifactId>
<version>2.2-r5</version>
</dependency>
Or download the library and put it into your project classpath, whatever.
Now I put a sample of the demo of the Window with a little difference, allowing generation of several windows.
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import jfxtras.labs.scene.control.window.CloseIcon;
import jfxtras.labs.scene.control.window.MinimizeIcon;
import jfxtras.labs.scene.control.window.Window;
public class WindowTests extends Application {
private static int counter = 1;
private void init(Stage primaryStage) {
final Group root = new Group();
Button button = new Button("Add more windows");
root.getChildren().addAll(button);
primaryStage.setResizable(false);
primaryStage.setScene(new Scene(root, 600, 500));
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
// create a window with title "My Window"
Window w = new Window("My Window#"+counter);
// set the window position to 10,10 (coordinates inside canvas)
w.setLayoutX(10);
w.setLayoutY(10);
// define the initial window size
w.setPrefSize(300, 200);
// either to the left
w.getLeftIcons().add(new CloseIcon(w));
// .. or to the right
w.getRightIcons().add(new MinimizeIcon(w));
// add some content
w.getContentPane().getChildren().add(new Label("Content... \nof the window#"+counter++));
// add the window to the canvas
root.getChildren().add(w);
}
});
}
public double getSampleWidth() {return 600;}
public double getSampleHeight() {return 500;}
#Override
public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) {launch(args);}
}
In the original demo, the event code was in the init method, and no button was included. I add the button to create dynamically windows and adding them to the screen.
Here is a snapshot of the result of the application:
I totally recommend you try the demo of jfxtras. They have really great stuff. Hope it helps.
You can implement simple internal window themselves. Main idea, that InternalWindow class just skeleton, that has internal frame like functionality. You can apply any content to it.
1) Declare class
public class InternalWindow extends Region
2) You should be able to set content in window
public void setRoot(Node node) {
getChildren().add(node);
}
3) You should be able to bring window to front if many window exist
public void makeFocusable() {
this.setOnMouseClicked(mouseEvent -> {
toFront();
});
}
4) Now we need dragging functionality
//just for encapsulation
private static class Delta {
double x, y;
}
//we can select nodes that react drag event
public void makeDragable(Node what) {
final Delta dragDelta = new Delta();
what.setOnMousePressed(mouseEvent -> {
dragDelta.x = getLayoutX() - mouseEvent.getScreenX();
dragDelta.y = getLayoutY() - mouseEvent.getScreenY();
//also bring to front when moving
toFront();
});
what.setOnMouseDragged(mouseEvent -> {
setLayoutX(mouseEvent.getScreenX() + dragDelta.x);
setLayoutY(mouseEvent.getScreenY() + dragDelta.y);
});
}
5) Also we want able to resize window (I show only simple right-bottom resizing)
//current state
private boolean RESIZE_BOTTOM;
private boolean RESIZE_RIGHT;
public void makeResizable(double mouseBorderWidth) {
this.setOnMouseMoved(mouseEvent -> {
//local window's coordiantes
double mouseX = mouseEvent.getX();
double mouseY = mouseEvent.getY();
//window size
double width = this.boundsInLocalProperty().get().getWidth();
double height = this.boundsInLocalProperty().get().getHeight();
//if we on the edge, change state and cursor
if (Math.abs(mouseX - width) < mouseBorderWidth
&& Math.abs(mouseY - height) < mouseBorderWidth) {
RESIZE_RIGHT = true;
RESIZE_BOTTOM = true;
this.setCursor(Cursor.NW_RESIZE);
} else {
RESIZE_BOTTOM = false;
RESIZE_RIGHT = false;
this.setCursor(Cursor.DEFAULT);
}
});
this.setOnMouseDragged(mouseEvent -> {
//resize root
Region region = (Region) getChildren().get(0);
//resize logic depends on state
if (RESIZE_BOTTOM && RESIZE_RIGHT) {
region.setPrefSize(mouseEvent.getX(), mouseEvent.getY());
} else if (RESIZE_RIGHT) {
region.setPrefWidth(mouseEvent.getX());
} else if (RESIZE_BOTTOM) {
region.setPrefHeight(mouseEvent.getY());
}
});
}
6) Usage. First we construct all layout. Then apply it to InternalWindow.
private InternalWindow constructWindow() {
// content
ImageView imageView = new ImageView("https://upload.wikimedia.org/wikipedia/commons/thumb/a/a9/Cheetah4.jpg/250px-Cheetah4.jpg");
// title bar
BorderPane titleBar = new BorderPane();
titleBar.setStyle("-fx-background-color: green; -fx-padding: 3");
Label label = new Label("header");
titleBar.setLeft(label);
Button closeButton = new Button("x");
titleBar.setRight(closeButton);
// title bat + content
BorderPane windowPane = new BorderPane();
windowPane.setStyle("-fx-border-width: 1; -fx-border-color: black");
windowPane.setTop(titleBar);
windowPane.setCenter(imageView);
//apply layout to InternalWindow
InternalWindow interalWindow = new InternalWindow();
interalWindow.setRoot(windowPane);
//drag only by title
interalWindow.makeDragable(titleBar);
interalWindow.makeDragable(label);
interalWindow.makeResizable(20);
interalWindow.makeFocusable();
return interalWindow;
}
7) And how add window to layout
#Override
public void start(Stage primaryStage) throws Exception {
Pane root = new Pane();
root.getChildren().add(constructWindow());
root.getChildren().add(constructWindow());
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
Result
Full code: gist
Upd about close button:
You can add method to InternalWindow
public void setCloseButton(Button btn) {
btn.setOnAction(event -> ((Pane) getParent()).getChildren().remove(this));
}
And when construct:
interalWindow.setCloseButton(closeButton);
how can I implement water 2D wave effect in JavaFX, I have image and want to when click on image a wave(or more) start expanding from that point, just like when we drop a piece rock into the calm water and we see the wave expanding.
This is a conversion of parts of old sun JavaFX 1 ripple generator to JavaFX 2.
It's not the most realistic water ripple effect, but maybe it's enough to get you started creating your own. You could add in a DisplacementMap effect to distort your image as a result of the "waves".
The code uses JavaFX animation timelines to generate expanding concentric circles that gradually fade away of time.
import javafx.animation.*;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.collections.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.*;
import javafx.scene.shape.Circle;
import javafx.stage.*;
import javafx.util.Duration;
public class FishSim extends Application {
private static final Paint SCENE_FILL = new RadialGradient(
0, 0, 300, 300, 500, false, CycleMethod.NO_CYCLE,
FXCollections.observableArrayList(new Stop(0, Color.BLACK), new Stop(1, Color.BLUE))
);
#Override public void start(Stage stage) {
final RippleGenerator rippler = new RippleGenerator();
final Scene scene = new Scene(rippler, 600, 400, SCENE_FILL);
scene.setOnMousePressed(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
rippler.setGeneratorCenterX(event.getSceneX());
rippler.setGeneratorCenterY(event.getSceneY());
rippler.createRipple();
rippler.startGenerating();
}
});
scene.setOnMouseDragged(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
rippler.setGeneratorCenterX(event.getSceneX());
rippler.setGeneratorCenterY(event.getSceneY());
}
});
scene.setOnMouseReleased(new EventHandler<MouseEvent>() {
#Override public void handle(MouseEvent event) {
rippler.stopGenerating();
}
});
stage.setTitle("Click, hold mouse button down and move around to create ripples");
stage.setScene(scene);
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) { launch(args); }
}
/**
* Generates ripples on the screen every 0.5 seconds or whenever
* the createRipple method is called. Ripples grow and fade out
* over 3 seconds
*/
class RippleGenerator extends Group {
private class Ripple extends Circle {
Timeline animation = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(radiusProperty(), 0)),
new KeyFrame(Duration.seconds(1), new KeyValue(opacityProperty(), 1)),
new KeyFrame(Duration.seconds(3), new KeyValue(radiusProperty(), 100)),
new KeyFrame(Duration.seconds(3), new KeyValue(opacityProperty(), 0))
);
private Ripple(double centerX, double centerY) {
super(centerX, centerY, 0, null);
setStroke(Color.rgb(200, 200, 255));
}
}
private double generatorCenterX = 100.0;
private double generatorCenterY = 100.0;
private Timeline generate = new Timeline(
new KeyFrame(Duration.seconds(0.5), new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
createRipple();
}
}
)
);
public RippleGenerator() {
generate.setCycleCount(Timeline.INDEFINITE);
}
public void createRipple() {
final Ripple ripple = new Ripple(generatorCenterX, generatorCenterY);
getChildren().add(ripple);
ripple.animation.play();
Timeline remover = new Timeline(
new KeyFrame(Duration.seconds(3), new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
getChildren().remove(ripple);
ripple.animation.stop();
}
})
);
remover.play();
}
public void startGenerating() {
generate.play();
}
public void stopGenerating() {
generate.stop();
}
public void setGeneratorCenterX(double generatorCenterX) {
this.generatorCenterX = generatorCenterX;
}
public void setGeneratorCenterY(double generatorCenterY) {
this.generatorCenterY = generatorCenterY;
}
}
The original JavaFX 1 fish simulator code that the conversion is based on came from a jfrog repository (which might no longer exist if you click it).
Robert Ladstätter created a 2D water effect sample animation for JavaFX 2 (using Scala). Roberts animation is like viewing the water from the side rather than above, but perhaps some of the concepts might help you.
In this tutorial you can find how to use custom GLSL/HLSL pixel shaders for JavaFX.
And the code for a simple distortion procedural wave in screenSpace in HLSL form:
uniform extern texture ScreenTexture;
sampler ScreenS = sampler_state
{
Texture = <ScreenTexture>;
};
float wave; // pi/.75 is a good default
float distortion; // 1 is a good default
float2 centerCoord; // 0.5,0.5 is the screen center
float4 PixelShader(float2 texCoord: TEXCOORD0) : COLOR
{
float2 distance = abs(texCoord - centerCoord);
float scalar = length(distance);
// invert the scale so 1 is centerpoint
scalar = abs(1 - scalar);
// calculate how far to distort for this pixel
float sinoffset = sin(wave / scalar);
sinoffset = clamp(sinoffset, 0, 1);
// calculate which direction to distort
float sinsign = cos(wave / scalar);
// reduce the distortion effect
sinoffset = sinoffset * distortion/32;
// pick a pixel on the screen for this pixel, based on
// the calculated offset and direction
float4 color = tex2D(ScreenS, texCoord+(sinoffset*sinsign));
return color;
}
technique
{
pass P0
{
PixelShader = compile ps_2_0 PixelShader();
}
}
I hope it helps.
I am trying to build a button with a progress bar which is displayed in the center of the button and instead of text, as soon as the button is tapped, and while some background processing takes place.
What I am doing is to have a custom button and set the animatable as a drawable left to the button, and in onDraw to move the animatable in the center of the button. However, for a short period of time after the button is tapped, I do not know why there are 2 progress bars on the button.
public class ButtonWithProgressBar extends Button {
protected int progressId = R.drawable.progress_bar;
protected Drawable progress;
protected CharSequence buttonText;
#Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
if (Strings.notEmpty(text)) {
buttonText = text;
}
}
public void startSpinning()
{
if(isSpinning()){
return;
}
progress = getContext().getResources().getDrawable(progressId);
final Drawable[] old = getCompoundDrawables();
setCompoundDrawablesWithIntrinsicBounds(old[0], old[1], progress, old[3]);
setEnabled(false);
if(progress instanceof Animatable){
((Animatable)progress).start();
}
setText("");
}
public void stopSpinning()
{
if(!isSpinning()){
return;
}
if(progress instanceof Animatable){
((Animatable)progress).stop();
}
setEnabled(true);
setText(buttonText);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (progress != null) {
final int drawableHeight = progress.getIntrinsicHeight();
final int drawableWidth = progress.getIntrinsicWidth();
final int drawableTop = (getHeight() - drawableHeight) / 2;
final int drawableLeft = (getWidth() - drawableWidth) / 2;
progress.setBounds(drawableLeft, drawableTop, drawableLeft + drawableWidth, drawableTop + drawableHeight);
progress.draw(canvas);
}
}
}
And this is displayed for a short period after tap, before everything looking as I want:
Any ideas why this is happening?
Found the problem.Updated code to a working version.