JavaFX 示例,将动作(行为)设置为菜单项
菜单是向用户呈现的选项或命令的列表,通常菜单包含执行一些操作的项目。菜单的内容称为菜单项。
在 JavaFX 中,菜单由 javafx.scene.control.Menu 类表示,菜单项由 javafx.scene.control.MenuItem 类表示。
对 MenuItem 设置动作
MenuItem 类从 javafx.scene.control.ButtonBase 类继承了一个名为 onAction 的属性,该属性的类型为 ObjectProperty<EventHandler<ActionEvent>>。此属性代表每次按按钮时调用的动作。你可以使用 ** setOnAction()** 方法为该属性设置值。
将动作设置为项目菜单的一种方法是使用 OnAction() 方法。
示例
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.FileChooser.ExtensionFilter;
public class MenuActionExample extends Application {
public void start(Stage stage) {
//Creating a menu
Menu fileMenu = new Menu("File");
//Creating menu Items
MenuItem item1 = new MenuItem("Open Image");
MenuItem item2 = new MenuItem("Clear");
//Adding all the menu items to the menu
fileMenu.getItems().addAll(item1, item2);
//Creating a File chooser
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Image");
fileChooser.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*.*"));
//Creating the image view
ImageView imageView = new ImageView();
//Setting the image view parameters
imageView.setX(10);
imageView.setY(45);
imageView.setFitWidth(575);
imageView.setFitHeight(300);
imageView.setPreserveRatio(true);
//Handling the event of the Open Image
item1.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
//File file= fileChooser.showOpenDialog(stage);
File file = fileChooser.showOpenDialog(stage);
InputStream stream = new FileInputStream(file);
Image image = new Image(stream);
//Setting image to the image view
imageView.setImage(image);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
//Handling the event of the exit menu item
item2.setOnAction(event -> {
imageView.setImage(null);
});
//Creating a menu bar and adding menu to it.
MenuBar menuBar = new MenuBar(fileMenu);
menuBar.setTranslateX(3);
menuBar.setTranslateY(3);
//Setting the stage
Group root = new Group(menuBar, imageView);
Scene scene = new Scene(root, 595, 355, Color.BEIGE);
stage.setTitle("Menu Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP