Add two add & subtract EventHandler's for multiple buttons - java

I'm trying to implement an EventHandler for a "store" type application that will allow the user to add or remove items from a cart, then display the remaining balance of a user-entered budget on the side. However, I am having issues with how to handle this. My professor told me to use the getSource() method but I'm unsure of how to implement that here in my code for what I specifically need it to do. My professor also told me I could use an Array List for the buttons but I'm awful at Array List's so if there's a way around that, that would be great.
`
import javafx.application.Application;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Label;
import javafx.geometry.Insets;
import java.util.Scanner;
public class ShoppingCart extends Application {
Image shirt = new Image("file:shirt.jpg");
Image jacket = new Image("file:jacket.jpg");
Image pants = new Image("file:pants.jpg");
Image shorts = new Image("file:shorts.jpg");
Image shoes = new Image("file:shoes.jpg");
Image socks = new Image("file:socks.jpg");
Image hat = new Image("file:hat.jpg");
Image gloves = new Image("file:gloves.jpg");
ImageView shirtView = new ImageView(shirt);
ImageView jacketView = new ImageView(jacket);
ImageView pantsView = new ImageView(pants);
ImageView shortsView = new ImageView(shorts);
ImageView shoesView = new ImageView(shoes);
ImageView socksView = new ImageView(socks);
ImageView hatView = new ImageView(hat);
ImageView glovesView = new ImageView(gloves);
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
shirtView.setPreserveRatio(true);
shirtView.setFitHeight(200);
jacketView.setPreserveRatio(true);
jacketView.setFitHeight(200);
pantsView.setPreserveRatio(true);
pantsView.setFitHeight(200);
shortsView.setPreserveRatio(true);
shortsView.setFitHeight(200);
shoesView.setPreserveRatio(true);
shoesView.setFitHeight(200);
socksView.setPreserveRatio(true);
socksView.setFitHeight(200);
hatView.setPreserveRatio(true);
hatView.setFitHeight(200);
glovesView.setPreserveRatio(true);
glovesView.setFitHeight(200);
Label shirtPrice = new Label("$12");
Label jacketPrice = new Label("$20");
Label pantsPrice = new Label("$15");
Label shortsPrice = new Label("$15");
Label shoesPrice = new Label("$30");
Label socksPrice = new Label("$5");
Label hatPrice = new Label("$10");
Label glovesPrice = new Label("$8");
int shirtCost = 12;
int jacketCost = 20;
int pantsCost = 15;
int shortsCost = 15;
int shoesCost = 30;
int socksCost = 5;
int hatCost = 10;
int glovesCost = 8;
Scanner custBudget = new Scanner(System.in);
TextField budget = new TextField("Please enter your budget...");
int scBudget = custBudget.nextInt();
Label budgetLabel = new Label();
budgetLabel.setText(String.valueOf(scBudget));
GridPane gridPane = new GridPane();
gridPane.add(shirtView, 0,0);
gridPane.add(jacketView, 0, 1);
gridPane.add(pantsView, 0, 2);
gridPane.add(shortsView, 0, 3);
gridPane.add(shoesView, 1, 0);
gridPane.add(socksView, 1, 1);
gridPane.add(hatView, 1, 2);
gridPane.add(glovesView, 1, 3);
Button addButton = new Button("Add To Cart");
addButton.setOnAction(new AddToCart());
Button removeButton = new Button("Remove From Cart");
removeButton.setOnAction(new RemoveFromCart());
HBox cartButtons = new HBox(20, addButton, removeButton);
VBox shirtItem = new VBox(shirtView, shirtPrice, cartButtons);
VBox jacketItem = new VBox(jacketView, jacketPrice, cartButtons);
VBox pantsItem = new VBox(pantsView, pantsPrice, cartButtons);
VBox shortsItem = new VBox(shortsView, shortsPrice, cartButtons);
VBox shoesItem = new VBox(shoesView, shoesPrice, cartButtons);
VBox socksItem = new VBox(socksView, socksPrice, cartButtons);
VBox hatItem = new VBox(hatView, hatPrice, cartButtons);
VBox glovesItem = new VBox(glovesView, glovesPrice, cartButtons);
HBox row1 = new HBox(20, shirtItem, jacketItem, pantsItem, shortsItem, budgetLabel);
HBox row2 = new HBox(20, shoesItem, socksItem, hatItem, glovesItem);
VBox rows = new VBox(20, row1, row2, budget);
gridPane.setAlignment(Pos.CENTER);
gridPane.setHgap(20);
gridPane.setVgap(20);
gridPane.setPadding(new Insets(10,10,10,10));
Scene scene = new Scene(gridPane, 1200, 800);
primaryStage.setScene(scene);
primaryStage.setTitle("Clothes Shopping");
primaryStage.show();
}
public class AddToCart implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent event) {
if (event.getSource() == addButton) {
}
}
}
public class RemoveFromCart implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent event) {
}
}
}
`

Related

How to use a Label from another class in Java (JavaFX)

