我试图在 fxml 的帮助下为我的 borderpane 提供背景。 我有一个 View 和一个 Controller 。 我想你必须在fxml中说:borderPane.setBackground(new Background(myBI));
但我不知道怎么办。 使用 CSS 不是一种选择。
查看:
package application;
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{
Parent root = FXMLLoader.load(getClass().getResource("Layout_play.fxml"));
primaryStage.setTitle("Test");
primaryStage.setFullScreen(true);
primaryStage.setScene(new Scene(root, 1280, 720));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller :
public class PlayController {
@FXML
private Label label;
@FXML
private TextField textfield;
@FXML
private BackgroundImage myBI= new BackgroundImage(new Image("/Background.png",1280,720,false,true),
BackgroundRepeat.REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT,
BackgroundSize.DEFAULT);
@FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
label.setText("Hello " + textfield.getText());
}
}
和最后一个 fxml
<BorderPane fx:controller="application.PlayController" xmlns:fx="http://javafx.com/fxml"
prefHeight="200" prefWidth="320" >
<top>
<Text text="java-Buddy"/>
</top>
<left>
<Label text="Who are you?"/>
</left>
<center>
<TextField id="textfield" fx:id="textfield"/>
</center>
<right>
<Button id="button" text="Click Me!"
onAction="#handleButtonAction" fx:id="button"/>
</right>
<bottom>
<Label id="label" fx:id="label"/>
</bottom>
</BorderPane>
最佳答案
由于您无法使用 CSS,所以这不会很漂亮。
您已经将 BackgroundImage
定义为 myBI
,您可以使用它来设置元素的背景。
例如,为您的 BorderPane 指定一个 fx:id
<BorderPane fx:id="bPane" fx:controller="application.PlayController" xmlns:fx="http://javafx.com/fxml"
prefHeight="200" prefWidth="320" >
然后从那里添加
@FXML
private Borderpane bPane;
到您的 Controller 类。
最后,创建方法
@FXML
public void initialize(){
bPane.setBackground(new Background(myBI));
}
关于Javafx设置背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50509010/