I have a Question how can i create this in Java with live update percentage
<div class="meter">
<span id="bar1" style="width: 50%">test</span>
<span id="bar2" style="width: 50%">test</span>
</div>
You can see its a Bar (meter) lets say 1000px and two bars in it. If someone Vote for Team one bar1 is 100% and bar2 0% so in meter there is only bar1.
I try it with JavaFX 8 Rectangle that chang dynamicly width, but donst work becuase it dosnt update.
Main.java
package application;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;
import application.TwitchBot.Test;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.scene.paint.Paint;
public class Main extends Application implements Test{
//local interface stuff
TextArea output = new TextArea();
Rectangle bar1 = new Rectangle();
Rectangle bar2 = new Rectangle();
double MID = 315;
Stage secondStage = new Stage();
Pane BarPane = new Pane();
Scene Bar = new Scene(BarPane, 650, 150, Color.GREEN);
#Override
public void start(Stage primaryStage) throws NickAlreadyInUseException, IOException, IrcException {
//Stage 1
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
output.setEditable(false);
root.getChildren().add(output);
output.appendText("/// WELCOME TO THE TWITCH BOT PREALPHA ///");
primaryStage.setTitle("Twitch Bot");
primaryStage.setScene(scene);
primaryStage.show();
//create Stage2
BarPane.setStyle("-fx-background-color:#00FF00");
BarPane.setPrefSize(200,200);
//BAR 1
Rectangle bar1 = new Rectangle();
bar1.setX(10);
bar1.setY(50);
bar1.setWidth(MID);
bar1.setHeight(50);
bar1.setFill(Color.BLUE);
//Bar 2
Rectangle bar2 = new Rectangle();
bar2.setX(MID);
bar2.setY(50);
bar2.setWidth(650-MID-10);
bar2.setHeight(50);
bar2.setFill(Color.RED);
BarPane.getChildren().addAll(bar1,bar2);
secondStage.setTitle("Second Stage");
secondStage.setScene(Bar);
secondStage.show();
//Start BOT
TwitchBot bot = new TwitchBot();
bot.interfaceCallback = this;
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "oauth:XXXXXXX");
bot.joinChannel("#XXXXXXX");
}
public void stop(){
System.exit(0);
}
public static void main(String[] args){
launch(args);
}
#Override
public void printScreen(String message) {
Platform.runLater(new Runnable(){
#Override
public void run() {
output.appendText("\n");
output.appendText(message);
secondStage.show();
}
});
}
#Override
public void setPercent(double Team1, double Team2) {
MID = ((650*Team1)/100)-10;
Platform.runLater(new Runnable(){
#Override
public void run() {
System.out.println(MID);
bar1.setWidth(MID);
bar2.setX(MID);
bar2.setWidth(650-MID-10);
}
});
}
#Override
public void setTeamnames(String Team1, String Team2) {
Platform.runLater(new Runnable(){
#Override
public void run() {
}
});
}
}
TwitchBot.java
package application;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.jibble.pircbot.*;
public class TwitchBot extends PircBot {
// Count Votes
double VoteT1 = 0;
double VoteT2 = 0;
double TotalVotes = 0;
double T1percent = 0;
double T2percent = 0;
// User Arry (Every user can vote 1 time
String users[] = new String[0];
// Files
File configFile = new File("config.properties");
String team1 = "team1.txt";
String team2 = "team2.txt";
String teamnames = "teams.txt";
// Write Channel
String Channel = "#XXXXX";
// Name
String BotName = "DotaLanBot";
// Default Keywords
String Voting = "!voteing"; //Vote Statistics
// Default Properties
String Team1 = "none";
String Team2 = "none";
String Power = "XXX";
public Test interfaceCallback;
public interface Test{
public void printScreen(String message);
public void setPercent(double Team1, double Team2);
public void setTeamnames(String Team1, String Team2);
}
public TwitchBot() {
loadSettings();
this.setName("dotalanbot");
sendMessage(Channel, "Hi I'm your Bot");
//writeInfile(teamnames, Team1 + " vs " + Team2);
T1percent = 50;
T2percent = 50;
}
public void onMessage(String channel, String sender, String login,String hostname, String message) {
//Chat ausgabe in Textfeld
interfaceCallback.printScreen(sender+": "+message);
if (message.equalsIgnoreCase("!win " + Team1)) {
if (check(sender)) {
System.out.println("vote team1");
System.out.println(sender);
VoteT1++;
TotalVotes++;
sendMessage(Channel, "Vote for " + Team1);
T1percent = calcPercent(VoteT1);
T2percent = calcPercent(VoteT2);
interfaceCallback.setPercent(T1percent,T2percent);
// users(sender);
}
}
if (message.equalsIgnoreCase("!win " + Team2)) {
if (check(sender)) {
System.out.println("vote team1");
System.out.println(sender);
VoteT2++;
TotalVotes++;
sendMessage(Channel, "Vote for " + Team2);
T1percent = calcPercent(VoteT1);
T2percent = calcPercent(VoteT2);
interfaceCallback.setPercent(T1percent,T2percent);
//users(sender);
}
}
if (message.equalsIgnoreCase(Voting)) {
System.out.println(Team1 + ":" + VoteT1 + " Votes");
System.out.println(Team2 + ":" + VoteT2 + " Votes");
System.out.println("Total Votes:" + TotalVotes);
sendMessage(Channel, Team1 + ":" + VoteT1 + " Votes || " + Team2
+ ":" + VoteT2 + " Votes || " + "Total Votes:"
+ TotalVotes);
}
if (message.equalsIgnoreCase("!resetvote")) {
if (sender.equalsIgnoreCase(Power)) {
sendMessage(Channel, "Voteing Reset");
resetvote();
}
}
if (message.equalsIgnoreCase("!test")) {
sendMessage(Channel, "Test");
}
if(message.length()>9){
if ((message.substring(0, 9)).equalsIgnoreCase("!setteam1" )) {
if (sender.equalsIgnoreCase(Power)) {
sendMessage(Channel, "Team 1 set to = "+message.substring(10));
Team1 = message.substring(10);
}
}
if ((message.substring(0, 9)).equalsIgnoreCase("!setteam2" )) {
if (sender.equalsIgnoreCase(Power)) {
sendMessage(Channel, "Team 2 set to = "+message.substring(10));
Team2 = message.substring(10);
}
}
}
}
//reset Voteing
private void resetvote(){
//writeInfile(teamnames, Team1 + " vs " + Team2);
T1percent = 50;
T2percent = 50;
interfaceCallback.setPercent(T1percent,T2percent);
String users[] = new String[0];
saveSettings();
}
// write user to array
private void users(String user) {
String[] temp = new String[users.length + 1];
temp[temp.length - 1] = user;
users = temp;
}
// Check if user votes before
private boolean check(String user) {
for (int i = 0; i < users.length; i++) {
if (user.equalsIgnoreCase(users[i])) {
return false;
}
}
return true;
}
// CALS PERCENT
private double calcPercent(double calc) {
double result = (calc / TotalVotes) * 100;
return result;
}
// SETTINGS STUFF
private void saveSettings() {
// wirte Prop
try {
Properties props = new Properties();
props.setProperty("Team1", Team1);
props.setProperty("Team2", Team2);
props.setProperty("Power", Power);
FileWriter writer = new FileWriter(configFile);
props.store(writer, "settings");
writer.close();
} catch (FileNotFoundException ex) {
// file does not exist
} catch (IOException ex) {
// I/O error
}
}
private void loadSettings() {
// Read
try {
FileReader reader = new FileReader(configFile);
Properties props = new Properties();
props.load(reader);
Team1 = props.getProperty("Team1");
Team2 = props.getProperty("Team2");
Power = props.getProperty("Power");
reader.close();
} catch (FileNotFoundException ex) {
// file does not exist
} catch (IOException ex) {
// I/O Error
}
}
}
The Rectangles you add to the scene graph (via BarPane.getChildren().addAll(...)) are not the same ones you reference outside the start(...) method. Hence when you update them in setPercent(...) with bar1.setWidth(...) and bar2.setWidth(...) you are not updating the Rectangles that are displayed.
The problem is that you declare the instance variables a the beginning of the class definition with
Rectangle bar1 = new Rectangle();
Rectangle bar2 = new Rectangle();
and then in the start(...) method, you declare local variables with the same names:
#Override
public void start(Stage primaryStage) {
// ...
Rectangle bar1 = new Rectangle();
// ...
Rectangle bar2 = new Rectangle();
// ...
}
Since you have declared them again here, they are not the same variables.
To fix this, just remove the declaration in the start(...) method, i.e.:
#Override
public void start(Stage primaryStage) {
// ...
bar1 = new Rectangle();
// ...
bar2 = new Rectangle();
// ...
}
It is probably a good idea to remove the initialization at the top of the class too. That way if you did make the error you made, you would be notified as soon as you tried to access them, with a NullPointerException. So:
public class Main extends Application implements Test{
//...
Rectangle bar1 ;
Rectangle bar2 ;
// ...
#Override
public void start(Stage primaryStage) {
// ...
bar1 = new Rectangle();
// ...
bar2 = new Rectangle();
// ...
}
// ...
}
Related
I have two classes ViewTaskTest and ControllerTaskTest. The view has two buttons, one to create a random point and the other to start the controller. After the start, the controller will place 10 random points to the chart inside the view. But the points are visible only at the end. I want to see the points being placed one by one. I know, that I have to use somehow the Task-functions and I am struggling to understand this concept.
This is the ViewTaskTest-class:
package View;
import Controller.ControllerTaskTest;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.chart.Axis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ViewTaskTest{
ScatterChart<Number, Number> scatterChart;
XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
Axis<Number> xAxis = new NumberAxis(0, 10, 2); ;
Axis<Number> yAxis = new NumberAxis(0, 10, 2); ;
Button buttonAddRandomPoint = new Button("Add random point");
Button buttonStartControllerTest = new Button("Start controller");
private final int MAIN_WINDOW_HEIGHT = 800;
private final int MAIN_WINDOW_WIDTH = 800;
ControllerTaskTest controller;
public ViewTaskTest() {
}
public void setController(ControllerTaskTest controller) {
this.controller = controller;
}
public void fillStage(Stage stage) {
stage.setTitle("QuickPID");
stage.setMinHeight(MAIN_WINDOW_HEIGHT);
stage.setMinWidth(MAIN_WINDOW_WIDTH);
stage.setMaxHeight(MAIN_WINDOW_HEIGHT);
stage.setMaxWidth(MAIN_WINDOW_WIDTH);
Scene sceneOne = new Scene(new Group());
scatterChart = new ScatterChart<Number, Number>(xAxis, yAxis);
scatterChart.getData().add(series);
// add a random point
buttonAddRandomPoint.setOnAction(e -> {
Double x = new Double(0.0);
Double y = new Double(0.0);
try{
x = Math.random() * 10;
y = Math.random() * 10;
series.getData().add(new XYChart.Data<Number, Number>(x, y));
} catch (Exception ex) {
System.out.println("Error");
}
});
buttonStartControllerTest.setOnAction(e -> {
controller.startAddingPoints();
});
VBox vboxButtons = new VBox(5);
HBox hboxMain = new HBox(5);
vboxButtons.getChildren().addAll(buttonAddRandomPoint, buttonStartControllerTest);
vboxButtons.setAlignment(Pos.BOTTOM_LEFT);
vboxButtons.setPadding(new Insets(10));
hboxMain.getChildren().addAll(scatterChart, vboxButtons);
sceneOne.setRoot(hboxMain);
stage.setScene(sceneOne);
}
public void addRandomPointFromController(Double x, Double y) {
System.out.println("starting view task");
Task<Integer> task = new Task<Integer>() {
#Override protected Integer call() throws Exception {
series.getData().add(new XYChart.Data<Number, Number>(x, y));
return 0;
}
};
task.run();
}
}
Here is the ControllerTestTask-Class:
package Controller;
import View.ViewTaskTest;
import javafx.concurrent.Task;
public class ControllerTaskTest {
ViewTaskTest view;
public ControllerTaskTest() {
}
public void setView(ViewTaskTest view) {
this.view = view;
}
public void startAddingPoints() {
System.out.println("starting controller task");
Task<Integer> task = new Task<Integer>() {
#Override protected Integer call() throws Exception {
for(int i = 0; i < 10; i++) {
Double x = Math.random() * 10;
Double y = Math.random() * 10;
view.addRandomPointFromController(x, y);
System.out.println("Adding point x = " + x + " and y = " + y);
Thread.sleep(100);
}
return 0;
}
};
task.run();
}
}
Here is the main-class:
package Test;
import Controller.ControllerTaskTest;
import View.ViewTaskTest;
import javafx.application.Application;
import javafx.stage.Stage;
public class Test extends Application{
private ViewTaskTest view= new ViewTaskTest();
private ControllerTaskTest controller = new ControllerTaskTest();
public static void main(String[] args) {
launch();
}
#Override
public void start(Stage stage) throws Exception {
view.setController(controller);
controller.setView(view);
stage.show();
view.fillStage(stage);
}
}
Some please explain me what I am doing wrong. I am experimenting with the Thread-funcitons but I cant solve my problem.
I have an arraylist of Point. I want to draw lines out the points. Here is what I have done.
for (int i = 0; i < arrPoint.size(); i++) {
Point startPoint = arrPoint.get(i);
Point endPoint = null;
if (i == arrPoint.size()) {
endPoint = arrPoint.get(0);
} else {
endPoint = arrPoint.get(i + 1);
}
Line line = new Line();
line.setStartX(startPoint.getCoordinateX());
line.setEndX(endPoint.getCoordinateX());
line.setStartY(startPoint.getCoordinateY());
line.setEndY(endPoint.getCoordinateY());
box.getChildren().add(line);
}
My Point cass is like
public class Point {
private double coordinateX;
private double coordinateY;
public Point(double coordinateX, double coordinateY) {
this.coordinateX = coordinateX;
this.coordinateY = coordinateY;
}
public void setCoordinateX(double coordinateX) {
this.coordinateX = coordinateX;
}
public void setCoordinateY(double coordinateY) {
this.coordinateY = coordinateY;
}
public double getCoordinateX() {
return coordinateX;
}
public double getCoordinateY() {
return coordinateY;
}
}
My code is displayed blank. I am new to JavaFx. Can I get any help?
You need to have the points before you can loop over the points to draw.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Draw line");
Group g = new Group();
Scene scene = new Scene(g, 550, 550,Color.web("0x0000FF",1.0));
ObservableList<Point> arrPoint = FXCollections.observableArrayList();
Point point1 = new Point(100, 200);
Point point2 = new Point(300, 400);
arrPoint.addAll(point1, point2);
for (int i = 0; i < arrPoint.size()-1; i++) {
Point startPoint = arrPoint.get(i);
Point endPoint = null;
if (i == arrPoint.size()) {
endPoint = arrPoint.get(0);
} else {
endPoint = arrPoint.get(i + 1);
}
Line line = new Line();
line.setStartX(startPoint.getCoordinateX());
line.setEndX(endPoint.getCoordinateX());
line.setStartY(startPoint.getCoordinateY());
line.setEndY(endPoint.getCoordinateY());
g.getChildren().add(line);
}
primaryStage.setScene(scene);
primaryStage.show();
}
}
I hope it can help you some.
I have a Javafx TableView where I can add new Rows by double Click on an empty Row at the End of my "filled" / Textfield filled Rows.
My Problem is,if i add some Rows ,Java don't give me more of the empty Rows I could double click to add some Rows.
Edit:removed some unnessary log
To see what i mean, here is the Code:
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TextArea;
import javafx.util.Callback;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
interface inside_table
{
public void Select_Row_by_Col(int index);
}
public class Supermain extends Application {
ObservableList<myTextRow> data;
#Override
public void start(Stage primaryStage) {
ArrayList myindizes=new ArrayList();
final TableView<myTextRow> table = new TableView<>();
table.setEditable(true);
table.setStyle("-fx-text-wrap: true;");
//Table columns
TableColumn<myTextRow, String> clmID = new TableColumn<>("ID");
clmID.setMinWidth(160);
clmID.setCellValueFactory(new PropertyValueFactory<>("ID"));
TableColumn<myTextRow, String> clmtext = new TableColumn<>("Text");
clmtext.setMinWidth(160);
clmtext.setCellValueFactory(new PropertyValueFactory<>("text"));
clmtext.setCellFactory(new TextFieldCellFactory("text"));
TableColumn<myTextRow, String> clmtext2 = new TableColumn<>("Text2");
clmtext2.setMinWidth(160);
clmtext2.setCellValueFactory(new PropertyValueFactory<>("text2"));
clmtext2.setCellFactory(new TextFieldCellFactory("text2"));
//Add data
data = FXCollections.observableArrayList(
new myTextRow(5, "Lorem","bla"),
new myTextRow(2, "Ipsum","bla")
);
table.getColumns().addAll(clmID, clmtext,clmtext2);
table.setItems(data);
table.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2 && mouseEvent.getY()>24) {
data.add(new myTextRow(td_get_biggest_ID() + 1,"",""));
table.selectionModelProperty().get().select(data.size()-1);
}
}
}
});
HBox hBox = new HBox();
hBox.setSpacing(5.0);
hBox.setPadding(new Insets(5, 5, 5, 5));
Button btn = new Button();
btn.setText("Get Data");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
for (myTextRow data1 : data) {
System.out.println("data:" + data1.getText2());
}
}
});
hBox.getChildren().add(btn);
BorderPane pane = new BorderPane();
pane.setTop(hBox);
pane.setCenter(table);
primaryStage.setScene(new Scene(pane, 640, 480));
primaryStage.show();
class I_table implements inside_table{
#Override
public void Select_Row_by_Col(int index) {
table.getSelectionModel().select(index);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public static class TextFieldCellFactory
implements Callback<TableColumn<myTextRow, String>, TableCell<myTextRow, String>> {
private String ColumnName;
public TextFieldCellFactory(String ColumnName){
this.ColumnName=ColumnName;
}
#Override
public TableCell<myTextRow, String> call(TableColumn<myTextRow, String> param) {
TextFieldCell textFieldCell = new TextFieldCell(this.ColumnName);
return textFieldCell;
}
public static class TextFieldCell extends TableCell<myTextRow, String> {
private TextArea textField;
private StringProperty boundToCurrently = null;
private String last_text;
private String ColumnName;
public TextFieldCell(String cname) {
textField = new TextArea();
textField.setWrapText(true);
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
last_text="";
this.ColumnName=cname;
this.setGraphic(textField);
textField.focusedProperty().addListener((obs, wasFocused, isNowFocused) -> {
if(this.ColumnName=="text2"){
if(isNowFocused){last_text=textField.getText();System.out.println("NOW focus "+last_text);}
if (! isNowFocused && ! isValid(textField.getText())) {
textField.setText(last_text);
//textField.setText("00:00:00:00");
textField.selectAll();
System.out.println("blur");
}
}
});
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
// Show the Text Field
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
// myindizes.add(getIndex());
// Retrieve the actual String Property that should be bound to the TextField
// If the TextField is currently bound to a different StringProperty
// Unbind the old property and rebind to the new one
ObservableValue<String> ov = getTableColumn().getCellObservableValue(getIndex());
SimpleStringProperty sp = (SimpleStringProperty) ov;
if (this.boundToCurrently == null) {
this.boundToCurrently = sp;
this.textField.textProperty().bindBidirectional(sp);
} else if (this.boundToCurrently != sp) {
this.textField.textProperty().unbindBidirectional(this.boundToCurrently);
this.boundToCurrently = sp;
this.textField.textProperty().bindBidirectional(this.boundToCurrently);
}
double height = real_lines_height(textField.getText(), this.getWidth(), 30, 22);
textField.setPrefHeight(height);
textField.setMaxHeight(height);
textField.setMaxHeight(Double.MAX_VALUE);
// if height bigger than the biggest height in the row
//-> change all heights of the row(textfields ()typeof textarea) to this height
// else leave the height as it is
//System.out.println("item=" + item + " ObservableValue<String>=" + ov.getValue());
//this.textField.setText(item); // No longer need this!!!
} else {
this.setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}//update
private boolean isValid(String s){
String splitArray[] = s.split(":");
if (splitArray.length != 4) {
System.out.println("false");
return false;
}
for (int i = 0; i < splitArray.length; i++) {
if (splitArray[i].length() != 2) {
System.out.println("false");
return false;
}
if (!splitArray[i].substring(0, 1).matches("[0-9]")) {
System.out.println("no number1");
return false;
}
if (!splitArray[i].substring(1, 2).matches("[0-9]")) {
System.out.println("no number2");
return false;
}
if (i < 3) {
int itest = Integer.parseInt(splitArray[i]);
if (itest > 59) {
System.out.println(itest + " ist zu groß!");
return false;
}
} else {
int itest2 = Integer.parseInt(splitArray[i]);
if (itest2 > Math.floor(25)) {
System.out.println(itest2 + " ist zu groß!");
return false;
}
//framerate!!!!!
}
System.out.println("splits: " + splitArray[i]);
//if( el.charAt(0).)
}
return true;
}
}
}
public class myTextRow {
private final SimpleIntegerProperty ID;
private final SimpleStringProperty text;
private final SimpleStringProperty text2;
public myTextRow(int ID, String text,String text2) {
this.ID = new SimpleIntegerProperty(ID);
this.text = new SimpleStringProperty(text);
this.text2 = new SimpleStringProperty(text2);
}
//setter
public void setID(int id) {
this.ID.set(id);
}
public void setText(String text) {
this.text.set(text);
}
public void setText2(String text) {
this.text2.set(text);
}
//getter
public int getID() {
return ID.get();
}
public String getText() {
return text.get();
}
public String getText2() {
return text2.get();
}
//properties
public StringProperty textProperty() {
return text;
}
public StringProperty text2Property() {
return text2;
}
public IntegerProperty IDProperty() {
return ID;
}
}
private static double real_lines_height(String s, double width, double heightCorrector, double widthCorrector) {
HBox h = new HBox();
Label l = new Label("Text");
h.getChildren().add(l);
Scene sc = new Scene(h);
l.applyCss();
double line_height = l.prefHeight(-1);
int new_lines = s.replaceAll("[^\r\n|\r|\n]", "").length();
// System.out.println("new lines= "+new_lines);
String[] lines = s.split("\r\n|\r|\n");
// System.out.println("line count func= "+ lines.length);
int count = 0;
//double rest=0;
for (int i = 0; i < lines.length; i++) {
double text_width = get_text_width(lines[i]);
double plus_lines = Math.ceil(text_width / (width - widthCorrector));
if (plus_lines > 1) {
count += plus_lines;
//rest+= (text_width / (width-widthCorrector)) - plus_lines;
} else {
count += 1;
}
}
//count+=(int) Math.ceil(rest);
count += new_lines - lines.length;
return count * line_height + heightCorrector;
}
private static double get_text_width(String s) {
HBox h = new HBox();
Label l = new Label(s);
l.setWrapText(false);
h.getChildren().add(l);
Scene sc = new Scene(h);
l.applyCss();
// System.out.println("FXMLDocumentController.get_text_width(): "+l.prefWidth(-1));
return l.prefWidth(-1);
}
public int td_get_biggest_ID() {
int biggest = 0;
for (int i = 0; i < data.size(); i++) {
if (((myTextRow) data.get(i)).getID() > biggest) {
biggest = ((myTextRow) data.get(i)).getID();
}
}
return biggest;
}
}
Just click anywhere else on the TableView but make sure it's at least 24 pixels from the top; This will work since you've added the event handler is added to the TableView...
If you only want to use the last row, then use a custom rowFactory and handle the events there.
Add a placeholder item to the TableView items that marks the row that is used for adding new elements (for some reason the selection model doesn't like null):
final myTextRow addPlaceHolder = new myTextRow(Integer.MIN_VALUE, null, null);
...
//Add data
data = FXCollections.observableArrayList(
new myTextRow(5, "Lorem", "bla"),
new myTextRow(2, "Ipsum", "bla"),
addPlaceHolder
);
make sure your TextFieldCells treat null values as empty rows:
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (!empty && item != null) {
// Show the Text Field
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
...
make sure the first column does not display anything for the placeholder
//Table columns
TableColumn<myTextRow, Number> clmID = new TableColumn<>("ID");
clmID.setMinWidth(160);
clmID.setCellValueFactory(cdf -> {
myTextRow item = cdf.getValue();
return item == addPlaceHolder ? Bindings.createObjectBinding(() -> null) : item.IDProperty();
});
and use the following rowFactory to handle adding the items (you don't need the updateItem part unless you need to add a style class to the TableRow; you need not extend TableRow in this case)
table.setRowFactory(tv -> new TableRow<myTextRow>() {
{
setOnMouseClicked(mouseEvent -> {
if (mouseEvent.getButton() == MouseButton.PRIMARY
&& mouseEvent.getClickCount() == 2
&& !isEmpty()
&& getItem() == addPlaceHolder) {
data.add(data.size() - 1, new myTextRow(td_get_biggest_ID() + 1, "", ""));
table.selectionModelProperty().get().select(data.size() - 1);
mouseEvent.consume();
}
});
}
#Override
protected void updateItem(myTextRow item, boolean empty) {
super.updateItem(item, empty);
// add style class for row containing addPlaceHolder
List<String> classes = getStyleClass();
final String clazz = "add-row";
if (item == addPlaceHolder) {
if (!classes.contains(clazz)) {
classes.add(clazz);
}
} else {
classes.remove(clazz);
}
}
});
I want a tableview to take in values when end user copies data from excel and pastes it on the tableview..
I want to know the best approach so as of now there isn't any code to post... I want to use Clipboard class and manually add content from the clipboard to the table...
Is that the right approach?
If not. How to do it?
Are there any methods or classes which already implement this
functionality..?
You can do it like this. But you need to adapt the code to match your requirements (e. g. numberformatting, etc).
TableCopyPasteCellsDemo.java
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TableCopyPasteCellsDemo extends Application {
private final ObservableList<Person> data = FXCollections.observableArrayList(new Person("Jacob", "Smith", 18), new Person("Isabella", "Johnson", 19), new Person("Ethan", "Williams", 20), new Person("Michael", "Brown", 21));
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
stage.setWidth(500);
stage.setHeight(550);
// create table columns
TableColumn<Person, String> firstNameCol = new TableColumn<Person, String>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<Person, String>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TableColumn<Person, Integer> ageCol = new TableColumn<Person, Integer>("Age");
ageCol.setMinWidth(60);
ageCol.setCellValueFactory(new PropertyValueFactory<Person, Integer>("age"));
TableView<Person> table = new TableView<>();
table.setPlaceholder(new Text("No content in table"));
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, ageCol);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 10, 10, 10));
BorderPane borderPane = new BorderPane();
borderPane.setCenter(table);
vbox.getChildren().addAll(borderPane);
vbox.getChildren().add( new Label( "Select cells and press CTRL+C. Paste the data into Excel or Notepad"));
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.show();
// enable multi-selection
table.getSelectionModel().setCellSelectionEnabled(true);
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// enable copy/paste
TableUtils.installCopyPasteHandler(table);
}
public static class Person {
private final StringProperty firstName;
private final StringProperty lastName;
private final IntegerProperty age;
private Person(String fName, String lName, Integer age) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.age = new SimpleIntegerProperty(age);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final java.lang.String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final java.lang.String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final java.lang.String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final java.lang.String lastName) {
this.lastNameProperty().set(lastName);
}
public final IntegerProperty ageProperty() {
return this.age;
}
public final int getAge() {
return this.ageProperty().get();
}
public final void setAge(final int age) {
this.ageProperty().set(age);
}
}
}
TableUtils.java
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.StringTokenizer;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
public class TableUtils {
private static NumberFormat numberFormatter = NumberFormat.getNumberInstance();
/**
* Install the keyboard handler:
* + CTRL + C = copy to clipboard
* + CTRL + V = paste to clipboard
* #param table
*/
public static void installCopyPasteHandler(TableView<?> table) {
// install copy/paste keyboard handler
table.setOnKeyPressed(new TableKeyEventHandler());
}
/**
* Copy/Paste keyboard event handler.
* The handler uses the keyEvent's source for the clipboard data. The source must be of type TableView.
*/
public static class TableKeyEventHandler implements EventHandler<KeyEvent> {
KeyCodeCombination copyKeyCodeCompination = new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY);
KeyCodeCombination pasteKeyCodeCompination = new KeyCodeCombination(KeyCode.V, KeyCombination.CONTROL_ANY);
public void handle(final KeyEvent keyEvent) {
if (copyKeyCodeCompination.match(keyEvent)) {
if( keyEvent.getSource() instanceof TableView) {
// copy to clipboard
copySelectionToClipboard( (TableView<?>) keyEvent.getSource());
// event is handled, consume it
keyEvent.consume();
}
}
else if (pasteKeyCodeCompination.match(keyEvent)) {
if( keyEvent.getSource() instanceof TableView) {
// copy to clipboard
pasteFromClipboard( (TableView<?>) keyEvent.getSource());
// event is handled, consume it
keyEvent.consume();
}
}
}
}
/**
* Get table selection and copy it to the clipboard.
* #param table
*/
public static void copySelectionToClipboard(TableView<?> table) {
StringBuilder clipboardString = new StringBuilder();
ObservableList<TablePosition> positionList = table.getSelectionModel().getSelectedCells();
int prevRow = -1;
for (TablePosition position : positionList) {
int row = position.getRow();
int col = position.getColumn();
// determine whether we advance in a row (tab) or a column
// (newline).
if (prevRow == row) {
clipboardString.append('\t');
} else if (prevRow != -1) {
clipboardString.append('\n');
}
// create string from cell
String text = "";
Object observableValue = (Object) table.getColumns().get(col).getCellObservableValue( row);
// null-check: provide empty string for nulls
if (observableValue == null) {
text = "";
}
else if( observableValue instanceof DoubleProperty) { // TODO: handle boolean etc
text = numberFormatter.format( ((DoubleProperty) observableValue).get());
}
else if( observableValue instanceof IntegerProperty) {
text = numberFormatter.format( ((IntegerProperty) observableValue).get());
}
else if( observableValue instanceof StringProperty) {
text = ((StringProperty) observableValue).get();
}
else {
System.out.println("Unsupported observable value: " + observableValue);
}
// add new item to clipboard
clipboardString.append(text);
// remember previous
prevRow = row;
}
// create clipboard content
final ClipboardContent clipboardContent = new ClipboardContent();
clipboardContent.putString(clipboardString.toString());
// set clipboard content
Clipboard.getSystemClipboard().setContent(clipboardContent);
}
public static void pasteFromClipboard( TableView<?> table) {
// abort if there's not cell selected to start with
if( table.getSelectionModel().getSelectedCells().size() == 0) {
return;
}
// get the cell position to start with
TablePosition pasteCellPosition = table.getSelectionModel().getSelectedCells().get(0);
System.out.println("Pasting into cell " + pasteCellPosition);
String pasteString = Clipboard.getSystemClipboard().getString();
System.out.println(pasteString);
int rowClipboard = -1;
StringTokenizer rowTokenizer = new StringTokenizer( pasteString, "\n");
while( rowTokenizer.hasMoreTokens()) {
rowClipboard++;
String rowString = rowTokenizer.nextToken();
StringTokenizer columnTokenizer = new StringTokenizer( rowString, "\t");
int colClipboard = -1;
while( columnTokenizer.hasMoreTokens()) {
colClipboard++;
// get next cell data from clipboard
String clipboardCellContent = columnTokenizer.nextToken();
// calculate the position in the table cell
int rowTable = pasteCellPosition.getRow() + rowClipboard;
int colTable = pasteCellPosition.getColumn() + colClipboard;
// skip if we reached the end of the table
if( rowTable >= table.getItems().size()) {
continue;
}
if( colTable >= table.getColumns().size()) {
continue;
}
// System.out.println( rowClipboard + "/" + colClipboard + ": " + cell);
// get cell
TableColumn tableColumn = table.getColumns().get(colTable);
ObservableValue observableValue = tableColumn.getCellObservableValue(rowTable);
System.out.println( rowTable + "/" + colTable + ": " +observableValue);
// TODO: handle boolean, etc
if( observableValue instanceof DoubleProperty) {
try {
double value = numberFormatter.parse(clipboardCellContent).doubleValue();
((DoubleProperty) observableValue).set(value);
} catch (ParseException e) {
e.printStackTrace();
}
}
else if( observableValue instanceof IntegerProperty) {
try {
int value = NumberFormat.getInstance().parse(clipboardCellContent).intValue();
((IntegerProperty) observableValue).set(value);
} catch (ParseException e) {
e.printStackTrace();
}
}
else if( observableValue instanceof StringProperty) {
((StringProperty) observableValue).set(clipboardCellContent);
} else {
System.out.println("Unsupported observable value: " + observableValue);
}
System.out.println(rowTable + "/" + colTable);
}
}
}
}
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);
}