I need to use a Label that was created in another class in my JavaFx application
This is my code:
Main Class
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class Main extends Application {
Stage window;
Scene scene1, scene2, scene3;
private Scanner x;
#Override
public void start(Stage primaryStage) throws Exception {
readTutor r = new readTutor();
window = primaryStage;
window.setTitle("Tutor Finder");
Label labelA1 = new Label("Welcome to the best online tutor\nproviding service in the world");
Button buttonA2 = new Button("Find a tutor!");
Button buttonA1 = new Button("Become a tutor!");
Button buttonB1 = new Button("Click here to go back");
Button buttonB2 = new Button("Submit");
Button buttonC1 = new Button("Click here to go back");
buttonB1.setOnAction(e -> window.setScene(scene1));
buttonC1.setOnAction(e -> window.setScene(scene1));
buttonA1.setOnAction(e -> window.setScene(scene2));
buttonA2.setOnAction(e -> window.setScene(scene3));
Label labelB1 = new Label("First Name:");
TextField textB1 = new TextField();
Label labelB2 = new Label("Last Name:");
TextField textB2 = new TextField();
Label labelB3 = new Label("Subject:");
TextField textB3 = new TextField();
Label labelB4 = new Label("Age:");
TextField textB4 = new TextField();
Label labelB5 = new Label("Contact No#:");
TextField textB5 = new TextField();
Label labelB6 = new Label("Country: ");
TextField textB6 = new TextField();
VBox layout = new VBox(20);
layout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(labelA1, buttonA1, buttonA2);
scene1 = new Scene(layout, 300, 300);
VBox layout2 = new VBox(20);
layout2.getChildren().addAll(labelB1, textB1, labelB2, textB2, labelB3,
textB3, labelB4, textB4, labelB5, textB5, labelB6, textB6, buttonB2, buttonB1);
buttonB2.setOnAction(l -> {
try {
BufferedWriter bw = new BufferedWriter(
new FileWriter("C:\\Users\\Salman\\Desktop\\Tutor Details\\output.txt", true));
bw.write(textB1.getText()+" ");
bw.write(textB2.getText()+" ");
bw.write(textB3.getText()+" ");
bw.write(textB4.getText()+" ");
bw.write(textB5.getText()+" ");
bw.write(textB6.getText()+" \n");
bw.close();
textB1.clear();
textB2.clear();
textB3.clear();
textB4.clear();
textB5.clear();
textB6.clear();
} catch (Exception e) {
return;
}
r.openFile();
r.readFile();
r.closeFile();
});
scene2 = new Scene(layout2, 400, 600);
VBox layout3 = new VBox(20);
layout3.setAlignment(Pos.CENTER);
layout3.getChildren().addAll(buttonC1);
scene3 = new Scene(layout3, 300, 300);
window.setScene(scene1);
window.show();
}
public static void main (String[]args){
launch(args);
}
}
readTutor Class
import javafx.scene.control.Label;
import java.io.*;
import java.util.*;
public class readTutor {
private Scanner x;
public Label tutorLabel;
public void openFile(){
try {
x = new Scanner(new File("C:\\Users\\Salman\\Desktop\\Tutor Details\\output.txt"));
}
catch(Exception e){
System.out.println("couldn't find file");
}
}
public void readFile(){
while(x.hasNext()){
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String e = x.next();
String f = x.next();
System.out.printf("%s %s %s %s %s %s\n", a, b, c, d, e, f);
tutorLabel = new Label(a+b+c+d+e+f);
}
}
public void closeFile(){
x.close();
}
}
What I want is to use the Label created in the readFile method in the readTutor Class, in scene3 and display that label there. But I can't figure out how to use that label from the Main class.
You should make an Object to store you're data or pass them to the target location.
There is much that is very, very wrong about the structure of code in the question. Mostly that it does all kinds of file handling and I/O on the FXAT, which will cause havoc with the GUI if there is any kind of lag with those operations.
Also, the idea of having a file handling helper class with a JavaFX screen Node in it is really not a good design. #Kleopatra's comment about using a data model is totally on point.
But in the spirit of answering the question about exposing the layout of a screen to other classes which have a legitimate reason to access it, I've made the required changes to the code so that it should work.
First, I've added a TextField and Label to the Main screen to show the results from the readTutor class. Then I've passed the TextField to readTutor in it's constructor:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class LabelPasser extends Application {
Stage window;
Scene scene1, scene2, scene3;
private Scanner x;
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Tutor Finder");
Label labelA1 = new Label("Welcome to the best online tutor\nproviding service in the world");
Button buttonA2 = new Button("Find a tutor!");
Button buttonA1 = new Button("Become a tutor!");
Button buttonB1 = new Button("Click here to go back");
Button buttonB2 = new Button("Submit");
Button buttonC1 = new Button("Click here to go back");
buttonB1.setOnAction(e -> window.setScene(scene1));
buttonC1.setOnAction(e -> window.setScene(scene1));
buttonA1.setOnAction(e -> window.setScene(scene2));
buttonA2.setOnAction(e -> window.setScene(scene3));
Label labelB1 = new Label("First Name:");
TextField textB1 = new TextField();
Label labelB2 = new Label("Last Name:");
TextField textB2 = new TextField();
Label labelB3 = new Label("Subject:");
TextField textB3 = new TextField();
Label labelB4 = new Label("Age:");
TextField textB4 = new TextField();
Label labelB5 = new Label("Contact No#:");
TextField textB5 = new TextField();
Label labelB6 = new Label("Country: ");
TextField textB6 = new TextField();
Label labelTutor = new Label("Tutor: ");
TextField tutorTF = new TextField();
VBox layout = new VBox(20);
layout.setAlignment(Pos.CENTER);
layout.getChildren().addAll(labelA1, buttonA1, buttonA2);
readTutor r = new readTutor(tutorTF);
scene1 = new Scene(layout, 300, 300);
VBox layout2 = new VBox(20);
layout2.getChildren()
.addAll(labelB1,
textB1,
labelB2,
textB2,
labelB3,
textB3,
labelB4,
textB4,
labelB5,
textB5,
labelB6,
textB6,
labelTutor,
tutorTF,
buttonB2,
buttonB1);
buttonB2.setOnAction(l -> {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Salman\\Desktop\\Tutor Details\\output.txt", true));
bw.write(textB1.getText() + " ");
bw.write(textB2.getText() + " ");
bw.write(textB3.getText() + " ");
bw.write(textB4.getText() + " ");
bw.write(textB5.getText() + " ");
bw.write(textB6.getText() + " \n");
bw.close();
textB1.clear();
textB2.clear();
textB3.clear();
textB4.clear();
textB5.clear();
textB6.clear();
} catch (Exception e) {
return;
}
r.openFile();
r.readFile();
});
scene2 = new Scene(layout2, 400, 600);
VBox layout3 = new VBox(20);
layout3.setAlignment(Pos.CENTER);
layout3.getChildren().addAll(buttonC1);
scene3 = new Scene(layout3, 300, 300);
window.setScene(scene1);
window.show();
}
public static void main(String[] args) {
launch(args);
}
}
Then I've modified readTutor such that it no longer creates a Label, but instead updates the Text property of the TextField that it received in its constructor:
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import java.io.File;
import java.util.Scanner;
public class readTutor {
private Scanner x;
public Label tutorLabel;
TextField tutorTF;
public readTutor(TextField tutorTF) {
this.tutorTF = tutorTF;
}
public void openFile() {
try {
x = new Scanner(new File("C:\\Users\\Salman\\Desktop\\Tutor Details\\output.txt"));
} catch (Exception e) {
System.out.println("couldn't find file");
}
}
public void readFile() {
while (x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String e = x.next();
String f = x.next();
System.out.printf("%s %s %s %s %s %s\n", a, b, c, d, e, f);
tutorTF.setText(a + b + c + d + e + f);
}
}
}
It turns out that if you program the file handling the way you should, with a Task, then most of the issues about the label passing become moot. I've cleaned up the code a bit to make it easier to read, then split the file handling out into a Task:
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Scanner;
public class LabelPasser extends Application {
Stage window;
Scene scene1, scene2, scene3;
private Scanner x;
private TextField textB1 = new TextField();
private TextField textB2 = new TextField();
private TextField textB3 = new TextField();
private TextField textB4 = new TextField();
private TextField textB5 = new TextField();
private TextField textB6 = new TextField();
private TextField tutorTF = new TextField();
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Tutor Finder");
Button buttonA2 = new Button("Find a tutor!");
Button buttonA1 = new Button("Become a tutor!");
Button buttonB1 = new Button("Click here to go back");
Button buttonB2 = new Button("Submit");
Button buttonC1 = new Button("Click here to go back");
buttonB1.setOnAction(e -> window.setScene(scene1));
buttonC1.setOnAction(e -> window.setScene(scene1));
buttonA1.setOnAction(e -> window.setScene(scene2));
buttonA2.setOnAction(e -> window.setScene(scene3));
VBox layout = new VBox(20, new Label("Welcome to the best online tutor\nproviding service in the world"), buttonA1, buttonA2);
layout.setAlignment(Pos.CENTER);
scene1 = new Scene(layout, 300, 300);
VBox layout2 = new VBox(20);
layout2.getChildren()
.addAll(new Label("First Name:"),
textB1,
new Label("Last Name:"),
textB2,
new Label("Subject:"),
textB3,
new Label("Age:"),
textB4,
new Label("Contact No#:"),
textB5,
new Label("Country: "),
textB6,
new Label("Tutor: "),
tutorTF,
buttonB2,
buttonB1);
buttonB2.setOnAction(evt -> buttonAction());
scene2 = new Scene(layout2, 400, 600);
VBox layout3 = new VBox(20);
layout3.setAlignment(Pos.CENTER);
layout3.getChildren().addAll(buttonC1);
scene3 = new Scene(layout3, 300, 300);
window.setScene(scene1);
window.show();
}
private void buttonAction() {
Task<String> fileTask = new Task<String>() {
#Override
protected String call() throws Exception {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Salman\\Desktop\\Tutor Details\\output.txt", true));
bw.write(textB1.getText() + " ");
bw.write(textB2.getText() + " ");
bw.write(textB3.getText() + " ");
bw.write(textB4.getText() + " ");
bw.write(textB5.getText() + " ");
bw.write(textB6.getText() + " \n");
bw.close();
textB1.clear();
textB2.clear();
textB3.clear();
textB4.clear();
textB5.clear();
textB6.clear();
} catch (Exception e) {
return "";
}
ReadTutor readTutor = new ReadTutor();
readTutor.openFile();
return readTutor.readFile();
}
};
fileTask.setOnSucceeded(evt -> tutorTF.setText(fileTask.getValue()));
Thread fileThread = new Thread(fileTask);
fileThread.start();
}
public static void main(String[] args) {
launch(args);
}
}
The readFile() method in ReadTutor was strange, and it looked like it was trying to create Labels in a loop, so the file reading is weird. I modified it just so that it would compile:
import java.io.File;
import java.util.Scanner;
public class ReadTutor {
private Scanner x;
public void openFile() {
try {
x = new Scanner(new File("C:\\Users\\Salman\\Desktop\\Tutor Details\\output.txt"));
} catch (Exception e) {
System.out.println("couldn't find file");
}
}
public String readFile() {
String results = "";
while (x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String e = x.next();
String f = x.next();
System.out.printf("%s %s %s %s %s %s\n", a, b, c, d, e, f);
results = a + b + c + d + e + f;
}
return results;
}
}
So now you can see that ReadTutor is just a file handler, and it returns a plain old Java String as a result and doesn't know anything about JavaFX at all. The Task handles the activity on a background thread and returns the String value from the read operation. When the Task completes, it will trigger the OnSucceeded event, which will update the value in the tutorTF TextField on the FXAT.

Compilation probs Java Dialog Box

I am tasked with creating a DVD Collection application that displays Three columns and five row of stuff. I have written the code for this to work but keep on getting compilation errors( CANNOT FIND SYMBOL ==> class DVDColletionApp ) that I am having a hard time debugging.
Below is the code in question. Assistance would be greatly appreciated.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
public class DVDCollectionApp extends Application {
private DVDCollection model;
private ListView<String> tList;
private ListView<Integer> yList, lList;
public DVDCollectionApp() {
model = DVDCollection.example1();
}
public void start(Stage primaryStage) {
BorderPane borderPane = new BorderPane();
// Create the labels
HBox labelPane = new HBox();
labelPane.setPadding(new Insets(0,0,0,10));
labelPane.setSpacing(10);
Label label1 = new Label("Title");
label1.setMinSize(300,30);
label1.setPrefSize(2000,30);
Label label2 = new Label("Year");
label2.setMinSize(60,30);
label2.setPrefSize(60,30);
Label label3 = new Label("Length");
label3.setMinSize(60,30);
label3.setPrefSize(60,30);
labelPane.getChildren().addAll(label1, label2, label3);
borderPane.setTop(labelPane);
// Create the lists
GridPane listPane = new GridPane();
listPane.setPadding(new Insets(10));
listPane.setHgap(10);
tList = new ListView<String>();
listPane.add(tList, 0, 0);
tList.setMinSize(300,60);
tList.setPrefSize(2000,2000);
yList = new ListView<Integer>();
listPane.add(yList, 1, 0);
yList.setMinSize(60,60);
yList.setPrefSize(60,500);
lList = new ListView<Integer>();
listPane.add(lList, 2, 0);
lList.setMinSize(60,60);
lList.setPrefSize(60,500);
borderPane.setCenter(listPane);
// Create the button pane
HBox buttonPane = new HBox();
buttonPane.setPadding(new Insets(10));
buttonPane.setSpacing(10);
Button addButton = new Button("Add");
addButton.setStyle("-fx-font: 12 arial; -fx-base: rgb(0,100,0); -fx-text-fill: rgb(255,255,255);");
addButton.setPrefSize(90,30);
Button deleteButton = new Button("Delete");
deleteButton.setStyle("-fx-font: 12 arial; -fx-base: rgb(200,0,0); -fx-text-fill: rgb(255,255,255);");
deleteButton.setPrefSize(90,30);
Button statsButton = new Button("Stats");
statsButton.setStyle("-fx-font: 12 arial;");
statsButton.setPrefSize(90,30);
buttonPane.getChildren().addAll(addButton, deleteButton, statsButton);
borderPane.setBottom(buttonPane);
addButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent actionEvent) {
String title = javax.swing.JOptionPane.showInputDialog("Please enter the DVD Title: ");
String year = javax.swing.JOptionPane.showInputDialog("Please enter the DVD Year: ");
String length = javax.swing.JOptionPane.showInputDialog("Please enter the DVD Duration: ");
if ((title != null) && (year != null) && (length != null) && (title.length() > 0) && (year.length() > 0) && (length.length() > 0)) {
DVD d = new DVD(title, Integer.parseInt(year), Integer.parseInt(length));
model.add(d);
update(model, -1);
}
}
});
deleteButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent actionEvent) {
if (tList.getSelectionModel().getSelectedItem() != null) {
model.remove(tList.getSelectionModel().getSelectedItem());
update(model, -1);
}
}
});
tList.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
model.setSelectedDVD(tList.getSelectionModel().getSelectedIndex());
update(model, tList.getSelectionModel().getSelectedIndex());
}
});
yList.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
model.setSelectedDVD(yList.getSelectionModel().getSelectedIndex());
update(model, yList.getSelectionModel().getSelectedIndex());
}
});
lList.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
model.setSelectedDVD(lList.getSelectionModel().getSelectedIndex());
update(model, lList.getSelectionModel().getSelectedIndex());
}
});
// Populate the lists
DVD[] theList = model.getDVDList();
String[] titles = new String[theList.length];
Integer[] years = new Integer[theList.length];
Integer[] lengths = new Integer[theList.length];
for (int i=0; i<theList.length; i++) {
titles[i] = theList[i].getTitle();
years[i] = theList[i].getYear();
lengths[i] = theList[i].getDuration();
}
tList.setItems(FXCollections.observableArrayList(titles));
yList.setItems(FXCollections.observableArrayList(years));
lList.setItems(FXCollections.observableArrayList(lengths));
primaryStage.setTitle("My DVD Collection");
primaryStage.setScene(new Scene(borderPane, 600, 300));
primaryStage.show();
}
// Update the view to reflect the model
public void update(DVDCollection model, int selectedDVD) {
DVD[] theList = model.getDVDList();
String[] titles = new String[theList.length];
Integer[] years = new Integer[theList.length];
Integer[] lengths = new Integer[theList.length];
for (int i=0; i<theList.length; i++) {
titles[i] = theList[i].getTitle();
years[i] = theList[i].getYear();
lengths[i] = theList[i].getDuration();
}
tList.setItems(FXCollections.observableArrayList(titles));
yList.setItems(FXCollections.observableArrayList(years));
lList.setItems(FXCollections.observableArrayList(lengths));
tList.getSelectionModel().select(selectedDVD);
yList.getSelectionModel().select(selectedDVD);
lList.getSelectionModel().select(selectedDVD);
}
public static void main(String[] args) {
launch(args);
}
}
Have you checked that java files are being compiled correctly?
The class DVDCollection doesn't seem to be imported, the DVDCollectionApp class must be in a .java of the same name and if you're using an IDE be sure to do a clean&build.

Why is the slider for this Java program is not working?

This is a fan program where use a slider to increase and decrease the speed of the fan. I do not need the increase and decrease button, I only have them as a guide to help the slider figure out what happens when you scroll left or right. I will delete those later. My slider is not showing and I can't test it out. Where did I go wrong here?
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
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;
import javafx.scene.control.Slider;
public class module2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
// Create fan pane
FanPane fanPane = new FanPane(100);
Slider mSlider = new Slider();
HBox scrollPane = new HBox(mSlider);
KeyFrame keyFrame = new KeyFrame(Duration.millis(10), e-> fanPane.spin());
Timeline fanTimeline = new Timeline(keyFrame);
fanTimeline.setCycleCount(Timeline.INDEFINITE);
// Buttons pause, resume, increase, decrease, reverse
Button pause = new Button("Pause");
pause.setOnAction(e-> fanTimeline.pause());
Button resume = new Button("Resume");
resume.setOnAction(e-> fanTimeline.play());
//fanPane.increase()
Button increase = new Button("Increase");
increase.setOnAction(e -> {
fanTimeline.setRate(fanTimeline.getCurrentRate() + 1);
mSlider.setValue(fanTimeline.getCurrentRate());
});
Button decrease = new Button("Decrease");
decrease.setOnAction(e -> {
fanTimeline.setRate(
(fanTimeline.getCurrentRate() - 1 < 0) ? 0 : fanTimeline.getCurrentRate() - 1);
mSlider.setValue(fanTimeline.getCurrentRate());
});
Button reverse = new Button("Reverse");
reverse.setOnAction(e-> fanPane.increment *= -1);
HBox hButtons = new HBox(pause,resume,reverse);
hButtons.setSpacing(10);
hButtons.setAlignment(Pos.CENTER);
hButtons.setPadding(new Insets(10, 10, 10, 10));
BorderPane borderPane = new BorderPane(fanPane, null, null, hButtons, null);
primaryStage.setScene(new Scene(borderPane));
primaryStage.setTitle("Spinning fan");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
private class FanPane extends Pane {
private Circle c;
private Arc[] blades = new Arc[4];
private double increment = 1;
Slider mSlider = new Slider();
HBox scrollPane = new HBox(mSlider);
FanPane(double radius) {
setMinHeight(400);
setMinWidth(400);
c = new Circle(200,200,radius,Color.BLUE);
c.setStroke(Color.BLACK);
double bladeRadius = radius * 0.9;
for (int i = 0; i < blades.length; i++) {
blades[i] = new Arc(
c.getCenterX(), c.getCenterY(), // center point
bladeRadius, bladeRadius, // X and Y radius
(i * 90) + 30, 35); // start angle and length
blades[i].setFill(Color.YELLOW);
blades[i].setType(ArcType.ROUND);
}
getChildren().addAll(c);
getChildren().addAll(blades);
}
private void spin() {
for (Arc blade : blades) {
double prevStartAngle = blade.getStartAngle();
blade.setStartAngle(prevStartAngle + increment);
}
}
}
}

JavaFX - Large amount of Data in ScrollPane freezes UI

What i need to do?
I need to display a lot of Data.
1 GridPane exists of ~25 Labels. There need to be 100-500 of those GridPanes to be shown.
How did i do it?
I used a ScrollPane for it.
So there are many GridPanes in a VBox which is placed into a ScrollPane.
I generate the GridPanes in an extra Thread and just set the Content of the ScrollPane in the JavaFX-Thread.
Some of those Labels are modified Labels so they are copyable or Links.
What happens?
The UI freezes for some seconds bevor the data is displayed.
Question1: Is there some modification i can make to prevent the UI from freezing?
Question2: Are there other Components better suited to display such Data?
ExampleCode:
package samples.longload;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Longload extends Application
{
private final Button runButton = new Button("Run");
private final Label label = new Label();
final ScrollPane sp = new ScrollPane();
final VBox vb = new VBox();
private final Service service = new Service()
{
#Override
protected Task createTask()
{
return new Task<Void>()
{
#Override
protected Void call() throws Exception
{
final List<Node> nodeList = new ArrayList<Node>();
for (int i = 0; i < 500; i++)
{
final GridPane grid = defineGrid();
nodeList.add(grid);
}
vb.getChildren().addAll(nodeList);
Platform.runLater(new Runnable()
{
#Override
public void run()
{
sp.setContent(vb);
}
});
return null;
}
};
}
};
#Override
public void start(final Stage stage)
{
final VBox layout = createLayout();
final Scene scene = new Scene(layout, 1500, 1000);
stage.setScene(scene);
bindUIandService(stage);
stage.show();
}
private void bindUIandService(final Stage stage)
{
label.textProperty()
.bind(service.stateProperty().asString()
);
stage.getScene()
.getRoot()
.cursorProperty()
.bind(
Bindings
.when(service.runningProperty())
.then(Cursor.WAIT)
.otherwise(Cursor.DEFAULT)
);
runButton
.disableProperty()
.bind(
service.runningProperty()
);
runButton.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(final ActionEvent event)
{
service.restart();
}
});
}
private VBox createLayout()
{
final VBox layout = new VBox(10);
sp.setPrefSize(300, 500);
sp.setVmax(440);
sp.setContent(new ProgressIndicator());
layout.getChildren().setAll(runButton, label, sp);
layout.setPadding(new Insets(10));
layout.setAlignment(Pos.CENTER);
return layout;
}
public static void main(final String[] args)
{
launch(args);
}
private LinkedHashMap<Node, Node> createContentMap()
{
final LinkedHashMap<Node, Node> contentMap = new LinkedHashMap<Node, Node>();
// ID-KONSEH
contentMap.put(new Label("1"), new Label("1", null));
// ID-DOKUMENT
contentMap.put(new Label("2"), new Label("2"));
// DISCRIMINATOR
contentMap.put(new Label("3"), new Label("3"));
// AKT
contentMap.put(new Label("4"), new Label("4"));
// FASSUNGSNR
contentMap.put(new Label("5"), new Label("5"));
// KORREKTURNR
contentMap.put(new Label("6"), new Label("6"));
// STATUS
contentMap.put(new Label("7"), new Label("7"));
// NEUZUGANG
contentMap.put(new Label("8"), new Label("8"));
// NEUZDAT
contentMap.put(new Label("9"), new Label("9"));
// APPDATVON
contentMap.put(new Label("10"), new Label("10"));
// APPDATBIS
contentMap.put(new Label("11"), new Label("11"));
// BEZUGVON
contentMap.put(new Label("12"), new Label("12"));
// BEZUGBIS
contentMap.put(new Label("13"), new Label("13"));
// INKRAFTVON
contentMap.put(new Label("14"), new Label("14"));
// INKRAFTBIS
contentMap.put(new Label("15"), new Label("15"));
// APPROBANT
contentMap.put(new Label("16"), new Label("16"));
// SACHBEARBEITER
contentMap.put(new Label("17"), new Label("17"));
// KURZTEXT
contentMap.put(new Label("18"), new Label("18"));
// PERSANMERKUNG
contentMap.put(new Label("19"), new Label("19"));
// LASTCHANGEDAT
contentMap.put(new Label("20"), new Label("20"));
// WIEDERVORLAGE_DATUM
contentMap.put(new Label("21"), new Label("21"));
// TEMP_GID
contentMap.put(new Label("22"), new Label("22"));
// DOK_MULTIFASSUNG
contentMap.put(new Label("23"), new Label("23"));
// ABGEFERTIGT_VON
contentMap.put(new Label("24"), new Label("24"));
// KORRIGIERT_VON
contentMap.put(new Label("25"), new Label("25"));
return contentMap;
}
public GridPane defineGrid()
{
final GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10)); // top, right, bottom, left
grid.setHgap(10); // horizontaler Abstand
grid.setVgap(10); // vertikaler Abstand
final int columnWidthDescription = 150; // breite der Beschreibungs-Spalten
final int columnWidthContent = 250; // breite der Inhalts-Spalten
final ColumnConstraints columnDescription1 = new ColumnConstraints(columnWidthDescription, columnWidthDescription, columnWidthDescription);
final ColumnConstraints columnContent1 = new ColumnConstraints(columnWidthContent, columnWidthContent, columnWidthContent);
final ColumnConstraints columnDescription2 = new ColumnConstraints(columnWidthDescription, columnWidthDescription, columnWidthDescription);
final ColumnConstraints columnContent2 = new ColumnConstraints(columnWidthContent, columnWidthContent, columnWidthContent);
final ColumnConstraints columnDescription3 = new ColumnConstraints(columnWidthDescription, columnWidthDescription, columnWidthDescription);
final ColumnConstraints columnContent3 = new ColumnConstraints(columnWidthContent, columnWidthContent, columnWidthContent);
grid.getColumnConstraints().addAll(columnDescription1, columnContent1, columnDescription2, columnContent2, columnDescription3,
columnContent3);
final LinkedHashMap<Node, Node> contentMap = createContentMap();
int column = 0;
int row = 1;
for (final Node desc : contentMap.keySet())
{
final Node content = contentMap.get(desc);
if (row > contentMap.size() / 3)
{
column = column + 2;
row = 1;
}
grid.add(desc, column, row);
grid.add(content, column + 1, row);
row++;
}
return grid;
}
}
This is how it should look like in the end:

Intersect of ImageView's in JavaFX

Why these statements does not work?
if (iv_ship.intersects(iv_plane.getBoundsInLocal())) System.out.println("xxxxxxxxx");
if (iv_plane.intersects(iv_ship.getBoundsInLocal())) System.out.println("zzzz");
if (iv_plane.getBoundsInLocal().intersects(iv_ship.getBoundsInLocal())) System.out.println("dupa");
I am pretty sure these two objects intersect. Maybe it is fault of TranslateTransition?
But i was also trying to intersect Rectangles in coast, which are not TT.
Best regards.
Here is all the code:
package riverpuff.v3;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javafx.animation.AnimationTimer;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* #author Marek
*/
public class RiverPuffV3 extends Application {
public String name = "";
public Rectangle shot = new Rectangle();
#Override
public void start(Stage primaryStage) {
createMenu(primaryStage);
primaryStage.show();
primaryStage.setResizable(false);
primaryStage.getIcons().
add(new Image(getClass().getResourceAsStream("Icon.png")));
}
private void createMenu(Stage primaryStage) {
primaryStage.setScene(null);
GridPane pane_menu = new GridPane();
Button button_name = new Button("Name");
button_name.setMaxHeight(Double.MAX_VALUE);
button_name.setMaxWidth(Double.MAX_VALUE);
button_name.setOnAction(e -> {
createName(primaryStage);
/*try{
OutputStreamWriter writer = new OutputStreamWriter( new FileOutputStream("log.txt", true), "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.newLine();
fbw.write("append txt...");
fbw.newLine();
fbw.close();
}
catch (Exception v) {
System.out.println("Error: " + v.getMessage());
}*/
});
Button button_start = new Button("Start");
button_start.setMaxHeight(Double.MAX_VALUE);
button_start.setMaxWidth(Double.MAX_VALUE);
button_start.setOnAction(e -> {
drawGame(primaryStage);
});
pane_menu.setHgap(10);
pane_menu.setVgap(10);
pane_menu.add(button_name,0,10,10,10);
pane_menu.add(button_start,15,10,10,10);
//reading name from a file
try {
String read_file = null;
BufferedReader in = new BufferedReader(new FileReader("log.txt"));
read_file = in.readLine();
Text text_name = new Text("Hello " + read_file);
pane_menu.add(text_name,5,5,10,5);
} catch (FileNotFoundException e) {
System.out.println("File not found!");
//throw new RuntimeException("File not found");
} catch (IOException e) {
System.out.println("IO Error occured");
//throw new RuntimeException("IO Error occured");
}
Scene scene_menu = new Scene(pane_menu, 300, 500);
primaryStage.setTitle("River Puff");
primaryStage.setScene(scene_menu);
}
//save name to a file
private void createName (Stage primaryStage) {
primaryStage.setScene(null);
GridPane pane_name = new GridPane();
TextField tf_name = new TextField();
tf_name.setMaxHeight(50);
tf_name.setMaxWidth(240);
tf_name.setAlignment(Pos.CENTER);
tf_name.setFont(Font.font("Verdana",25));
tf_name.setOnKeyPressed(ke -> {
if (ke.getCode() == KeyCode.ENTER) {
name = tf_name.getText();
if (!name.isEmpty()){
MyFile myFile = new MyFile();
myFile.writeTextFile("log.txt", name);
}
createMenu(primaryStage);
}
});
Button button_ok = new Button("OK");
button_ok.setMaxHeight(30);
button_ok.setMaxWidth(80);
button_ok.setOnAction(e -> {
name = tf_name.getText();
if (!name.isEmpty()){
MyFile myFile = new MyFile();
myFile.writeTextFile("log.txt", name);
}
createMenu(primaryStage);
});
Text text_name = new Text("What is your name?");
text_name.setFont(Font.font("Verdana",15));
pane_name.setHgap(10);
pane_name.setVgap(10);
pane_name.add(text_name,8,9,5,5);
pane_name.add(button_ok,11,22,8,3);
pane_name.add(tf_name,3,15,24,5);
Scene scene_name = new Scene(pane_name, 300, 500);
primaryStage.setTitle("River Puff - Name");
primaryStage.setScene(scene_name);
}
private void drawGame (Stage primaryStage) {
primaryStage.setScene(null);
final int H = 700;
final int W = 1000;
Group root = new Group();
Scene scene_game = new Scene(root, W, H, Color.LIGHTBLUE);
Button button_menu = new Button("Menu");
button_menu.setOnAction(e ->{
createMenu(primaryStage);
});
Image ship = new Image((getClass().getResourceAsStream("ship.png"))); //loading images
Image plane = new Image((getClass().getResourceAsStream("Icon.png")));
/**********************************************************************/
Rectangle[] coastL = {
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle()
};
Rectangle[] coastR = {
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle(),
new Rectangle(), new Rectangle()
};
for (int i=0; i<8; i++) {
coastL[i].setFill(Color.FORESTGREEN);
coastL[i].setHeight(100);
coastR[i].setFill(Color.FORESTGREEN);
coastR[i].setHeight(100);
}
AnimationTimer timer = new AnimationTimer() {
int[] j = {0,0,0,0,0,0,0,0};
#Override
public void handle(long now) {
for (int i=0; i<8; i++) if (j[i]==(i*100+800)) j[i]=i*100;
for (int i=1;i<9;i++) { //creating coast
coastL[i-1].setX(0);
coastL[i-1].setY(j[i-1]-(i*100));
coastL[i-1].setWidth(250+i*(i%3));
coastR[i-1].setX(W-(250+i*(i%4)));
coastR[i-1].setY(j[i-1]-(i*100));
coastR[i-1].setWidth(250+i*(i%4));
}
for (int i=0;i<8;i++) j[i]++;
}
};
timer.start();
ImageView iv_ship = new ImageView();
iv_ship.setImage(ship);
iv_ship.setFitWidth(150);
iv_ship.setFitHeight(45);
iv_ship.setX(300);
iv_ship.setY(0);
TranslateTransition tt_shipX =
new TranslateTransition(Duration.millis(2000), iv_ship); //moving enemies
tt_shipX.setAutoReverse(true);
tt_shipX.setCycleCount(Timeline.INDEFINITE);
tt_shipX.setByX(200f);
tt_shipX.play();
TranslateTransition tt_shipY =
new TranslateTransition(Duration.millis(13000), iv_ship);
tt_shipY.setAutoReverse(false);
tt_shipY.setCycleCount(Timeline.INDEFINITE);
tt_shipY.setByY(800);
tt_shipY.play();
ImageView iv_plane = new ImageView();
iv_plane.setImage(plane);
iv_plane.setFitWidth(50);
iv_plane.setFitHeight(50);
iv_plane.setX(475);
iv_plane.setY(600);
TranslateTransition tt_plane =
new TranslateTransition(Duration.millis(1), iv_plane);
TranslateTransition tt_shot =
new TranslateTransition(Duration.millis(4000), shot);
tt_shot.setAutoReverse(false);
tt_shot.setCycleCount(1);
TranslateTransition tt_shotB =
new TranslateTransition(Duration.millis(0.5f), shot);
tt_shotB.setAutoReverse(false);
tt_shotB.setCycleCount(1);
root.setOnKeyPressed((KeyEvent ke) -> { //steering a plane }
if (ke.getCode() == KeyCode.LEFT &&
tt_plane.getNode().getTranslateX() > -475) {
tt_plane.setByX(-5f);
tt_plane.play();
System.out.println(tt_plane.getNode().getTranslateX());
}
else if (ke.getCode() == KeyCode.RIGHT &&
tt_plane.getNode().getTranslateX() < 475) {
tt_plane.setByX(5f);
tt_plane.play();
System.out.println(tt_plane.getNode().getTranslateX());
}
else if (ke.getCode() == KeyCode.A) {
shot.setFill(Color.BLACK);
shot.setX(tt_plane.getNode().getTranslateX()+495);
shot.setY(580);
shot.setWidth(10);
shot.setHeight(20);
tt_shot.setByY(-600);
tt_shot.play();
tt_shot.setOnFinished((ActionEvent arg0) -> {
shot.setDisable(true);
tt_shotB.setByY(600);
tt_shotB.play();
});
}
});
if (iv_ship.intersects(iv_plane.getBoundsInLocal())) System.out.println("xxxxxxxxx");
if (iv_plane.intersects(iv_ship.getBoundsInLocal())) System.out.println("zzzz");
if (iv_plane.getBoundsInLocal().intersects(iv_ship.getBoundsInLocal())) System.out.println("dupa");
root.getChildren().add(button_menu);
for (int i=0; i<8; i++) {
root.getChildren().add(coastL[i]);
root.getChildren().add(coastR[i]);
}
root.getChildren().add(iv_plane);
root.getChildren().add(iv_ship);
root.getChildren().add(shot);
primaryStage.setScene(scene_game);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
First of all, you need to take into account that the nodes can be transformed (with translations), so instead of getBoundsInLocal() you need getBoundsInParent().
According to javadocs:
getBoundsInParent() gets the value of the property boundsInParent. The rectangular bounds of this Node which include its transforms. boundsInParent is calculated by taking the local bounds (defined by boundsInLocal) and applying the transform created.
This will work, at any given position of both nodes:
if(iv_plane.getBoundsInParent().intersects(iv_ship.getBoundsInParent())){
System.out.println("Intersection detected");
}
The next problem you have to solve is when do you check a possible intersection. Based on your code, you checked only once, when the nodes where not even added to the root/scene/stage. That couldn't work.
For this to work, you have to check everytime one of them is moved, using some listeners to changes in the translateXProperty() and translateYProperty(), something like this:
private final ChangeListener<Number> checkIntersection = (ob,n,n1)->{
if (iv_plane.getBoundsInParent().intersects(iv_ship.getBoundsInParent())){
System.out.println("Intersection detected");
}
};
private ImageView iv_ship, iv_plane;
private void drawGame (Stage primaryStage) {
iv_ship = new ImageView();
iv_plane = new ImageView();
...
iv_ship.translateXProperty().addListener(checkIntersection);
iv_ship.translateYProperty().addListener(checkIntersection);
...
root.getChildren().addAll(iv_plane,iv_ship);
primaryStage.setScene(scene_game);
}

Categories