按钮未显示在Java FX应用程序中

时间:2018-10-20 15:39:55

标签: java javafx fxml

我在sample.fxml中创建的按钮在编译后没有显示,我使用SceneBuilder创建了它们。我也尝试再次编译以进行重建。经过一切尝试,我变得束手无策,问题仍然出在他们身上。一点帮助会很好。

main.java

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

 public class Main extends Application {

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

            primaryStage.show();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

controller.java

package sample;

import javafx.event.ActionEvent;

import java.util.Random;

public class Controller {

    public void generateRandom(ActionEvent event)
    {
        Random rand = new Random();
        int number = rand.nextInt(50)+1;
        System.out.println(Integer.toString(number));
    }
}

sample.fxml

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="476.0" prefWidth="497.0" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
   <children>
      <Button fx:id="clickme" layoutX="192.0" layoutY="299.0" mnemonicParsing="false" onAction="#generateRandom" prefHeight="52.0" prefWidth="93.0" text="Click me" />
      <Label layoutX="155.0" layoutY="152.0" prefHeight="71.0" prefWidth="166.0" />
   </children>
</AnchorPane>

1 个答案:

答案 0 :(得分:3)

您在Scene中创建了一个新的Main,但从未在舞台上摆好场景。

在创建标题后添加primaryStage.setScene(scene);以将场景添加到舞台:

@Override
public void start(Stage primaryStage) throws Exception {
    try {
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        Scene scene = new Scene(root, 300, 275);
        primaryStage.setScene(scene);              // Add this line
        primaryStage.setTitle("Hello World");
        primaryStage.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}