javafx events not working - java

public class Testing extends Application {
#Override
public void start(Stage stage)
{
Button button1 = new Button("First button");
Button button2 = new Button("Second button");
EventHandler<ActionEvent> aHandler = new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event)
{
button2.setText("Working");
}
};
button1.addEventHandler(ActionEvent.ACTION, aHandler);
HBox hbox = new HBox(40,button1, button2);
Scene scene = new Scene(hbox, 840, 400);
stage.setScene(scene);
stage.setTitle("Testing");
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
You can see that this is a javafx Testing class where I am testing eventHandlers and it works fine but when I split the code and add it into on its own methods then the eventHandlers does not work like in the code below
public class Testing extends Application {
#Override
public void start(Stage stage)
{
EventHandler<ActionEvent> aHandler = new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event)
{
button2().setText("Working");
}
};
button1().addEventHandler(ActionEvent.ACTION, aHandler);
stage.setScene(scene());
stage.setTitle("Testing");
stage.show();
}
public Button button1()
{
Button btn = new Button("First button");
return btn;
}
public Button button2()
{
Button btn = new Button("Second button");
return btn;
}
public HBox hbox()
{
HBox hbox = new HBox(40,button1(), button2());
return hbox;
}
public Scene scene()
{
Scene scene = new Scene(hbox(), 840, 400);
return scene;
}
public static void main(String[] args)
{
launch(args);
}
}
Now this code does not work. Please help.
Please note: If any one have another idea to encapsulate eventHandlers then please mention it if you can because my goal is to define eventHandlers in one class and registering it in another class.
Thank you.

Of course it's not working, you are creating an instance of Button every call to button1() and button2(). The instance of button1 and button2 in the HBox are different instances from the one you added the event handler.
I definitely recommend not splitting like what you are doing. This kind of splitting makes it hard to troubleshoot problems, and you are creating new instances whenever you call any of those methods. Stick to what you are doing originally.

Related

Can you write two different Java FX scenes as two separate classes?

