如何在 JavaFX 中向按鈕新增影像(操作)?
按鈕控制元件在使用者介面應用程式中,一般來說,單擊按鈕時它會執行相應的操作。你可以透過例項化 javafx.scene.control.Button 類建立按鈕。
向按鈕新增影像
可以使用Button 類的 setGraphic() 方法(繼承自javafx.scene.control.Labeled 類)向按鈕新增圖形物件(節點)。該方法接受表示圖形(圖示)的 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) { //Creating a graphic (image) Image img = new Image("UIControls/logo.png"); ImageView view = new ImageView(img); view.setFitHeight(80); view.setPreserveRatio(true); //Creating a Button Button button = new Button(); //Setting the location of the button button.setTranslateX(200); button.setTranslateY(25); //Setting the size of the button button.setPrefSize(80, 80); //Setting a graphic to the button button.setGraphic(view); //Setting the stage 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); } }
輸出
廣告