import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.InputStream;
import java.util.ArrayList;
/**菜单栏的使用
* @ClassName MenuTest
* @Description TODO
* @Author Mr_X
* @Date 2022/4/25 16:36
* @Version 1.0
*
*/
public class MenuTest extends Application {
private ToggleGroup tg = new ToggleGroup();
private PropertyListener pl = new PropertyListener(tg);
private MenuItemsFactory mf = new MenuItemsFactory(tg);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
AnchorPane anchorPane = new AnchorPane();
MenuBar menuBar = new MenuBar();
pl.propertyListen();
for (Menu menu : mf.getMenus()) {
menuBar.getMenus().add(menu);
}
menuBar.setPrefWidth(900);
anchorPane.getChildren().add(menuBar);
Scene scene = new Scene(anchorPane);
primaryStage.setScene(scene);
primaryStage.setTitle(this.getClass().getSimpleName());
primaryStage.setHeight(600);
primaryStage.setWidth(900);
primaryStage.show();
anchorPane.widthProperty().addListener((observable, oldValue, newValue) -> menuBar.setPrefWidth(newValue.doubleValue()));
}
}
/**
* 处理事件最好放在一个另一个类中,避免代码臃肿。
*/
class PropertyListener{
private ToggleGroup tg;
private ObservableList toggles;
public PropertyListener() {
}
public PropertyListener(ToggleGroup tg) {
this.tg = tg;
toggles = tg.getToggles();
}
public void propertyListen(){
tg.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
FilteredList filtered = toggles.filtered(e -> e.isSelected());
for (Toggle toggle : filtered) {
RadioMenuItem rd = (RadioMenuItem) toggle;
System.out.println(rd.getText()+"选中!");
}
});
}
}
/**
* 返回带有MenuItems选项的List
效果:
javafxUI
代码涉及Lambda表达式、流 *** 作,可能需要一定的Java基础才能理解个别代码段。
推荐的JavaFX学习视频课程:JavaFX视频教程
评论列表(0条)