Duration.millis symbol not found? [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 2 years ago.
I'm new to JavaFX, especially the built in API, which is the Timeline
But I wanna add a timer for an event using Timeline
Timeline timeline;
timeline = new Timeline(new KeyFrame(Duration.millis(2500),
(evt) -> {
System.out.println("hello");
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
error: cannot find symbol
Duration.millis(2500),
symbol: method millis(int)
location: class Duration
1 error
This is the full code of it, just wanna test out the timeline thing to create a timer for an event.
In this case, I try to add a simple println "Hello" to see if it works, but it doesn't.
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXPasswordField;
import com.jfoenix.controls.JFXTextField;
import javafx.scene.image.Image;
import java.io.IOException;
import java.net.URL;
import java.time.Duration;
import java.util.ResourceBundle;
import java.util.TimerTask;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.Window;
import javax.swing.*;
public class Scene2Controller implements Initializable {
#FXML
private JFXButton btn_submit;
#FXML
private JFXTextField txt_email;
#FXML
private JFXPasswordField txt_pass;
#FXML
private ImageView img1;
#FXML
private ImageView img2;
#FXML
private Pane pane_loader;
#FXML
private void handleButtonAction(ActionEvent event) throws IOException, Exception {
if (event.getSource() == btn_submit) {
if (txt_email.getText().equals("") && txt_pass.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please fill in the field", "Error", JOptionPane.ERROR_MESSAGE);
}
else
{
pane_loader.setVisible(true);
pane_loader.toFront();
if (txt_email.getText().equals("root") && txt_pass.getText().equals("test1234"))
{
Timeline timeline;
timeline = new Timeline(new KeyFrame(Duration.millis(2500l),
(evt) -> {
System.out.println("hello");
}));
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}
else
JOptionPane.showMessageDialog(null, "Invalid Username or Password", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
Image image = new Image ("/image/business_care_clinic_1282308.jpg");
Image image2 = new Image ("/image/815.gif");
img1.setImage(image);
img2.setImage(image2);
}
}

Huge thanks to #kleopatra and #Pagbo , I just realised that I've imported the wrong class.
my bad.. :)
import java.time.Duration;
to
import javafx.util.Duration;

Related

Issue with Javafx actually opening Gui example

I am having problems with javafx (surprise lol). For some reason my code seems to be running, but the actual gui never shows up on my screen, and it is stuck in the bottom right. When I take out the "implements initializable" in the Sample Controller class, then the gui shows up. I would greatly appreciate any help anyone could give me !!
Thanks
Main Class
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root,400,400);
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);
}
}
Sample Controller Class
package application;
import java.awt.Label;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ListView;
import javafx.scene.control.Alert.AlertType;
import javafx.stage.Popup;
import javafx.stage.Stage;
public class SampleController{
#FXML
private ListView<String>mainListView;
/**
* Initializing the class
*/
public void initialize(URL url, ResourceBundle rb) {
ObservableList<String>thisMainListView = FXCollections.observableArrayList("SPY","QQQ","Rus2000");
mainListView.setItems(thisMainListView);
}
}

Automatic events in JavaFX

Would it be possible to wrap an entire JavaFX application into a while loop to trigger automatic events? For example in a auction house simulator:
package main;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
// Standard JavaFX boilerplate
primaryStage.show();
while(true){
// Get price of this item
// Update table of listings
}
}
public static void main(String[] args) {
launch(args);
}
I know that the loop would block the main thread for the GUI so I was thinking of using the system time + a few seconds in the while loop instead:
double systemTime = systemTime;
double executeTime = systemTime + 5;
while(systemTime != executeTime){
//Do things
executeTime = systemTime + 5;
}
At any rate I know what I need, I just don't know what it's called or implemented.
Well you were right this would most likely block the JavaFX thread, but so would your second statement. As its still looping blocking the thread. What you could do is use
the ScheduledExecutorService to run a Runnable or thread to periodically refresh the gui and update it with what ever information. But you should make sure to wrap the parts which change the GUI within the JavaFX Thread which you can simply do so by using Platform.runLater method. Or for more heavy duty background tasks, use the Task class for JavaFX.
I will use the runLater method for simplicity sakes.
Example:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.lang.management.PlatformManagedObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class Example extends Application {
private Scene myscene;
private TextArea exampleText;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
//JavaFX boilerplate
VBox rootVBox = new VBox();
exampleText = new TextArea();
VBox.setVgrow(exampleText, Priority.ALWAYS);
myscene = new Scene(rootVBox);
rootVBox.getChildren().add(exampleText);
//End of JavaFX boilerplate
// Scheduler to update gui periodically
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
Random r = new Random();
Runnable addNewNumber = () -> {
Platform.runLater(()->{
System.out.println("I Just updated!!!");
String newNumber = Integer.toString(r.nextInt(100));
System.out.println("adding "+ newNumber +" to textfield ");
exampleText.appendText(newNumber+"\n");
});
};
executor.scheduleAtFixedRate(addNewNumber, 0, 500, TimeUnit.MILLISECONDS);
primaryStage.setScene(myscene);
primaryStage.show();
}
}

