button doesn't change colour after scene building in JavaFX - javafx

I would like to change the colour of a button after I build the scene.
I have to do a battleship. When I place a boat many buttons have to change their colours.
So, I have a function do to it and I test that. I filter the boxes contained in "oceanBoxes" by their coordinates and when I get true I call function putBoatInside.
private void placeGuiBoat(int x, int y, int direction, int size) {
List<Integer> listBoxesBoatNeed;
if(direction == HORIZONTAL) {
listBoxesBoatNeed = IntStream.range(y,y+size).boxed().collect(Collectors.toList());
try {
listBoxesBoatNeed.forEach(e -> oceanBoxes.stream().filter(p->p.getX() == x && p.getY() == e).findFirst().orElse(null).putBoatInside());
} catch(Exception e) {}
}
}
And in Boxe class, I have this
public void putBoatInside() {
this.setStyle("-fx-background-color:#000;");
}
EDIT
Here the minimal reproducible example I made to solve it and see that the problem wasn't there.
Main
package application;
import javafx.scene.layout.GridPane;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import GUI.BtnOcean;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
GridPane root = new GridPane();
BtnOcean btn = new BtnOcean(1,1);
BtnOcean btn1 = new BtnOcean(1,2);
BtnOcean btn2 = new BtnOcean(1,3);
BtnOcean btn3 = new BtnOcean(1,4);
BtnOcean btn4 = new BtnOcean(1,5);
ArrayList<BtnOcean> ocean = new ArrayList<BtnOcean>(Arrays.asList(btn,btn1,btn2,btn3,btn4));
Button btn5 = new Button("change");
List<Integer> list = IntStream.range(1,5).boxed().collect(Collectors.toList());
btn5.setOnAction(j -> {
list.stream().forEach(e -> ocean.stream().filter( p-> p.getX() == 1 && p.getY() == e ).findFirst().orElse(null).putBoatInside());
});
root.add(btn, 0, 0);
root.add(btn1, 1, 0);
root.add(btn2, 2, 0);
root.add(btn3, 3, 0);
root.add(btn4, 4, 0);
root.add(btn5, 5, 0);
Scene scene = new Scene(root,1200,800);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
BtnOcean class
package GUI;
import javax.swing.ImageIcon;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class BtnOcean extends Button{
private int x;
private int y;
private String cssProps = "-fx-background-color:#fff;" +
"-fx-border-color:#000000;"+
"-fx-border-width: 1px;";
public BtnOcean(int x, int y,String text){
this.x = x;
this.y = y;
setMinHeight(60);
setMinWidth(60);
setStyle(cssProps);
setText(text);
}
public BtnOcean(int x, int y){
this.x = x;
this.y = y;
setMinHeight(60);
setMinWidth(60);
setStyle(cssProps);
}
public void putBoatInside() {
System.out.println(this);
this.setStyle("-fx-background-color:#000;");
}

Related

Click to draw a shape (circle)

this code Draw a circle and I want to put a button that when I click on the button I can do draw a circle. How Can I put Button for code below?
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class HelloApplication extends Application {
private Circle circle;
private boolean firstClick = true;
private double centerX, centerY;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
Group root = new Group();
circle = new Circle();
circle.setFill(Color.TRANSPARENT);
circle.setStroke(Color.BLACK);
root.getChildren().add(circle);
Scene scene = new Scene(root, 600, 600);
setHandlers(scene);
primaryStage.setTitle("blank");
primaryStage.setScene(scene);
primaryStage.show();
}
public void setHandlers(Scene scene) {
scene.setOnMouseClicked(e -> {
if (firstClick) {
centerX = e.getX();
centerY = e.getY();
// sets the center
circle.setCenterX(centerX);
circle.setCenterY(centerY);
// sets next "stage" of drawing your circle
firstClick = false;
// on second click will reset the process by setting firstClick to true
}
else {
firstClick = true;
}
});
scene.setOnMouseMoved(e -> {
// will only evaluate on the first instance of a click
if (!firstClick) {
// Distance formula between center of circle and mouse pointer
double c = Math
.sqrt(Math.pow(centerX - e.getX(), 2) + Math.pow(centerY - e.getY(), 2));
circle.setRadius(c);
}
});
}
}
The following mre demonstrates the basic functionality you required :
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;
public class DrawCircles extends Application {
private Pane drawPane; //container for shapes
private Circle clickedPoint;
private static Color POINT_COLOR = Color.BLUEVIOLET, CIRCLE_COLOR = Color.RED;
private static int POINT_RADIUS = 2;
#Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
drawPane = new Pane(); //container for shapes
root.setCenter(drawPane);
Label help = new Label();
ToggleButton draw = new ToggleButton(" Draw ");
draw.selectedProperty().addListener((ChangeListener<Boolean>) (obs, oldV, newV) -> {
draw.setText(newV ? "Drawing" : " Draw ");
help.setText(newV ? "Double click on one point. Double click on second point" : "");
});
HBox buttonBar = new HBox(10, draw, help);
buttonBar.setAlignment(Pos.BOTTOM_LEFT);
root.setBottom(buttonBar);
drawPane.setOnMouseClicked(event -> {
if(!draw.isSelected()) return;
if (event.getButton().equals(MouseButton.PRIMARY) && event.getClickCount() == 2) {
addPoint( event.getX() , event.getY());
}
});
Scene scene = new Scene(root, 500, 500);
primaryStage.setScene(scene);
primaryStage.setTitle("Draw Circles");
primaryStage.show();
}
private void addPoint(double x, double y) {
if(clickedPoint == null){ //no previously clicked point
clickedPoint = new Circle(x, y, POINT_RADIUS, POINT_COLOR);
drawPane.getChildren().add(clickedPoint); //mark clicked point
}else{
Shape shape = makeCircle(clickedPoint.getCenterX(), clickedPoint.getCenterY(), x, y);
drawPane.getChildren().add(shape); //add line
drawPane.getChildren().remove(clickedPoint);// remove first clicked point
clickedPoint = null;
}
}
private Shape makeCircle(double xCenter, double yCenter, double xEdge, double yEdge){
double radius =Math.sqrt( Math.pow(xEdge - xCenter, 2) + Math.pow(yEdge - yCenter, 2));
return new Circle(xCenter, yCenter, radius, CIRCLE_COLOR);
}
public static void main(String[] args) {
launch(args);
}
}

