Writing my first program using JavaFX here. The program shows data of an object (Person) and I want to implement a 'previous' button that should refresh the Pane with the previous object in a static ArrayList 'arrayListOfPeople'.
As a noob, I hoped I could simply do currentPersonPosition-1 and loadWindow like this:
Button btnBottom = new Button(Integer.toString(currentPersonPosition-1));
final EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
loadWindow(currentPersonPosition, borderPane, anotherStage);
}
};
But, the handle() method can't use the currentPersonPosition variable as it seems the the inner method can only use final instance variables... Then how do you deal with this properly?
I wrote something that certainly isn't a proper way of doing it: I've set the button text to be the currentPersonPosition-1, and then read&parse the value within the handle method. After spending a lot of time to come with this dopey workaround, I wonder how it's done properly.
The minimal producible example below opens a window and shows Name1/Name2/Name3 in the window title bar, and contains a tiny button at the bottom left that functions as the 'previous' button.
Thanks in advance!
public class Main extends Application {
Scene scene = null;
static ArrayList<String> arrayListOfPeople = new ArrayList<>();
public static void main(String[] args) {
launch(args);
}
@Override
public void start(final Stage primaryStage) {
int currentPersonPosition = arrayListOfPeople.size() - 1;
final BorderPane borderPane = new BorderPane();
scene = new Scene(borderPane, 640, 480);
arrayListOfPeople.add("Name1");
arrayListOfPeople.add("Name2");
arrayListOfPeople.add("Name3");
loadWindow(currentPersonPosition, borderPane, primaryStage);
}
public void loadWindow(int currentPersonPosition, final BorderPane borderPane, final Stage anotherStage) {
if (currentPersonPosition < 0) currentPersonPosition = arrayListOfPeople.size()-1;
// BOTTOM
Button btnBottom = new Button(Integer.toString(currentPersonPosition-1));
final EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
String[] testString = e.getTarget().toString().split(",");
System.out.println(testString[0]);
if (testString[0].contains("\"")) {
int positionOfFirstTextQuote = testString[0].indexOf("\"");
int positionOfLastTextQuote = testString[0].lastIndexOf("\"");
String currentClipPositionString = testString[0].substring(positionOfFirstTextQuote + 1, positionOfLastTextQuote);
int currentPersonPosition = Integer.parseInt(currentClipPositionString);
loadWindow(currentPersonPosition, borderPane, anotherStage);
}
}
};
btnBottom.addEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);
borderPane.setBottom(btnBottom);
anotherStage.setTitle(arrayListOfPeople.get(currentPersonPosition));
anotherStage.setScene(scene);
anotherStage.show();
}
}