Java fx Changing the Color of a String

In my Program i have to change the color of a sample string by clicking on the radio Buttons. But i keep getting errors every time i click on them. i keep getting this error. I am also using e(fx)clipse to code this.
Caused by: java.lang.ClassCastException:
javafx.graphics#10.0.2/javafx.scene.paint.Color cannot be cast to
javafx.graphics#10.0.2/javafx.scene.text.Text at
employee.view.MainController.colorRadioButtonSelected(MainController.java:83)
package employee.view;
import javafx.beans.value.ChangeListener;
import javafx.scene.paint.Paint;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
public class MainController {
#FXML
private BorderPane myPane;
#FXML
private RadioButton blackRadioButton;
#FXML
private ToggleGroup colorToggleGroup;
#FXML
private RadioButton redRadioButton;
#FXML
private RadioButton blueRadioButton;
#FXML
private RadioButton greenRadioButton;
#FXML
private ListView<String> mylistView;
#FXML
private CheckBox boldCheckBox;
#FXML
private CheckBox italicCheckBox;
String Text;
Text sample=new Text(50,300,"SAMPLE");
FontWeight weight = FontWeight.NORMAL; // FontWeight.BOLD is boldface
FontPosture posture = FontPosture.REGULAR; // FontPosture.ITALIC is italic
int size=18;
boolean fontBold = false;
boolean fontItalic = false;
public void initialize() {
blackRadioButton.setUserData(Color.BLACK);
redRadioButton.setUserData(Color.RED);
greenRadioButton.setUserData(Color.GREEN);
blueRadioButton.setUserData(Color.BLUE);
myPane.getChildren( ).add( sample );
sample.setFont(Font.font("Verdana", weight, posture, size));
}
#FXML
void boldCheckBoxSelected(ActionEvent event) {
}
#FXML
void colorRadioButtonSelected(ActionEvent event) {
sample= (javafx.scene.text.Text) colorToggleGroup.getSelectedToggle().getUserData();
}
#FXML
void italicCheckBoxSelected(ActionEvent event) {
}
}
You set the data as Color
blackRadioButton.setUserData(Color.BLACK);
redRadioButton.setUserData(Color.RED);
greenRadioButton.setUserData(Color.GREEN);
blueRadioButton.setUserData(Color.BLUE);
But you try to cast it as Text
(javafx.scene.text.Text) colorToggleGroup.getSelectedToggle().getUserData();
To fix this you can use a switch statement or multiple if statements to set sample object depending on which colour is selected. Example if statement:
if ((Color) colorToggleGroup.getSelectedToggle().getUserData() == Color.BLUE) {
sample = new Text(50, 300, "Something");
}
Alternatively you can set the data for the radio buttons as Text, for example:
blueRadioButton.setUserData(new Text(50, 300, "Something"));