javaFX: MediaPlayer's seek method hangs the player without error message oder Status change

I have a programm with 8 mediaplayer, which are controlled like one big video with a single set of controls.
I have one Slider to control the time, aka I call all MediaPlayer's seek methods in onMouseReleased of the slider. My Problem is, the mediaplayer hang all the time, without changing their status or calling onError . When I put every seek in a new Thread, these problems disappear msot of the time, but not always and I'm gettign a lot of concurrency issues.
Does anybody know the reason why the player hangs?
EDIT:
Ok, here a minimal reproducible example:
Class MediaControlMinimal:
package org.example;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Window;
import javafx.util.Duration;
import java.util.ArrayList;
import java.util.List;
public class MediaControlMinimal extends BorderPane {
private final List<MediaPlayer> mpList;
private Duration duration;
private boolean shouldPlay;
private int setupComplete;
private final Slider timeSlider;
private final HBox mediaBar;
private final Button playButton;
private final MediaPlayer controlMediaPlayer;
public MediaControlMinimal(List<MediaPlayer> mpList, int videoRows) {
this.mpList = mpList;
List<MediaView> mvList = new ArrayList<>(mpList.size());
Pane mvPane = new Pane() {
};
for (MediaPlayer mp : mpList) {
MediaView mediaView = new MediaView(mp);
mvList.add(mediaView);
mvPane.getChildren().add(mediaView);
}
mvPane.setStyle("-fx-background-color: black;");
setCenter(mvPane);
mediaBar = new HBox(); // 5 als param für spacing = 5, sieh zeile 247
mediaBar.setAlignment(Pos.CENTER);
mediaBar.setPadding(new Insets(5, 10, 5, 10));
BorderPane.setAlignment(mediaBar, Pos.CENTER);
playButton = new Button();
playButton.setOnAction(e -> {
shouldPlay = !shouldPlay;
if (shouldPlay) {
playAll();
} else {
pauseAll();
}
});
// Add time slider
timeSlider = new Slider();
HBox.setHgrow(timeSlider, Priority.ALWAYS);
timeSlider.setMinWidth(50);
timeSlider.setMaxWidth(Double.MAX_VALUE);
timeSlider.setOnMouseReleased(event -> {
for (MediaPlayer mp : mpList) {
mp.seek(Duration.millis((event.getX() / timeSlider.getWidth()) * timeSlider.getMax());
}
});
controlMediaPlayer = mpList.get(1);
controlMediaPlayer.currentTimeProperty().addListener(observable -> {
updateValues(controlMediaPlayer);
});
for (MediaPlayer mp : mpList) {
mp.setOnReady(() -> {
int videosPerRow = mpList.size() / videoRows;
if (setupComplete == 0) {
duration = mp.getMedia().getDuration();
timeSlider.setMax(duration.toMillis());
updateValues(mp);
final Window window = mvPane.getScene().getWindow();
final double titleHeight = window.getHeight() - mvPane.getScene().getHeight();
double windowHeight = videoRows * mp.getMedia().getHeight() + titleHeight;
if (!Main.isTransDesign) {
windowHeight += mediaBar.getHeight();
}
window.setHeight(windowHeight);
window.setWidth(videosPerRow * mp.getMedia().getWidth());
}
if (setupComplete < mpList.size()) {
final Node mpNode = mvPane.getChildren().get(mpList.indexOf(mp));
if (mpList.indexOf(mp) != 0 && mpNode.getLayoutX() == 0 && mpNode.getLayoutY() == 0) {
//fenster höhe
double xRelocate = mp.getMedia().getWidth() * (mpList.indexOf(mp) % videosPerRow);
double yRelocate = mp.getMedia().getHeight() * Math.floorDiv(mpList.indexOf(mp), videosPerRow);
mpNode.relocate(xRelocate, yRelocate);
}
++setupComplete;
}
});
mp.setCycleCount(MediaPlayer.INDEFINITE);
}
mediaBar.getChildren().add(playButton);
mediaBar.getChildren().add(timeSlider);
setBottom(mediaBar);
}
private void playAll() {
for (MediaPlayer mp : mpList) {
mp.play();
}
}
private void pauseAll() {
for (MediaPlayer mp : mpList) {
mp.pause();
}
}
protected void updateValues(MediaPlayer mp) {
if (timeSlider != null) {
Platform.runLater(() -> {
Duration currentTime = mp.getCurrentTime();
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled() && duration.greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.toMillis());
}
});
}
}
}
Class EmbeddedMediaPlayer
package org.example;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
public class EmbeddedMediaPlayer extends Application {
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle(Main.WINDOW_TITLE);
Group root = new Group();
Scene scene = new Scene(root, 1586, 900);
List<MediaPlayer> mediaPlayerList = new ArrayList<>();
// create media player
for(String s : Main.MEDIA_URL){
MediaPlayer mediaPlayer = new MediaPlayer(new Media(s));
mediaPlayer.setAutoPlay(false);
mediaPlayerList.add(mediaPlayer);
}
MediaControlMinimal mediaControl = new MediaControlMinimal(mediaPlayerList, Main.VIDEO_ROWS);
scene.setRoot(mediaControl);
primaryStage.setScene(scene);
primaryStage.show();
}
#Override
public void stop(){
System.out.println("Stage is closing");
System.exit(0);
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Class Main
package org.example;
public class Main {
public static final String[] MEDIA_URL = {
"https://video.fogodosamba.de/media/SambaReggae_Sticks.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Fundo1.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Dobra.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Fundo2.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Ansage.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Timbal.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Caixa.mp4",
"https://video.fogodosamba.de/media/SambaReggae_Repi.mp4"
};
public static final int VIDEO_ROWS = 2;
public static final String WINDOW_TITLE = "";
public static void main(String[] args) {
EmbeddedMediaPlayer.main(args);
}
}
EDIT 2:
Sometimes a video hsngs for a while, then starts up again, but plays in slow motion. No error message in onerror, no state change and getCurrentRate = 1.

JavaFX change scene (view) in MVC

I have to do a game (Connect 4) as a project for my university, based on an MVC(Model, View, Controller) model. Now I am done with the two views (one which asks the user for input, the other that should print out the grid for the game, based on the user's input, but I have a problem, I cannot merge these two views and the two CSS documents together. Does anybody know how to do this?
Thank you very much for your help!
import java.util.InputMismatchException;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Labeled;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
public class View2 extends Application implements EventHandler<ActionEvent>{
Stage window;
//Boolean variable to store the answer
static char number;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
//GridPane
GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(8);
grid.setHgap(10);
//Row Label - Constraints use (child, column, row)
Label rowLabel = new Label("Number of Rows:");
GridPane.setConstraints(rowLabel, 0, 0);
//Column Label
Label colLabel = new Label("Number of Columns:");
GridPane.setConstraints(colLabel, 0, 1);
//Connections Label
Label conLabel = new Label("Needed Connections:");
GridPane.setConstraints(conLabel, 0, 2);
//Rows Input
TextField rowInput = new TextField();
rowInput.setPromptText("Number Rows");
GridPane.setConstraints(rowInput, 1, 0);
//Column Input
TextField colInput = new TextField();
colInput.setPromptText("Number Columns");
GridPane.setConstraints(colInput, 1, 1);
//Needed Connections
TextField conInput = new TextField();
conInput.setPromptText("Needed Connections");
GridPane.setConstraints(conInput, 1, 2);
//Display customized grid
Button displayButton = new Button("Display Grid");
GridPane.setConstraints (displayButton, 1, 4);
//Checking Input
displayButton.setOnAction(e-> {
isInt(rowInput, rowInput.getText());
isInt(colInput, colInput.getText());
isInt(conInput, conInput.getText());
});
//Add everything to grid
grid.getChildren().addAll(rowLabel, colLabel, conLabel, rowInput, colInput, conInput, displayButton);
Scene scene = new Scene(grid, 400, 200);
scene.getStylesheets().add(getClass().getResource("styleView2.css").toExternalForm());
window.setScene(scene);
window.show();
}
//Check input
private boolean isInt(TextField input, String message) {
try {
int number=Integer.parseInt(input.getText());
input.setText("The input is valid");
return true;
} catch(NumberFormatException e) {
input.setText("The input is not valid");
}
return false;
}
}
//CSS for View
.root{
-fx-background-color: #383838;
-fx-font-size: 40pt;
}
.button{
-fx-background-color: linear-gradient(#86c1b9, #7cafc2);
-fx-background-radius: 15;
-fx-min-width: 120;
-fx-min-height: 120;
-fx-pref-width: 120;
-fx-pref-height: 120;
}
//CSS for View2
.root{
-fx-background-color: #F8F8F8;
-fx-font-size: 10pt;
}
.label{
-fx-text-fill: #181818;
}
.button{
-fx-background-color: #AB4642;
-fx-text-fill: #FFFFFF;
-fx-background-radius: 5;
}
import java.util.ArrayList;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
//View for creating the grid
public class View {
private Stage stage;
private Model model;
public int hRows = 6;
public int vRows = 7;
ArrayList[] hArray = new ArrayList[hRows];
public View(Stage stage, Model model) {
this.stage = stage;
this.model = model;
GridPane root = new GridPane();
stage.setTitle("Connect 4");
for (int i = 0; i < hArray.length; i ++) {
hArray[i] = new ArrayList<Button>();
}
for (int i = 0; i < hArray.length; i ++) {
for(int j = 0; j < vRows; j ++ ) {
Button b = new Button();
hArray[i].add(b);
b.setOnAction(this::gameButtons);
}
}
for (int i = 0; i < hArray.length; i ++) {
for(int j = 0; j < vRows; j ++ ) {
root.add((Node) (hArray[i].get(j)), i, j);
}
}
// Standard stuff for Scene and Stage
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
public void start() {
stage.show();
}
private void gameButtons(ActionEvent e) {
}
}
When you need to learn something new, it is often much easier to do it on a smaller scale, rather than on you application.
This goes in line with SO requirement of posting mre when asking or answering.
Your question is essentially how to change scene in a javafx app, and the following code demonstrates just that, and nothing else. To test it you may copy the entire code into one file (View2.java) and run:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class View2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
Button displayButton = new Button("Display Grid");
//Change scene
displayButton.setOnAction(e-> {
Model model = new Model(6,12);
View view = new View(model);
primaryStage.setScene(new Scene(view.getRoot()));
});
grid.getChildren().add(displayButton);
Scene scene = new Scene(grid, 400, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class View{
private final GridPane root;
public View(Model model) {
root = new GridPane();
for (int i = 0; i < model.gethRows(); i ++) {
for(int j = 0; j < model.getvRows(); j ++ ) {
Button b = new Button(i+"-"+j);
root.add(b, j, i);
}
}
}
GridPane getRoot() {
return root;
}
}
class Model {
private final int hRows, vRows;
Model(int hRows, int vRows) {
this.hRows = hRows;
this.vRows = vRows;
}
int gethRows() {
return hRows;
}
int getvRows() {
return vRows;
}
}

how to make imageView move in the direction it's facing after rotate it in javafx

I'm making game using javafx and chick image is my main player. I display chick image using Imageview. I want this chick to constantly spnining and when I pressed UP arrow, I want it to stop spinning and move toward the direction it's facing.
I use setRotate to spin my chick. When I execute code, my chick spin just fine but when I pressed UP arrow keyboard, it moves toward a random direction. How can I fix it?
package javagame;
import java.util.ArrayList;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.NodeOrientation;
import javafx.geometry.Point3D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
public class JavaGame extends Application {
#Override
public void start(Stage primaryStage) {
Chick test = new Chick(1);
test.setPosition(300,200);
StackPane root = new StackPane();
root.getChildren().addAll(test);
Scene scene = new Scene(root, 900, 700);
ArrayList<String> input = new ArrayList<String>();
scene.setOnKeyPressed(
new EventHandler<KeyEvent>()
{
public void handle(KeyEvent e)
{
String code = e.getCode().toString();
if ( !input.contains(code) )
input.add( code );
}
});
scene.setOnKeyReleased(
new EventHandler<KeyEvent>()
{
public void handle(KeyEvent e)
{
String code = e.getCode().toString();
input.remove( code );
}
});
new AnimationTimer(){
public void handle(long now){
System.out.println(test.getNodeOrientation());
System.out.println("effective " +test.getEffectiveNodeOrientation());
if(input.contains("UP")){
test.move();
System.out.println(test.getAngle());
System.out.println(test.getPosition());
System.out.println("getRotate " +test.getRotate());
System.out.println("local" +test.getLocalToSceneTransform());
System.out.println("parent" +test.getLocalToParentTransform());
}
else{
test.stop();
System.out.println(test.getAngle());
System.out.println(test.getPosition());
System.out.println("local" +test.getLocalToSceneTransform());
System.out.println("parent" +test.getLocalToParentTransform());
}
}
}.start();
primaryStage.setTitle("java game");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
And here's the class that I created about player
package javagame;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
public class Chick extends Pane{
private Image [] img = {new Image("file:img/0.png"),
new Image("file:img/pcTop.png"), new Image("file:img/rcTop.png"),
new Image("file:img/ycTop.png"),new Image("file:img/gcTop.png")};
private ImageView imageView;
private double x;
private double y;
private double vx=1;
private double vy=1;
private double angle=0;
private double q;
private double toAngle = 1;
private Timeline rotateAnimation;
private Timeline translateAnimation;
public Chick(){
}
public Chick(int num){
imageView = new ImageView(img[num]);
//vx=5; vy=5;
getChildren().clear();
getChildren().addAll(imageView);
rotateAnimation = new Timeline(
new KeyFrame( Duration.millis(100), e ->{ spin();} ) );
rotateAnimation.setCycleCount(Timeline.INDEFINITE);
rotateAnimation.play();
translateAnimation = new Timeline(
new KeyFrame( Duration.millis(20), e ->{ move();} ) );
translateAnimation.setCycleCount(Timeline.INDEFINITE);
}
public void setPosition(double x, double y){
this.x = x;
this.y = y;
imageView.setTranslateX(x);
imageView.setTranslateY(y);
}
public String getPosition(){
return "( " +x+ ", " +y+ " )";
}
public double getQuardant(){
if(angle>0 && angle<90)q=1;
if(angle>90 && angle<180)q=2;
if(angle>180 && angle<270)q=3;
if(angle>270 && angle<360)q=4;
else q=0;
return q;
}
public void move(){
translateAnimation.play();
rotateAnimation.stop();
x += vx*cos(angle);
y += vy*sin(360-angle);
setPosition(x,y);
//this.relocation(x,y);
}
public void stop(){
rotateAnimation.play();
translateAnimation.stop();
}
public void spin(){
if(angle < 359)angle += toAngle;
else angle=0;
imageView.setRotate(angle);
}
public double getAngle(){
return angle;
}
public void setToAngle(double d){
toAngle = d;
}
}
Before you compute your sin and cos you have to convert the angle to radians. (Math.toRadians())

Image Slider using JavaFX Error Syntax error on token(s), misplaced construct(s)

package javafx;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ImageSlide extends Application {
// Width and height of image in pixels
private final double IMG_WIDTH = 600;
private final double IMG_HEIGHT = 300;
private final int NUM_OF_IMGS = 3;
private final int SLIDE_FREQ = 4; // in secs
#Override
public void start(Stage stage) throws Exception {
//root code
StackPane root = new StackPane();
Pane clipPane = new Pane();
// To center the slide show incase maximized
clipPane.setMaxSize(IMG_WIDTH, IMG_HEIGHT);
clipPane.setClip(new Rectangle(IMG_WIDTH, IMG_HEIGHT));
HBox imgContainer = new HBox();
//image view
ImageView imgGreen = new ImageView(new Image(getClass()
.getResourceAsStream("\\Merged1.pngg")));
ImageView imgBlue = new ImageView(new Image(getClass()
.getResourceAsStream("\\Merged2.png")));
ImageView imgRose = new ImageView(new Image(getClass()
.getResourceAsStream("\\Merged3.png")));
imgContainer.getChildren().addAll(imgGreen, imgBlue, imgRose);
clipPane.getChildren().add(imgContainer);
root.getChildren().add(clipPane);
Scene scene = new Scene(root, IMG_WIDTH, IMG_HEIGHT);
stage.setTitle("Image Slider");
stage.setScene(scene);
startAnimation(imgContainer);
stage.show();
}
//start animation
private void startAnimation(final HBox hbox) {
//error occured on (ActionEvent t) line
//slide action
EventHandler<ActionEvent> slideAction = (ActionEvent t) {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
//eventHandler
EventHandler<ActionEvent> resetAction = (ActionEvent t) {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1), hbox);
trans.setByX((NUM_OF_IMGS - 1) * IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
List<KeyFrame> keyFrames = new ArrayList<>();
for (int i = 1; i <= NUM_OF_IMGS; i++) {
if (i == NUM_OF_IMGS) {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), resetAction));
} else {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), slideAction));
}
}
//add timeLine
Timeline anim = new Timeline(keyFrames.toArray(new KeyFrame[NUM_OF_IMGS]));
anim.setCycleCount(Timeline.INDEFINITE);
anim.playFromStart();
}
//call main function
public static void main(String[] args) {
launch(args);
}
}
The lines
EventHandler<ActionEvent> slideAction = (ActionEvent t) {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
should be
EventHandler<ActionEvent> slideAction = (ActionEvent t) -> {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
Note the only addition ->. Which IDE are you using?

Resources