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

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.

Related

Add two add & subtract EventHandler's for multiple buttons

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) {
}
}
}
`

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.

Userclass isn't Processing the value for username and password for comparing when value taken from login class

import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.text.*;
import javafx.scene.control.*;
import javafx.scene.paint.*;
import javafx.scene.text.Font;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.geometry.*;
public class Login extends Application
{
static Stage classStage = new Stage();
#Override
public void start(Stage primaryStage)
{
Text t = new Text("Welcome To Our Library");
t.setFont(Font.font("Arial Black", 24.0));
Label l1 = new Label("User Name: ");
l1.setFont(Font.font("Arial", 16));
l1.setPadding(new Insets(10));
TextField t1 = new TextField();
t1.setPromptText("Your Username");
t1.selectAll();
t1.setPadding(new Insets(10,10,10,50));
Label l2 = new Label("Password: ");
l2.setFont(Font.font("Arial", 16));
l2.setPadding(new Insets(10));
TextField t2 = new TextField();
t2.setPromptText("Your Username");
t2.setPadding(new Insets(10,10,10,50));
Button b1 = new Button("Register");
b1.setPadding(new Insets(10,40,10,40));
b1.setStyle("-fx-font-size: 14px; ");
Button b2 = new Button("Login");
b2.setStyle("-fx-font-size: 14px; ");
b2.setPadding(new Insets(10,50,10,50));
b1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Register r = new Register();
r.start(Register.classStage);
primaryStage.hide();
}
);
User u = new User();
String user = u.getusername();
String pass = u.getconfirm_password();
b2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if(t1.getText().equals(user) && t2.getText().equals(pass))
{
Welcome r = new Welcome();
r.start(Welcome.classStage);
primaryStage.hide();
}
}
}
);
VBox root = new VBox();
HBox h = new HBox();
HBox h1 = new HBox();
HBox h2 = new HBox();
HBox h3 = new HBox();
h3.setSpacing(35.0);
h.setPadding(new Insets(100,100,10,100));
h1.setPadding(new Insets(50,100,10,100));
h2.setPadding(new Insets(20,100,10,110));
h3.setPadding(new Insets(20,80,10,80));
h.getChildren().addAll(t);
h1.getChildren().addAll(l1,t1);
h2.getChildren().addAll(l2,t2);
h3.getChildren().addAll(b1,b2);
h.setAlignment(Pos.CENTER);
h1.setAlignment(Pos.CENTER);
h2.setAlignment(Pos.CENTER);
h3.setAlignment(Pos.CENTER);
root.getChildren().addAll(h,h1,h2,h3);
Scene s = new Scene(root,700,600);
primaryStage.setTitle("Library Mangement System");
primaryStage.setScene(s);
primaryStage.show();
Login.classStage = primaryStage ;
}
}
}
Registration class for creating registration form.
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.text.*;
import javafx.scene.control.*;
import javafx.scene.text.Font;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.geometry.*;
import javafx.scene.control.Alert.AlertType;
public class Register extends Application{
static Stage classStage = new Stage();
Alert alert = new Alert(AlertType.WARNING);
#Override
public void start(Stage primaryStage)
{
Text t = new Text("Complete the form below to create your new Library account");
t.setFont(Font.font("Arial Black", 16));
Label l1 = new Label("First Name: ");
l1.setFont(Font.font("Arial", 16));
l1.setPadding(new Insets(10));
TextField t1 = new TextField();
t1.setPadding(new Insets(10,10,10,50));
Label l2 = new Label("Last Name: ");
l2.setFont(Font.font("Arial", 16));
l2.setPadding(new Insets(10));
TextField t2 = new TextField();
t2.setPadding(new Insets(10,10,10,50));
Label l3 = new Label("User Name: ");
l3.setFont(Font.font("Arial", 16));
l3.setPadding(new Insets(10));
TextField t3 = new TextField();
t3.setPadding(new Insets(10,10,10,50));
Label l4 = new Label("Password: ");
l4.setFont(Font.font("Arial", 16));
l4.setPadding(new Insets(10));
TextField t4 = new TextField();
t4.setPadding(new Insets(10,10,10,50));
Label l5 = new Label("Confirm Password: ");
l5.setFont(Font.font("Arial", 16));
l5.setPadding(new Insets(10));
TextField t5 = new TextField();
t5.setPadding(new Insets(10,10,10,50));
Label l6 = new Label("Contact Number: ");
l6.setFont(Font.font("Arial", 16));
l6.setPadding(new Insets(10));
TextField t6 = new TextField();
t6.setPadding(new Insets(10,10,10,50));
Label l7 = new Label("Email: ");
l7.setFont(Font.font("Arial", 16));
l7.setPadding(new Insets(10));
TextField t7 = new TextField();
t7.setPadding(new Insets(10,10,10,50));
Label l8 = new Label("Sex: ");
l8.setFont(Font.font("Arial", 16));
l8.setPadding(new Insets(10));
final ToggleGroup group = new ToggleGroup();
RadioButton rb1 = new RadioButton("Male");
rb1.setToggleGroup(group);
rb1.setSelected(true);
RadioButton rb2 = new RadioButton("Female");
rb2.setToggleGroup(group);
rb1.setPadding(new Insets(10,10,10,30));
rb2.setPadding(new Insets(10,10,10,30));
Button b1 = new Button("Cancel");
b1.setPadding(new Insets(10,40,10,40));
b1.setFont(Font.font("Arial", 14));
Button b2 = new Button("Confirm");
b2.setPadding(new Insets(10,40,10,40));
b2.setFont(Font.font("Arial", 14));
b1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Login l = new Login();
l.start(Login.classStage);
primaryStage.hide();
}
}
)
;
b2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
/*if(t4.getText()!=t5.getText()){
alert.setTitle("Warning Dialog");
alert.setHeaderText("Password doesn't match!");
alert.setContentText("Try again with different password.");
alert.showAndWait();
}*/
User u = new User();
Login l = new Login();
l.start(Login.classStage);
primaryStage.hide();
}
}
);
VBox root = new VBox();
HBox h = new HBox();
HBox h1 = new HBox();
HBox h2 = new HBox();
HBox h3 = new HBox();
HBox h4 = new HBox();
HBox h5 = new HBox();
HBox h6 = new HBox();
HBox h7 = new HBox();
HBox h8 = new HBox();
HBox h9 = new HBox();
h9.setSpacing(30.0);
h.setPadding(new Insets(30,100,10,100));
h1.setPadding(new Insets(30,100,10,100));
h2.setPadding(new Insets(10,100,10,100));
h3.setPadding(new Insets(10,100,10,100));
h4.setPadding(new Insets(10,100,10,110));
h5.setPadding(new Insets(10,100,10,50));
h6.setPadding(new Insets(10,100,10,65));
h7.setPadding(new Insets(10,100,10,140));
h8.setPadding(new Insets(10,100,10,140));
h9.setPadding(new Insets(20,80,10,80));
h9.setSpacing(25.0);
h.getChildren().addAll(t);
h1.getChildren().addAll(l1,t1);
h2.getChildren().addAll(l2,t2);
h3.getChildren().addAll(l3,t3);
h4.getChildren().addAll(l4,t4);
h5.getChildren().addAll(l5,t5);
h6.getChildren().addAll(l6,t6);
h7.getChildren().addAll(l7,t7);
h8.getChildren().addAll(l8,rb1,rb2);
h9.getChildren().addAll(b1,b2);
h.setAlignment(Pos.CENTER);
h1.setAlignment(Pos.CENTER);
h2.setAlignment(Pos.CENTER);
h3.setAlignment(Pos.CENTER);
h4.setAlignment(Pos.CENTER);
h5.setAlignment(Pos.CENTER);
h6.setAlignment(Pos.CENTER);
h7.setAlignment(Pos.CENTER);
h8.setAlignment(Pos.CENTER);
h9.setAlignment(Pos.CENTER);
root.getChildren().addAll(h,h1,h2,h3,h4,h5,h6,h7,h8,h9);
Scene s = new Scene(root,700,650);
primaryStage.setScene(s);
primaryStage.setTitle("Registration");
primaryStage.show();
}
}
Now there needs a user class which will have all the value of the register form.
class User{
private String firstname;
private String lastname;
private String username;
private String password;
private String confirm_password;
private String contactno;
private String email;
public User()
{
}
public User(String firstname,String lastname,String username,String password,String confirm_password,String contactno,String email)
{
this.setfirstname(firstname);
this.setlastname(lastname);
this.setusername(username);
this.setpassword(password);
this.setconfirm_password(confirm_password);
this.setcontactno(contactno);
this.setemail(email);
}
public void setusername(String username)
{
this.username=username;
}
public void setpassword(String password)
{
this.password=password;
}
public void setconfirm_password(String confirm_password)
{
this.confirm_password=confirm_password;
}
public void setfirstname(String firstname)
{
this.firstname=firstname;
}
public void setlastname(String lastname)
{
this.lastname=lastname;
}
public void setcontactno(String contactno)
{
this.contactno=contactno;
}
public void setemail(String email)
{
this.email=email;
}
public String getusername()
{
return this.username;
}
public String getpassword()
{
return this.password;
}
public String getconfirm_password()
{
return this.confirm_password;
}
public String getfirstname()
{
return this.firstname;
}
public String getlastname()
{
return this.lastname;
}
public String getcontactno()
{
return this.contactno;
}
public String getemail()
{
return this.email;
}
}
This program needs to work like this.A register form will first appear.After user gives the details.All the info like firstname,lastname,password,email,sex etc all the details will be transferred to the user class.so when that user login to the system It will check the value of username and password from user class and compare them.When mismatch occurs it will show errors

error message displays if the user enters a character that isn't an integer

I am writing this program for a class i am in and i have been able to create this code. I know that it is very messy and i apologize. I need to find a way to have the program prevent the user from entering anything besides and integer. if i had a way for it to check i would be able to make a new stage appear myself. if there are any ideas i would be happy to hear them. Again I am not asking anyone to make the app for me i just need a way to check if there are characters other than integers and do something in that case. like a for else loop. Thanks in advance. (this is the first time i have ever used JavaFX so go easy:/
import java.util.InputMismatchException;
import org.omg.CORBA.portable.InputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
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.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.event.*;
public class Lab9Test extends Application {
public static void main(String[] args) {
// TODO Auto-generated method stub
//launch it all
launch(args);
}
#Override //create the grids scenes stages needed to run the program
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
final Stage dialogStage = new Stage();
Label Label1 = new Label ("ERROR! You cannot divide by zero!");
Button Okay = new Button("Okay!");
GridPane GPane2 = new GridPane();
GPane2.setAlignment(Pos.TOP_LEFT);
GPane2.setVgap(10);
GPane2.setHgap(-32);
GPane2.setPadding(new Insets(10,10,10,10));
Scene scene2 = new Scene(GPane2, 222,300);
GridPane.setConstraints(Okay,4,1);
GridPane.setConstraints(Label1,0,2);
VBox root = new VBox();
dialogStage.setScene(scene2);
dialogStage.getIcons().add(new
GPane2.getChildren().addAll(Label1, Okay);
Okay.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
dialogStage.close();
}
});
primaryStage.setTitle("JavaFX Arithmatic");
GridPane GPane = new GridPane();
GPane.setAlignment(Pos.TOP_LEFT);
GPane.setVgap(10);
GPane.setHgap(-75);
GPane.setPadding(new Insets(10,10,10,10));
Scene scene = new Scene(GPane, 325, 250);
Button add = new Button();
add.setText("+");
Button multiply = new Button();
multiply.setText("*");
Button divide = new Button();
divide.setText("/");
Button subtract = new Button();
subtract.setText("-");
Button percent = new Button();
percent.setText("%");
Button clear = new Button();
clear.setText("CLEAR");
Text scenetitle = new Text("Enter two numbers and select an operation.");
Text SecondNumber = new Text("Second Number:");
Text FirstNumber = new Text("First Number:");
Text Result = new Text("Result:");
//create text fields
final TextField TFFirstNumber = new TextField();
final TextField TFSecondNumber = new TextField();
final TextField TFResult = new TextField();
//change position on grid
GridPane.setConstraints(FirstNumber,0,1);
GridPane.setConstraints(SecondNumber,0,2);
GridPane.setConstraints(Result,0,3);
GridPane.setConstraints(add,0,4);
GridPane.setConstraints(multiply,0,5);
GridPane.setConstraints(percent,0,6);
GridPane.setConstraints(divide,1,5);
GridPane.setConstraints(subtract,1,4);
GridPane.setConstraints(clear,1,6);
GridPane.setConstraints(scenetitle,0,0);
GridPane.setConstraints(TFFirstNumber,1,1);
GridPane.setConstraints(TFSecondNumber,1,2);
GridPane.setConstraints(TFResult,1,3);
GPane.getChildren().addAll(TFResult,TFFirstNumber,TFSecondNumber,add,FirstNumber,SecondNumber,Result,subtract,multiply,divide,percent,clear,scenetitle);
//change size and alter the text fields
add.setMaxWidth(150);
subtract.setMaxWidth(150);
clear.setMaxWidth(150);
divide.setMaxWidth(150);
percent.setMaxWidth(150);
multiply.setMaxWidth(150);
TFFirstNumber.setMaxWidth(150);
TFSecondNumber.setMaxWidth(150);
TFResult.setMaxWidth(150);
TFResult.setEditable(false);
primaryStage.setScene(scene);
primaryStage.getIcons().add(new
primaryStage.show();
//give all of the buttons a purpose in life
add.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
Integer value1 = Integer.valueOf(TFFirstNumber.getText());
Integer value2 = Integer.valueOf(TFSecondNumber.getText());
Integer r = value1 + value2;
TFResult.setText(r.toString());
}
});
subtract.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
Integer value1 = Integer.valueOf(TFFirstNumber.getText());
Integer value2 = Integer.valueOf(TFSecondNumber.getText());
Integer r = value1 - value2;
TFResult.setText(r.toString());
}
});
multiply.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
Integer value1 = Integer.valueOf(TFFirstNumber.getText());
Integer value2 = Integer.valueOf(TFSecondNumber.getText());
Integer r = value1 * value2;
TFResult.setText(r.toString());
}
});
divide.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
Integer value1 = Integer.valueOf(TFFirstNumber.getText());
Integer value2 = Integer.valueOf(TFSecondNumber.getText());
if(value2==0){
dialogStage.show();
}
else{
Integer r = value1 / value2;
TFResult.setText(r.toString());
}
}
});
percent.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
Integer value1 = Integer.valueOf(TFFirstNumber.getText());
Integer value2 = Integer.valueOf(TFSecondNumber.getText());
Integer r = value1 % value2;
TFResult.setText(r.toString());
}
});
clear.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent event){
TFFirstNumber.clear();
TFSecondNumber.clear();
TFResult.clear();
}
});
}
}
The duplicate offers a good solution, but there is another way:
You could wrap the parsing of the integers in something like this:
public void handle(ActionEvent event) {
Integer value1 = 0;
Integer value2 = 0;
try {
value1 = Integer.valueOf(TFFirstNumber.getText());
value2 = Integer.valueOf(TFSecondNumber.getText());
} catch(Exception e) {
System.err.println("Wrong input value: needs to be an integer");
return; // i.e. do mothing more
}
Integer r = value1 + value2;
TFResult.setText(r.toString());
}

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