N
N
Neonoviiwolf2016-08-14 18:29:39
Java
Neonoviiwolf, 2016-08-14 18:29:39

How to add a button with code in javaFX?

I can’t solve the problem, in javaFX
I made a layout on fxml (I threw buttons, etc.) now I need to create other objects using the code (they are created during program execution) and as it turned out, if I used fxml, then Parent root no more root.getChildren().add. It turns out that either everything is written in code, or everything is done through fxml - even it is extremely inconvenient, how to solve the problem?
Error:(50, 13) java: getChildren() has protected access in javafx.scene.Parent

public class Main extends Application {


    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();

        Button btn = new Button();
        btn.setText("tttt");
        root.getChildren().add(btn); //getChildren - подчёркивается красным и при компиляции выдаёт ошибку

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0"
      prefWidth="800.0" xmlns="http://javafx.com/javafx/8.0.91" >
    <children>
    </children>
</Pane>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Kornachev, 2016-08-14
@Neonoviiwolf

Try like this:

Pane root = (Pane) FXMLLoader.load(getClass().getResource("sample.fxml"));

A
Adrenal1ne1, 2016-08-16
@Adrenal1ne1

In fxml you add:

<Button fx:id="refreshButton" mnemonicParsing="false"
                                        onAction="#handleButtonRefreshStatsAction" prefHeight="34.0"
                                        text="Refresh stats"/>

in the controller you write something like this:
@FXML
  Button refreshButton = new Button();

and you can add functionality to the button:
@FXML
  private void handleButtonRefreshStatsAction(ActionEvent event) {
    LOGGER.info("Pressed button Refresh Stats");

    Platform.runLater(new Runnable() {
      @Override
      public void run() {
        new Thread(new Runnable() {
          @Override
          public void run() {
            //DO SOMETHING HERE
          }
        }).start();
      }
    });
  }

Here ---> tutorials.jenkov.com/javafx/button.html a simple example of how to do it programmatically without FXML

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question