JavaFX使用MenuBar、Meun、MenuItem实现简单菜单窗口
程序员文章站
2024-02-03 20:58:04
...
一、环境
jdk8
二、模拟
三、代码
package xyz.hashdog.class26;
import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
* @author th
* @description: TODO
* @projectName hashdog
* @date 2020/2/1620:48
*/
public class Launch extends Application {
public static void main(String[] args) {
Application.launch(Launch.class,args);
}
@Override
public void start(Stage primaryStage) throws Exception {
AnchorPane an = new AnchorPane();
//创建menubar
MenuBar menuBar = new MenuBar();
Menu menu1 = new Menu("menu1");
Menu menu2 = new Menu("menu2");
Menu menu3 = new Menu("menu3");
Menu menu4 = new Menu("menu4");
//绑定menu
menuBar.getMenus().addAll(menu1,menu2,menu3,menu4);
//绑定一个图标
ImageView imageView = new ImageView("https://img-blog.csdnimg.cn/20200218180346114.png");
imageView.setFitWidth(16);
imageView.setFitHeight(16);
MenuItem item1 = new MenuItem("item1",imageView);
//设置item1的快捷键
item1.setAccelerator(KeyCombination.valueOf("ctrl+m"));
//item1的点击事件
item1.setOnAction(e->{
System.out.println("item1的点击事件");
});
MenuItem item2 = new MenuItem("item2");
MenuItem item3 = new MenuItem("item3");
MenuItem item4 = new MenuItem("item4");
MenuItem item5 = new MenuItem("item5");
//将menuitem放到menu
menu1.getItems().addAll(item1,item2,item3);
menu2.getItems().addAll(item4,item5);
an.getChildren().add(menuBar);
an.setStyle("-fx-background-color: deepskyblue");
Scene s= new Scene(an);
primaryStage.setScene(s);
primaryStage.setTitle("hashdog");
primaryStage.setWidth(500);
primaryStage.setHeight(300);
//设置窗口不可拉伸
primaryStage.setResizable(false);
primaryStage.show();
menuBar.setPrefWidth(primaryStage.getWidth());
}
}