【发布时间】:2015-07-22 16:48:46
【问题描述】:
如果自定义 JavaFX 组件使用 FXML 作为视图,我如何正确扩展它以添加或修改其 GUI 组件?
作为示例场景,假设我使用以下方法创建自定义 JavaFX 组件:
SpecializedButton.java(控制器)
package test;
import java.io.IOException;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
public class SpecializedButton extends HBox
{
@FXML private Button button;
@FXML private Label label;
public SpecializedButton()
{
FXMLLoader loader = new FXMLLoader( getClass().getResource( "SpecializedButton.fxml" ) );
loader.setRoot( this );
loader.setController( this );
try {
loader.load();
} catch ( IOException e ) {
throw new RuntimeException( e );
}
}
// specialized methods for this specialized button
// ...
public void doSomething() {
button.setText( "Did something!" );
}
}
SpecializedButton.fxml(视图)
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.Button?>
<fx:root type="HBox" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<AnchorPane HBox.hgrow="ALWAYS">
<children>
<Label fx:id="label" text="Click to do something: " AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
<AnchorPane HBox.hgrow="ALWAYS">
<children>
<Button fx:id="button" onAction="#doSomething" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
</children>
</AnchorPane>
</children>
</fx:root>
MyApp.java
package test;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class MyApp extends Application
{
public static void main( String[] args )
{
launch( args );
}
public void start( Stage stage ) throws Exception
{
stage.setScene( new Scene( new SpecializedButton(), 300, 50 ) );
stage.show();
}
}
SpecializedButton 类加载 FXML 视图 (SpecializedButton.fxml) 并充当它的控制器。
SpecializedButton FXML 视图只是创建了一个 HBox,其中包含两个 AnchorPanes 以及一个标签和一个按钮,分别位于左侧和右侧。单击按钮时,它会调用 SpecializedButton 控制器类中的 doSomething()。
问题
通过此设置,我使用 FXML 将视图与应用程序逻辑分开。
但是,如果我想创建一个扩展 SpecializedButton 的新 HighlySpecializedButton 类,我也不知道如何“扩展”视图。
如果我想使用 SpecializedButton 视图,但要为 HighSpecializedButton 修改它,我必须将视图代码复制到新的 FXML 文件中,从而导致重复代码而不是正确继承。
如果我不使用 FXML,而是在 Java 类中创建 GUI 组件,扩展该类将使我能够正确继承和添加/修改超类中的组件。
我显然误解了有关 JavaFX 的一些非常重要的概念。
问题
在这种情况下,FXML 视图是否如此“愚蠢”,以至于每次我想从自定义组件继承时都必须创建一个全新的 FXML 视图?
或者,如果我误解了真正的问题,创建可扩展的自定义 JavaFX 组件(无论是否使用 FXML)的正确方法是什么?
如果有任何见解,我将不胜感激。提前致谢!
【问题讨论】:
-
这对我来说只是过度使用继承:考虑使用聚合代替。但是,要真正按照您想要的方式进行操作,您不能只使用
<fx:include>吗?或者,只需让“子类组件”的FXML引用<SpecializedButton>。 -
其他问题:您是否扩展过 html 文档? FXML 是一种可编写脚本的、基于 XML 的标记语言,用于构建 Java 对象图。这是来自这里的文档:docs.oracle.com/javase/8/javafx/api/javafx/fxml/doc-files/…
标签: java inheritance javafx fxml