I'm a beginning Java programmer, finishing up the "Java 101" class at my local university. I'm also pushing myself to learn some extra topics on the side, including Java FX. I've worked through the Java FX tutorials on Oracle's website, plus sat through some YouTube videos, plus read "Java FX for Dummies" (which was the best book I could find for a beginner.) All of this material has taught me a lot of the basics, but some stuff that (should be) relatively simple escapes me.
For example: Let's say I have a Java FX program that uses multiple scenes on one stage. When the user clicks a "Switch!" button, the second scene is swapped out for the first. Easy. I can do all of this in one .java file, no problem. (See code below)
But my .java class file is getting really long and cumbersome to troubleshoot. It would be great if I could define/declare/initialize one scene as one class in one .java file and the second scene as another class in another .java file. This would make keeping track of the components of each scene much, much easier. The problem is, I can't figure out how to do this.
I'd imagine that you would write a Scene1.java class and then a Scene2.java class, and simply pass the stage object between the two when you want to switch scenes. But I can't find an example of how this is done, and all my attempts result in compiler errors or really scary runtime errors.
Does anyone know how this can be done? If so, what would I have to do to modify the SwitchScenes2() method below to create the new Scene2 object and pass it the stage?
Thanks! RAO
/*
JavaFXExample.java
*/
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.event.*;
import javafx.geometry.*;
public class JavaFXExample extends Application{
public static void main(String[] args){
launch(args);
}
Button btnSw1;
Button btnSw2;
Button btnClose;
HBox hbox1;
VBox vbox1;
Scene scene1;
Scene scene2;
Stage stage;
#Override public void start(Stage primaryStage){
btnSw1 = new Button("Switch Scenes!");
btnSw1.setOnAction(
e -> SwitchScenes2() );
btnSw2 = new Button("Switch back!");
btnSw2.setOnAction(
e -> SwitchScenes1() );
btnClose = new Button();
btnClose.setText("Close me!");
btnClose.setOnAction(e -> CloseWindowClick());
hbox1 = new HBox(10);
hbox1.getChildren().addAll(btnSw1);
vbox1 = new VBox(10);
vbox1.getChildren().addAll(btnSw2, btnClose);
scene1 = new Scene(hbox1, 300, 300);
scene2 = new Scene(vbox1, 200, 400);
stage = primaryStage;
stage.setScene(scene1);
stage.setTitle("Example App");
stage.show();
}
public void SwitchScenes1(){
stage.setScene(scene1);
}
public void SwitchScenes2(){
stage.setScene(scene2);
}
public void CloseWindowClick(){
stage.close();
}
}
Pete as I understand you wish to separate one big java file into small files,create Java classes in each class create method(function) that will return layout(HBox,VBox, Flowpane or ....)then in your main create an object of that Java class and use those methods to build on big application.
in my sample I made one main and one separated class with one function,just to show you how its works. In my main there is 2 lables, 2 buttons one layout and one object of the separated class, by clicking the buttons scenes will change
My Main:
public class SwitchSceneSample extends Application {
public static void main(String[] args) {
launch(args);
}
Stage window;
Scene scene1, scene2;
#Override
public void start(Stage primaryStage) throws Exception {
// I am using window as primaryStage
window = primaryStage;
// Label 1
Label label1 = new Label("Welcome to the first scene!");
// Label 2
Label label2 = new Label("This is second scene!");
// Button 1, by pressing this button primaryStage will be set as scene 2
Button button1 = new Button("Go to scene 2");
button1.setOnAction(e -> window.setScene(scene2));
// Button 2, by pressing this button primaryStage will be set as scene 1
Button button2 = new Button("Click to go scene 1");
button2.setOnAction(e -> window.setScene(scene1));
// Creating an object of the class'LayoutOne.java'
LayoutOne l1 = new LayoutOne();
// set my scene 1(by calling method called 'sceneView1()' from class 'LayoutOne.java')
scene1 = new Scene(l1.sceneView1(label1, button1), 200, 200);
// Set my scene 2 inside my main class
StackPane layout2 = new StackPane();
layout2.getChildren().addAll(label2, button2);
scene2 = new Scene(layout2, 600, 300);
// Making my
window.setScene(scene1);
window.setTitle("Scene Switch Sample");
window.show();
}
}
My Second Class:
public class LayoutOne {
public VBox sceneView1(Label label, Button button) {
// Layout 1 - children are laid out in vertical column
VBox layout1 = new VBox(20);
layout1.getChildren().addAll(label, button);
return layout1;
}
}
What you will want to do is create separate classes that both have functions to return the scene. From there you will want to initialize these classes and with a button call a function that will add data to these scene or create a new blank scene (as a quick way to "delete" the scene). But if you want a more professional way to switch between scenes like this you will want to check out the TabPane().
Scene1 scene1 = new Scene1();
Scene2 scene2 = new Scene2();
TabPane tabPane = new TabPane();
Tab tab1 = new Tab();
tab1.setContent(scene1);
tabPane.getTabs().add(tab1);
Tab tab2 = new Tab();
tab2.setContent(scene2);
tabPane.getTabs().add(tab2);
Create a Manager class that contain the main method & initialize the first screen. eg.
public class VMCSManager extends Application {
private Parent content;
private static VMCSManager instance;
public VMCSManager() {
instance=this;
}
public static void main(String[] args) {
launch(args);
}
public static VMCSManager getInstance() {
return instance;
}
#Override
public void start(Stage primaryStage) throws Exception {
initializePanel();
Scene scene = new Scene(content);
stageStyle(primaryStage);
primaryStage.setScene(scene);
primaryStage.show();
}
private void initializePanel() throws IOException{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("fxml/SimulatorDisplay.fxml"));
content = loader.load();
}
public void openCustomerPanel() throws IOException{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("fxml/CustomerDisplay.fxml"));
content = loader.load();
Scene scene = new Scene(content);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create main controller class for the first screen. eg;
public class SimulatorController implements Initializable{
#FXML
public void clickCustomer (ActionEvent event) throws IOException{
log.info("Starting Customer Panel");
VMCSManager.getInstance().openCustomerPanel();
}
#FXML
public void clickMaintainer(ActionEvent event) throws IOException{
log.info("Starting Maintainer Panel");
VMCSManager.getInstance().openMaintainerPanel();
}
}
Lastly Create the controller class for the specified screen. eg`
public class CustomerController extends SimulatorController{
#FXML
private Label brand1Lbl;
#FXML
private Label brand2Lbl;
#FXML
private Label brand3Lbl;
#FXML
private Label brand4Lbl;
#FXML
private Label brand5Lbl;
#FXML
private Label statusLbl1;
#FXML
private Label statusLbl2;
private static final Logger log=LoggerFactory.getLogger(CustomerController.class);
public CustomerController() {
context= new BuyingStateContext();
}
public void initialize(URL location, ResourceBundle resources) {
this.location = location;
this.rb = resources;
coinsValidityFlash.setVisible(false);
insertCoinTxt.setDisable(true);
brand1Btn.setStyle("-fx-background-color: #CACACA;");
brand2Btn.setStyle("-fx-background-color: #CACACA;");
brand3Btn.setStyle("-fx-background-color: #CACACA;");
brand4Btn.setStyle("-fx-background-color: #CACACA;");
brand5Btn.setStyle("-fx-background-color: #CACACA;");
populateVending();
}
.
.
.
}
`

How to embed JPanel into JavaFX pane for graph visualization

How can I add a swingNode to a specific pane using my controller class?
I'm trying to add a JPanel that loads a network graph created using the JUNG software library I'm not sure how to do it.
You can achieve what you want to do using SwingNode class. Here is an example code where a JButton (swing component) is added to a StackPane (JavaFX component):
public class SwingFx extends Application {
#Override
public void start(Stage stage) {
final SwingNode swingNode = new SwingNode();
createAndSetSwingContent(swingNode);
StackPane pane = new StackPane();
pane.getChildren().add(swingNode);
stage.setScene(new Scene(pane, 100, 50));
stage.show();
}
private void createAndSetSwingContent(final SwingNode swingNode) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
swingNode.setContent(new JButton("Click me!"));
}
});
}
public static void main(String[] args) {
launch(args);
}
}
Source: http://download.java.net/jdk8/jfxdocs/javafx/embed/swing/SwingNode.html

How to add a button to a panel using a method and access it from the main?

Let's say I want to create a method that adds a button to a StackPane. then I want to access to that button, for exemple I want to add an EventHandler from the main:
public class Test extends Application {
#Override
public void start(Stage primaryStage) throws ParseException {
StackPane root = new StackPane();
addButton(root);
// HERE I WANT TO ADD AN EVENT HANDLER TO b BUT I CANNOT ACCESS IT
// b.addEventHandler();
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public void addButton(StackPane sp){
final Button b = new Button("Test");
sp.getChildren().add(b);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Add event handler to the button when you creating the button
public void addButton(StackPane sp){
final Button b = new Button("Test");
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
//your logic
}});
sp.getChildren().add(b);
}
Since button is local to your addButton you need to have a reference to it. Return the reference of your button from addButton method and use it.
It would be better to use it this way
public Button addButton(){
//create Button
}
You can add this button to the StackPane in your start()
Alternatively,
This approach is not recommended.
You can get the Button out of the StackPane
Button button = (Button)root.getChildren().get(0);
N.B. Use this only if you are sure of the position of the Button
UPDATE
If you just want to separate your design from the action performed by the controls, JavaFX provides an eligant way to do it, using FXML.
It helps you to design the UI without any indulgence of the actions that they need to perform. And later, these FXML's can be binded to their actions through Controllers(Java Interface)
Scope the UI controls to the instance of the application class, instead of making them local to the method.
public class Test extends Application {
private Button b ;
public void start(Stage primaryStage) throws Exception {
StackPane root = new StackPane();
addButton(root);
b.addEventHandler(...);
// ...
}
private void addButton(Pane pane) {
b = new Button("Test");
pane.getChildren().add(b);
}
// ...
}
Or, if you really want to separate the layout from the event handling, do the layout in FXML and inject the controls into a controller class, which can be responsible for the event handlers.

Closing a modal window by clicking button

I have a window with a button. Clicking this button opens a modal window.
Now, I want to close this second window by clicking a button, but I can't figure out how.
public class StartMenu extends Application {
#Override
public void start(Stage primaryStage) {
final Button b = new Button("Go");
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
Stage stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
AnotherWindow aw = new AnotherWindow ();
aw.start(stage);
}
});
((Group) scene.getRoot()).getChildren().add(b);
primaryStage.setScene(scene);
primaryStage.show();
}}
 
 
public class AnotherWindow extends Application {
#Override
public void start(Stage primaryStage) {
final Button b = new Button("Back");
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
//Code to close window
}
});
((Group) scene.getRoot()).getChildren().add(b);
primaryStage.setScene(scene);
primaryStage.show();
}}
I found the following post by Krzysztof Sz. that helped me find the solution.
public class AnotherWindow extends Application {
#Override
public void start(Stage primaryStage) {
final Button b = new Button("Back");
b.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
((Button)t.getTarget()).getScene().getWindow().hide();
}
});
((Group) scene.getRoot()).getChildren().add(b);
primaryStage.setScene(scene);
primaryStage.show();
}}
 
It is the following piece of code that let's me close the current (modal) window when the button is clicked:
((Button)t.getTarget()).getScene().getWindow().hide();
You want to close a modal window from a click on a different window? If a modal window is visible, how will you get back to the other window?
You might want to use one window: when a button is clicked, hide all the controls in that window and make visible the information you wanted to have in your modal window, along with a button to click. When that button is clicked, reset the window to its' original state.
This just becomes an exercise in showing/hiding controls in a container.

Creating multiple buttons in java scene

I am attempting to create a scene with multiple buttons and I am having some issues.
What I have now is this:
public class Tester extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
Button btn1 = new Button();
btn1.setText("Start Game");
Button btn2 = new Button();
btn2.setText("Exit");
btn2.setOnAction(new EventHandler<ActionEvent>());
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Game Start");
}
});
Pane root = new Pane();
btn1.setLayoutX(500);
btn1.setLayoutY(530);
root.getChildren().add(btn1);
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.show();
I am trying to figure out what I need to do to have a second button. At the moment, I cant seem to have a second event handler.
Any help will be greatly appreciated.
Here is an update to your program to:
Define an action (display "Wumpus Hunt Complete!") for the second button.
Add the second button to the scene so that it can be seen.
The event handler for taking action for a button is an example of an anonymous inner class.
Sample Code:
Button btn1 = new Button();
btn1.setText("Start Game");
Button btn2 = new Button();
btn2.setText("Exit");
btn2.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Wumpus Hunt Complete!");
}
});
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
System.out.println("Game Start");
}
});
Pane root = new Pane();
btn1.setLayoutX(500);
btn1.setLayoutY(530);
root.getChildren().add(btn1);
btn2.setLayoutX(500);
btn2.setLayoutY(630);
root.getChildren().add(btn2);
primaryStage.setScene(new Scene(root, 1024, 768));
primaryStage.show();

Categories