Beginner; GUI not appearing?

I'm new to java and coding. I tried searching this problem but could not find a solution.
I was given this code as an example on paper. I tried to recreate it in Eclipse but when I run the code, nothing happens (no gui popup or anything like that). It wouldn't work in jGrasp either. Anyone know what is wrong?
Thanks
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import javafx.scene.media.AudioClip;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
public class AudioShuffle extends Application {
private AudioClip audio1;
private AudioClip audio2;
private AudioClip audio3;
private AudioClip audio4;
private Button play, stop, shuffle;
#Override
public void start(Stage primaryStage) {
String clipURL = "http://www.music.helsinki.fi/tmt/opetus/uusmedia/esim/a2002011001-e02-16kHz.wav";
audio1 = new AudioClip(clipURL);
play=new Button("PLAY");
play.setStyle("-fx-font:20 Arial");
stop=new Button("STOP");
stop.setStyle("-fx-font:20 Arial");
play.setOnAction(this::processButtonPress);
stop.setOnAction(this::processButtonPress);
FlowPane pane = new FlowPane(play, stop);
pane.setAlignment(Pos.CENTER);
pane.setHgap(20);
pane.setStyle("=fx=background=color: cyan");
Scene scene = new Scene(pane, 300,100);
primaryStage.setTitle("Audio Playlist");
primaryStage.setScene(scene);
primaryStage.show();
}
public void processButtonPress(ActionEvent event){
if(event.getSource()==play){
audio1.play();
}
else if(event.getSource()==stop){
audio1.stop();
}
}
public static void main(String[] args){
}
}

java fx imageslideshow using animations

i'm trying to make simple slideshow using java fx. I'm implementing methods which allow me after pressing button to show one image after another until list is over.
For now i have a code like this...it works but it shows images too fast i dont know why.Maybe someone can help me and tell me how can i slow down this timeline variable or timer.thanks in advance:
package pl.gallery.controller;
import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.util.Duration;
import pl.gallery.model.ImageParser;
public class MainPaneController implements Initializable {
#FXML
private BorderPane borderPane;
#FXML
private Button nextButton;
#FXML
private MenuBar menuBar;
#FXML
private AnchorPane anchorPaneTop;
#FXML
private HBox hBox;
#FXML
private Button previousButton;
#FXML
private MenuItem openFolder;
#FXML
private AnchorPane anchorPaneCenter;
#FXML
private ImageView imageView;
#FXML
private Button slideShowButton;
#FXML
private Menu menu;
private Image image;
private ImageParser parser;
private ObservableList<Image> imagesList;
private int indexPrev = 0;
private int indexNext = 0;
private Timeline timeline;
private AnimationTimer timer;
//variable for storing actual frame
private Integer i=0;
#Override
public void initialize(URL location, ResourceBundle resources)
throws IndexOutOfBoundsException {
parser = new ImageParser();
imagesList = FXCollections.observableArrayList();
DirectoryChooser dc = new DirectoryChooser();
openFolder.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
/*
* parser = new ImageParser(); imagesList = new
* ArrayList<Image>(); DirectoryChooser dc = new
* DirectoryChooser(); File dir = dc.showDialog(new Stage());
* parser.createFileList(dir);
*
*
* imagesList.add(new Image(parser.getFilesList().get(0)
* .toURI().toString())); imageView.setImage(imagesList.get(0));
*/
File dir = dc.showDialog(new Stage());
imagesList = parser.createImagesListFromFileList(dir);
imageView.setImage(imagesList.get(0));
}
});
slideShowButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
Duration duration = new Duration(1000);
timeline.setDelay(duration);
timer = new AnimationTimer() {
#Override
public void handle(long l) {
imageView.setImage(imagesList.get(i));
i++;
}
};
timeline.play();
timer.start();
}
});
}
}

Categories

Resources