繁体   English   中英

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

[英]buttons not showing in java fx application

我在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>

您在Main创建了一个新Scene ,但是从未在舞台上设置场景。

添加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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM