如何在 JavaFX 中向按钮添加图像(操作)?

javafxobject oriented programmingprogramming更新于 2025/4/14 15:37:17

一般来说,按钮 是用户界面应用程序中的控件,单击按钮时会执行相应的操作。您可以通过实例化 javafx.scene.control.Button 类来创建按钮。

向按钮添加图像

您可以使用 Button 类(继承自 javafx.scene.control.Labeled 类)的 setGraphic() 方法向按钮添加图形对象(节点)。此方法接受表示图形(图标)的 Node 类的对象。

向按钮添加图像 −

  • 创建一个 Image 对象,绕过所需图形的路径。

  • 使用图像对象创建一个 ImageView 对象。

  • 通过实例化 Button 类来创建按钮。

  • 最后,通过将 ImageView 对象作为参数传递,在按钮上调用 setGraphic() 方法。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ButtonGraphis extends Application {
   public void start(Stage stage) {
      //创建图形(图像)
      Image img = new Image("UIControls/logo.png");
      ImageView view = new ImageView(img);
      view.setFitHeight(80);
      view.setPreserveRatio(true);
      //创建按钮
      Button button = new Button();
      //设置按钮的位置
      button.setTranslateX(200);
      button.setTranslateY(25);
      //设置按钮的大小
      button.setPrefSize(80, 80);
      //为按钮设置图形
      button.setGraphic(view);
      //设置舞台
      Group root = new Group(button);
      Scene scene = new Scene(root, 595, 170, Color.BEIGE);
      stage.setTitle("Button Graphics");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出


相关文章