手拉手JavaFX UI控件与springboot3+FX桌面开发(上):https://developer.aliyun.com/article/1431711
MenuBar菜单栏
MenuItem 菜单项、getItems获取项目、getMenus获取菜单、SeparatorMenuItem 分隔符菜单项、Separator分离器、MenuBar菜单栏、Items项目、checkMenuItem选中菜单项、CustomMenuItem自定义菜单项、
案例:
public void start(Stage stage) throws Exception { stage.setTitle("系统设置"); BorderPane borderPane =new BorderPane(); MenuBar menuBar =new MenuBar(); Menu create = new Menu("新建"); MenuItem project =new MenuItem("项目"); create.getItems().addAll(project); Menu system = new Menu("系统设置"); MenuItem aboutus =new MenuItem("关于我们"); MenuItem settings =new MenuItem("系统设置"); MenuItem exit =new MenuItem("退出"); exit.setOnAction(e->{ Platform.exit(); }); system.getItems().addAll(create,aboutus,settings,new SeparatorMenuItem(),exit); Menu goodsManage = new Menu("商品管理"); MenuItem g1 =new MenuItem("q1"); MenuItem g2 =new MenuItem("q2"); CheckMenuItem t1 =new CheckMenuItem("1"); CheckMenuItem t2 =new CheckMenuItem("2"); Slider slider =new Slider(); CustomMenuItem customMenuItem =new CustomMenuItem(slider); customMenuItem.setHideOnClick(false); goodsManage.getItems().addAll(g1,g2,t1,t2,customMenuItem); // menuBar.getMenus().addAll(system,goodsManage); borderPane.setTop(menuBar); Scene scene =new Scene(borderPane,500,400); stage.setScene(scene); stage.show(); }
案例2
public class MenuBarDemo extends Application{ TextArea textArea =new TextArea(); HBox hBox =new HBox(); public static void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { stage.setTitle("MenuBarDemo"); BorderPane borderPane =new BorderPane(); Button button =new Button("test"); MenuBar menuBar =new MenuBar(); Menu menu1= new Menu("menu1"); Menu menu2= new Menu("menu2"); Menu menu3= new Menu("系统设置"); MenuItem item1 =new MenuItem("t1"); MenuItem item2 =new MenuItem("t1"); MenuItem item3 =new MenuItem("t1"); MenuItem item4 =new MenuItem("t1"); MenuItem settings =new MenuItem("系统设置"); MenuItem exit =new MenuItem("退出"); exit.setOnAction(e->{ Platform.exit(); }); menu1.getItems().addAll(item1,item2); menu2.getItems().addAll(item3,item4); menu3.getItems().addAll(settings,exit); //设置快捷键 item1.setAccelerator(KeyCombination.valueOf("Enter")); item2.setAccelerator(KeyCombination.valueOf("ctrl+o")); item3.setAccelerator(KeyCombination.valueOf("ctrl+p")); menuBar.getMenus().addAll(menu1,menu2,menu3); menuBar.setPadding(new Insets(10)); menuBar.setPrefHeight(50); hBox.getChildren().addAll(button,menuBar); borderPane.setTop(hBox); hBox.setPrefHeight(50); borderPane.setCenter(textArea); Scene scene =new Scene(borderPane); stage.setScene(scene); stage.setHeight(400); stage.setWidth(300); stage.show(); menuBar.setPrefHeight(stage.getWidth()); //宽度监听事件 hBox.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { menuBar.setPrefWidth(newValue.doubleValue()-button.getWidth()); } }); item1.setOnAction((e)->{ System.out.println("111"); }); }
SeparatorMenuItem
Menu拆分(子菜单)
将Menu作为MenuItem,放到Menu子控件当中
RadioMenuItem单选多选菜单项
单选
ToggleGroup tg= new ToggleGroup(); RadioMenuItem rmi1 =new RadioMenuItem("RadioMenuItem1"); RadioMenuItem rmi2 =new RadioMenuItem("RadioMenuItem2"); rmi1.setToggleGroup(tg); rmi2.setToggleGroup(tg); //设置默认选中状态 rmi2.setSelected(true); menu2.getItems().addAll(rmi1,rmi2);
多选
禁用设置
//禁用设置
cmi3.setDisable(true);
CustomMenuItem 自定义菜单栏
public void start(Stage stage) throws Exception { stage.setTitle("CustomMenuBarDemo"); AnchorPane an =new AnchorPane(); MenuBar menuBar = new MenuBar(); Menu menu1 =new Menu("menu1"); Menu menu2 =new Menu("menu2"); Menu menu3 =new Menu("menu3"); MenuItem item1 =new MenuItem("item1"); MenuItem item2 =new MenuItem("item2"); MenuItem item3 =new MenuItem("item3"); //自定义菜单项 CustomMenuItem cmi1 =new CustomMenuItem(); Button button =new Button("button"); cmi1.setContent(button); CustomMenuItem cmi2 =new CustomMenuItem(); ProgressBar bar = new ProgressBar(0.6); cmi2.setContent(bar); menuBar.getMenus().addAll(menu1,menu2,menu3); menu1.getItems().addAll(item1,item2,item3,cmi1); an.getChildren().addAll(menuBar); Scene scene =new Scene(an); stage.setScene(scene); stage.setWidth(800); stage.setHeight(800); stage.setResizable(false); stage.show(); }
MenuButton菜单按钮
//MenuButton菜单按钮
MenuButton mb =new MenuButton("MenuButton"); MenuItem item4 =new MenuItem("item1"); MenuItem item5 =new MenuItem("item2"); MenuItem item6 =new MenuItem("item3"); mb.getItems().addAll(item4,item5,item6); AnchorPane.setTopAnchor(mb, 150.0);
SplitMenuButton
SplitMenuButton smButton = new SplitMenuButton(); smButton.setText("SplitMenuButton"); MenuItem item1s =new MenuItem("item1s"); MenuItem item2s =new MenuItem("item2s"); MenuItem item3s =new MenuItem("item3s"); smButton.getItems().addAll(item1s,item2s,item3s); AnchorPane.setTopAnchor(smButton, 300.0); an.getChildren().addAll(menuBar,mb,smButton);
ContextMenu
右击
//ContextMenu
Button textbutton = new Button("ContextMenu"); an.getChildren().add(textbutton); ContextMenu ctm =new ContextMenu(); MenuItem item4t =new MenuItem("item1t"); MenuItem item5t =new MenuItem("item2t"); MenuItem item6t =new MenuItem("item3t"); ctm.getItems().addAll(item4t,item5t,item6t); textbutton.setContextMenu(ctm); AnchorPane.setTopAnchor(textbutton, 200.0); textbutton.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { System.out.println("触发textbutton"); } });
Separator分隔符
separator分离器、prefHeightProperty首选高度属性、widthProperty宽度属性
public void start(Stage stage) throws Exception { stage.setTitle("separator"); BorderPane borderPane =new BorderPane(); MenuBar menuBar =new MenuBar(); Separator separator =new Separator(); separator.setMinWidth(100); separator.setMinHeight(50); borderPane.setTop(separator); Scene scene =new Scene(borderPane,500,400); stage.setScene(scene); stage.show(); }
其他
comboBox下拉框
combobox下拉列表框、combo联合体、Editable可编辑、
public class ComboBoxDemo extends Application { @Override public void start(Stage stage) throws Exception { stage.setTitle("combo"); BorderPane borderPane = new BorderPane(); TextArea textArea =new TextArea (); VBox vBox =new VBox(); vBox.setMinWidth(50); ComboBox<String> comboBox =new ComboBox<String>(); comboBox.getItems().addAll("A","B","C","D"); ComboBox<Rectangle> comboBox2 =new ComboBox<Rectangle>(); comboBox2.getItems().addAll( new Rectangle(10,10,Color.RED), new Rectangle(10,10,Color.YELLOW), new Rectangle(10,10,Color.ANTIQUEWHITE), new Rectangle(10,10,Color.AQUAMARINE) ); comboBox.setEditable(true); //设置提示 comboBox.setPromptText("请选择"); //设置默认值 comboBox.setValue("A"); //清空 //comboBox.setValue(null); //获取选中的值 comboBox.getValue(); System.out.println("获取选中的值: "+comboBox.getValue()); System.out.println("获取项: "+comboBox.getItems()); vBox.getChildren().addAll(comboBox,comboBox2); comboBox.valueProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue observable, String oldValue, String newValue) { System.out.println(observable); System.out.println(oldValue); System.out.println(newValue); textArea.setText("observable:"+observable+"\n oldValue:"+oldValue+"\n newValue:"+newValue); } }); // comboBox.setOnAction((e)->{ // textArea.setText("获取选中的值: "+comboBox.getValue()); // }); borderPane.setTop(menu11()); borderPane.setLeft(vBox); borderPane.setCenter(textArea); Scene scene =new Scene(borderPane,800,700); scene.setFill(Color.LIGHTBLUE); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } public MenuBar menu11(){ MenuBar menuBar =new MenuBar(); Menu create = new Menu("新建"); MenuItem project =new MenuItem("项目"); create.getItems().addAll(project); Menu system = new Menu("系统设置"); MenuItem aboutus =new MenuItem("关于我们"); MenuItem settings =new MenuItem("系统设置"); MenuItem exit =new MenuItem("退出"); exit.setOnAction(e->{ Platform.exit(); }); system.getItems().addAll(create,aboutus,settings,new SeparatorMenuItem(),exit); Menu goodsManage = new Menu("商品管理"); MenuItem g1 =new MenuItem("q1"); MenuItem g2 =new MenuItem("q2"); CheckMenuItem t1 =new CheckMenuItem("1"); CheckMenuItem t2 =new CheckMenuItem("2"); Slider slider =new Slider(); CustomMenuItem customMenuItem =new CustomMenuItem(slider); customMenuItem.setHideOnClick(false); goodsManage.getItems().addAll(g1,g2,t1,t2,customMenuItem); menuBar.getMenus().addAll(system,goodsManage); return menuBar; }; }
HTMLEditor富文本编辑器
PrefHeight预高度(PrefHeight)、
public class HTMLEditorDemo extends Application { @Override public void start(Stage stage) throws Exception { stage.setTitle(""); BorderPane borderPane =new BorderPane(); borderPane.setTop(getmenu11()); borderPane.setCenter(getBorderPane()); Button baocun =new Button("保存"); baocun.setOnAction((e)->{ System.out.println(); }); borderPane.setBottom(baocun); Scene scene =new Scene(borderPane,800,700); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } public HTMLEditor getBorderPane(){ HTMLEditor htmlEditor =new HTMLEditor(); htmlEditor.setPrefHeight(245); htmlEditor.setHtmlText("test"); htmlEditor.getHtmlText(); return htmlEditor; }
分页
public class PaginationDemo extends Application { private Pagination pagination; public int itemsPerPage() { return 8; } public VBox createPage(int pageIndex) { VBox vox = new VBox(5); int page = pageIndex * itemsPerPage(); for (int i = page; i < page + itemsPerPage(); i++) { VBox element = new VBox(); Hyperlink link = new Hyperlink("Item " + (i + 1)); link.setVisited(true); Label text = new Label("Search results\nfor " + link.getText()); element.getChildren().addAll(link, text); vox.getChildren().add(element); } //vox.getChildren().add(new Button("页码:"+pageIndex)); return vox; } @Override public void start(Stage stage) throws Exception { stage.setTitle("Pagination"); pagination = new Pagination(28, 0); pagination.setStyle("-fx-border-color:red;"); pagination.setPageFactory((Integer pageIndex) -> createPage(pageIndex)); BorderPane borderPane =new BorderPane(); borderPane.setBottom(pagination); Scene scene =new Scene(borderPane,600,500); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } }
listView列表
public void start(Stage stage) throws Exception { stage.setTitle("listView and observableList"); BorderPane borderPane =new BorderPane(); //写法1 ObservableList<String> date = FXCollections.observableArrayList(); ListView<String> listView = new ListView<String>(date); listView.setPrefSize(200,250); date.addAll("A","B","C","D","E"); listView.setItems(date); //获取选中的字符 listView.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String old_val, String new_val) -> { System.out.println(new_val); }); //写法2 ListView<Studentt> listView2 = new ListView<Studentt>(); ObservableList<Studentt> listData = FXCollections.observableArrayList(); listData.add(new Studentt(1,"张三")); listData.add(new Studentt(2,"李四")); listData.add(new Studentt(3,"小明")); listView2.setItems(listData); borderPane.setTop(listView); borderPane.setCenter(listView2); Scene scene =new Scene(borderPane,500,400); stage.setScene(scene); stage.show(); }
public class ListViewDemo extends Application { static class Student{ int id; String name; public Student() { } public Student(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } } @Override public void start(Stage stage) throws Exception { stage.setTitle("listView and observableList"); BorderPane borderPane =new BorderPane(); //写法1 ObservableList<String> date = FXCollections.observableArrayList(); ListView<String> listView = new ListView<String>(date); listView.setPrefSize(200,250); date.addAll("A","B","C","D","E"); listView.setItems(date); listView.getSelectionModel().selectedItemProperty().addListener( (ObservableValue<? extends String> ov, String old_val, String new_val) -> { System.out.println(new_val); }); //写法2 ListView<Student> listView2 = new ListView<Student>(); ObservableList<Student> listData = FXCollections.observableArrayList(); listData.add(new Student(1,"张三")); listData.add(new Student(2,"李四")); listData.add(new Student(3,"小明")); listView2.setItems(listData); //设置单元格生成器 listView2.setCellFactory(new Callback<ListView<Student>, ListCell<Student>>() { @Override public ListCell<Student> call(ListView<Student> param) { return new mylistcall(); } }); borderPane.setTop(listView); borderPane.setCenter(listView2); Scene scene =new Scene(borderPane,500,400); stage.setScene(scene); stage.show(); } //listCall负责显示列表项里每一个Cell的显示 static class mylistcall extends ListCell<Student>{ @Override protected void updateItem(Student item, boolean empty) { //FX框架要求必须先调用super.updateItem() super.updateItem(item, empty); //自己编写 if (item != null){ this.setText(item.id+" "+item.name); } } } public static void main(String[] args) { launch(); } }
表格
public void start(Stage stage) throws Exception { stage.setTitle("table"); //堆叠窗格 StackPane stackPane =new StackPane(); //表格视图 TableView tableView = new TableView(); tableView.setEditable(true); //列名称 TableColumn firstNameCol =new TableColumn("First name"); TableColumn lastNameCol =new TableColumn("last name"); TableColumn emailCol =new TableColumn("email"); //列可见 emailCol.setVisible(true); tableView.getColumns().addAll(firstNameCol,lastNameCol,emailCol); stackPane.getChildren().add(tableView); Scene scene =new Scene(stackPane,500,400); stage.setScene(scene); stage.show(); } import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Callback; public class Main extends Application { private Pagination pagination; @Override public void start(final Stage stage) throws Exception { pagination = new Pagination(10, 0); pagination.setStyle("-fx-border-color:red;"); pagination.setPageFactory((Integer pageIndex) -> createPage(pageIndex)); AnchorPane anchor = new AnchorPane(); AnchorPane.setTopAnchor(pagination, 10.0); AnchorPane.setRightAnchor(pagination, 10.0); AnchorPane.setBottomAnchor(pagination, 10.0); AnchorPane.setLeftAnchor(pagination, 10.0); anchor.getChildren().addAll(pagination); Scene scene = new Scene(anchor); stage.setScene(scene); stage.setTitle("PaginationSample"); stage.show(); } public int itemsPerPage() { return 8; } public VBox createPage(int pageIndex) { VBox box = new VBox(5); TableView<Person> table = new TableView<>(); ObservableList<Person> data = FXCollections.observableArrayList(new Person("A", "B"),new Person("D", "E")); table.setItems(data); TableColumn firstNameCol = new TableColumn("First Name"); firstNameCol.setMinWidth(100); firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName")); TableColumn lastNameCol = new TableColumn("Last Name"); lastNameCol.setMinWidth(100); lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName")); TableColumn<Person,String> operationCol = new TableColumn("操作"); lastNameCol.setMinWidth(100); operationCol.setCellFactory(new Callback<TableColumn<Person, String>, TableCell<Person, String>>() { @Override public TableCell<Person, String> call(TableColumn<Person, String> personStringTableColumn) { Button btn = new Button("删除"); TableCell<Person,String> cell = new TableCell<Person,String>(){ @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty) { setGraphic(null); setText(null); } else { btn.setOnAction(actionEvent->{ Person person = getTableView().getItems().get(getIndex()); System.out.println(person.firstName); System.out.println(person.lastName); System.out.println("删除...."); }); setGraphic(btn);//设置按钮 setText(null);//清空文本 } } }; return cell; } }); table.getColumns().addAll(firstNameCol, lastNameCol,operationCol); firstNameCol.setSortType(TableColumn.SortType.DESCENDING); lastNameCol.setSortable(false); box.setSpacing(5); box.setPadding(new Insets(10, 0, 0, 10)); box.getChildren().addAll(table); return box; } public static void main(String[] args) { launch(); } public static class Person { private String firstName; private String lastName; public Person(){} public Person(String firstName,String lastName ){ this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } }
TreeTableView树表视图
Expanded扩大、TreeTableView、TreeTableView 树表视图 、TreeTableColumn树表列、TreeItem树项目
public class TreeItemDemo extends Application { @Override public void start(Stage stage) throws Exception { stage.setTitle("TreeItemDemo"); BorderPane borderPane =new BorderPane(); //VBox vbox =new VBox(); TreeItem<String> t1 =new TreeItem<>("t1"); //集合已展开 t1.setExpanded(false); //创建树项目 TreeItem<String> t2 = new TreeItem<>("哈喽1"); TreeItem<String> t3 = new TreeItem<>("哈喽2"); TreeItem<String> t4 = new TreeItem<>("哈喽3"); //添加子项 t1.getChildren().setAll(t2,t3,t4); //创建树表列 TreeTableColumn<String, String> column = new TreeTableColumn<>("TreeTableColumn"); column.setPrefWidth(150); column.setCellValueFactory((TreeTableColumn.CellDataFeatures<String, String> p) -> new ReadOnlyStringWrapper( p.getValue().getValue())); TreeTableView<String> treeTableView = new TreeTableView<>(t1); treeTableView.getColumns().add(column); // vbox.getChildren().add(vbox); TextArea textArea =new TextArea(); borderPane.setTop(menu11()); borderPane.setLeft(treeTableView); borderPane.setCenter(textArea); Scene scene =new Scene(borderPane,500,400); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } public MenuBar menu11(){ MenuBar menuBar =new MenuBar(); Menu create = new Menu("新建"); MenuItem project =new MenuItem("项目"); create.getItems().addAll(project); Menu system = new Menu("系统设置"); MenuItem aboutus =new MenuItem("关于我们"); MenuItem settings =new MenuItem("系统设置"); MenuItem exit =new MenuItem("退出"); exit.setOnAction(e->{ Platform.exit(); }); system.getItems().addAll(create,aboutus,settings,new SeparatorMenuItem(),exit); Menu goodsManage = new Menu("商品管理"); MenuItem g1 =new MenuItem("q1"); MenuItem g2 =new MenuItem("q2"); CheckMenuItem t1 =new CheckMenuItem("1"); CheckMenuItem t2 =new CheckMenuItem("2"); Slider slider =new Slider(); CustomMenuItem customMenuItem =new CustomMenuItem(slider); customMenuItem.setHideOnClick(false); goodsManage.getItems().addAll(g1,g2,t1,t2,customMenuItem); menuBar.getMenus().addAll(system,goodsManage); return menuBar; }; }
图形
PieChart饼图、setLegendSide设置图例侧、setClockwise顺时针设置、setLabelsVisible集合标签可见、
Line Chart折线图、NumberAxis数字轴、Number of Month月份数、NumberAxis数字轴、XYChart XY图表
StackedAreaChart堆叠区域图表、series系列、
BubbleChart气泡图、extraValue 额外价值、BarChart条形图、StackedBarChart堆积条形图、
案例
import javafx.animation.Animation; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Side; import javafx.scene.Scene; import javafx.scene.chart.*; import javafx.scene.control.Label; import javafx.scene.input.MouseEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Duration; import java.util.Arrays; public class graphDemo extends Application { @Override public void start(Stage stage) throws Exception { stage.setTitle("graphDemo"); BorderPane borderPane =new BorderPane(); HBox hbox =new HBox(50); //饼图 PieChart pieChart = new PieChart(); // ObservableList<PieChart.Data> pieChartData = // FXCollections.observableArrayList( // new PieChart.Data("Grapefruit", 13), // new PieChart.Data("Oranges", 25), // new PieChart.Data("Plums", 10), // new PieChart.Data("Pears", 22), // new PieChart.Data("Apples", 30)); //添加数据 pieChart.setData(getChartData()); pieChart.setTitle("Title"); //设置图例侧 pieChart.setLegendSide(Side.BOTTOM); //顺时针设置 pieChart.setClockwise(true); //集合标签可见 pieChart.setLabelsVisible(true); //事件 VBox vBox1 =new VBox(new Label("坐标:")); Label label = new Label(); vBox1.getChildren().add(label); final Label caption = new Label(""); caption.setTextFill(Color.DARKORANGE); caption.setStyle("-fx-font: 24 arial;"); for (final PieChart.Data data : pieChart.getData()) { data.getNode().addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { caption.setTranslateX(e.getSceneX()); caption.setTranslateY(e.getSceneY()); label.setText("X:"+e.getSceneX()+" y:"+e.getSceneY()); caption.setText(String.valueOf(data.getPieValue()) + "%"); } }); } //折线图 //NumberAxis数字轴 NumberAxis xAxis = new NumberAxis(); NumberAxis yAxis = new NumberAxis(); xAxis.setLabel("月份数"); //创建LineChart折线图 LineChart<Number, Number> lineChart = new LineChart<Number, Number>( xAxis, yAxis); lineChart.setTitle("Line Chart 折线图"); //创建 XY图表 XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); series.setName("数据"); // 用数据填充序列 series.getData().add(new XYChart.Data<Number, Number>(1, 23)); series.getData().add(new XYChart.Data<Number, Number>(2, 114)); series.getData().add(new XYChart.Data<Number, Number>(3, 15)); series.getData().add(new XYChart.Data<Number, Number>(4, 124)); series.getData().add(new XYChart.Data<Number, Number>(5, 100)); series.getData().add(new XYChart.Data<Number, Number>(6, 170)); //将XY图表添加进LineChart折线图 lineChart.getData().add(series); //区域图 NumberAxis xAxis2 = new NumberAxis(1, 12, 1); NumberAxis yAxis2 = new NumberAxis(); xAxis2.setLabel("月分"); yAxis2.setLabel("数值"); //StackedAreaChart堆叠区域图表 StackedAreaChart<Number,Number> stackedAreaChart = new StackedAreaChart<Number,Number>(xAxis2,yAxis2); stackedAreaChart.setTitle("StackedAreaChart堆叠区域图表"); //XY图表 XYChart.Series<Number,Number> series1 = new XYChart.Series<Number,Number>(); //XY图表 XYChart.Series<Number,Number> series2 = new XYChart.Series<Number,Number>(); XYChart.Series<Number,Number> series3 = new XYChart.Series<Number,Number>(); series1.setName("XYChart.系列 1"); series2.setName("XYChart.系列 2"); series3.setName("XYChart.系列 3"); //添加数据 series1.getData().add(new XYChart.Data(1, 100)); series1.getData().add(new XYChart.Data(2, 200)); series1.getData().add(new XYChart.Data(10, 150)); series2.getData().add(new XYChart.Data(1, 50)); series2.getData().add(new XYChart.Data(2, 200)); series2.getData().add(new XYChart.Data(10, 260)); series3.getData().add(new XYChart.Data(1, 40)); series3.getData().add(new XYChart.Data(2, 100)); series3.getData().add(new XYChart.Data(10, 160)); //将系列12数据添加至StackedAreaChart堆叠区域图表 stackedAreaChart.getData().addAll(series1, series2,series3); //气泡图 //创建 XY图表 NumberAxis xAxisq = new NumberAxis(1, 53, 4); NumberAxis yAxisq = new NumberAxis(0, 80, 10); //BubbleChart创建气泡图 BubbleChart<Number,Number> blc = new BubbleChart<Number,Number>(xAxisq,yAxisq); xAxisq.setLabel("Week"); xAxisq.setTickLabelFill(Color.CHOCOLATE); xAxisq.setMinorTickCount(4); yAxisq.setLabel("Product Budget"); yAxisq.setTickLabelFill(Color.CHOCOLATE); yAxisq.setTickLabelGap(10); yAxisq.setTickLabelFormatter( new NumberAxis.DefaultFormatter(yAxisq,"$ ",null) ); blc.setTitle("Budget Monitoring"); XYChart.Series series4 = new XYChart.Series(); series4.setName("Product 1"); series4.getData().add(new XYChart.Data(3, 35, 2)); series4.getData().add(new XYChart.Data(12, 60, 1.8)); series4.getData().add(new XYChart.Data(15, 15, 7)); series4.getData().add(new XYChart.Data(22, 30, 2.5)); series4.getData().add(new XYChart.Data(28, 20, 1)); series4.getData().add(new XYChart.Data(35, 41, 5.5)); series4.getData().add(new XYChart.Data(42, 17, 9)); series4.getData().add(new XYChart.Data(49, 30, 1.8)); XYChart.Series series5 = new XYChart.Series(); series5.setName("Product 2"); series5.getData().add(new XYChart.Data(8, 15, 2)); series5.getData().add(new XYChart.Data(13, 23, 1)); series5.getData().add(new XYChart.Data(15, 45, 3)); series5.getData().add(new XYChart.Data(24, 30, 4.5)); series5.getData().add(new XYChart.Data(38, 78, 1)); series5.getData().add(new XYChart.Data(40, 41, 7.5)); series5.getData().add(new XYChart.Data(45, 57, 2)); series5.getData().add(new XYChart.Data(47, 23, 3.8)); //将数据导入BubbleChart气泡图 blc.getData().addAll(series1, series2); //条形图 CategoryAxis linexAxis = new CategoryAxis(); NumberAxis lineyAxis = new NumberAxis(); BarChart barChart = new BarChart(linexAxis,lineyAxis); linexAxis.setLabel("种类"); lineyAxis.setLabel("销量"); XYChart.Series dataSeries1 = new XYChart.Series(); dataSeries1.setName("2022"); dataSeries1.getData().add(new XYChart.Data("苹果", 567)); dataSeries1.getData().add(new XYChart.Data("李子" , 65)); dataSeries1.getData().add(new XYChart.Data("香蕉" , 23)); barChart.getData().add(dataSeries1); //水平线 String itemA = "A"; String itemB = "B"; String itemC = "F"; NumberAxis xAxisbar = new NumberAxis(); CategoryAxis yAxisbar = new CategoryAxis(); BarChart<Number, String> bc = new BarChart<Number, String>(xAxisbar, yAxisbar); bc.setTitle("Summary"); xAxisbar.setLabel("Value"); xAxisbar.setTickLabelRotation(90); yAxisbar.setLabel("Item"); XYChart.Series series11 = new XYChart.Series(); series11.setName("2003"); series11.getData().add(new XYChart.Data(2, itemA)); series11.getData().add(new XYChart.Data(20, itemB)); series11.getData().add(new XYChart.Data(10, itemC)); XYChart.Series series22 = new XYChart.Series(); series22.setName("2004"); series22.getData().add(new XYChart.Data(50, itemA)); series22.getData().add(new XYChart.Data(41, itemB)); series22.getData().add(new XYChart.Data(45, itemC)); XYChart.Series series33 = new XYChart.Series(); series33.setName("2005"); series33.getData().add(new XYChart.Data(45, itemA)); series33.getData().add(new XYChart.Data(44, itemB)); series33.getData().add(new XYChart.Data(18, itemC)); Timeline tl = new Timeline(); tl.getKeyFrames().add(new KeyFrame(Duration.millis(500), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent actionEvent) { for (XYChart.Series<Number, String> series : bc.getData()) { for (XYChart.Data<Number, String> data : series.getData()) { data.setXValue(Math.random() * 100); } } } })); tl.setCycleCount(Animation.INDEFINITE); tl.play(); bc.getData().addAll(series11, series22, series33); //StackedBarChart堆积条形图 CategoryAxis xAxiss = new CategoryAxis(); NumberAxis yAxiss = new NumberAxis(); xAxiss.setLabel("Month"); xAxiss.setCategories(FXCollections.<String> observableArrayList(Arrays.asList( "January", "February", "March"))); yAxiss.setLabel("Value"); //堆积条形图 StackedBarChart<String,Number> stackedBarChart = new StackedBarChart<String,Number>(xAxiss,yAxiss); stackedBarChart.setTitle("StackedBarChart"); XYChart.Series<String,Number> series1s = new XYChart.Series(); series1s.setName("XYChart.Series 1"); series1s.getData().add(new XYChart.Data("January", 100)); series1s.getData().add(new XYChart.Data("February", 200)); series1s.getData().add(new XYChart.Data("March", 50)); XYChart.Series<String,Number> series23 = new XYChart.Series(); series23.setName("XYChart.Series 2"); series23.getData().add(new XYChart.Data("January", 150)); series23.getData().add(new XYChart.Data("February", 100)); series23.getData().add(new XYChart.Data("March", 60)); stackedBarChart.getData().addAll(series1s, series23); // hbox.getChildren().addAll(blc,pieChart,caption,lineChart,stackedAreaChart,barChart,bc,stackedBarChart); borderPane.setCenter(hbox); borderPane.setBottom(vBox1); // Scene scene = new Scene(borderPane,1300,800); stage.setScene(scene); stage.show(); } public static void main(String[] args) {launch();} private ObservableList<PieChart.Data> getChartData() { ObservableList<PieChart.Data> answer = FXCollections.observableArrayList(); answer.addAll(new PieChart.Data("java", 17), new PieChart.Data("JavaFx",31), new PieChart.Data("Swing",10), new PieChart.Data("IO",20), new PieChart.Data("NIO",21) ); return answer; } }
鼠标事件
在MouseEvent对象里,能得到以下信息
Event.getButton() 按钮(左、中、右)
Event.getClickCount() 移动(0),单击(1),双击(2)
Event.getX()获取窗口坐标
Event.getSceneX()获取屏幕坐标
setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { } });
案例
setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { onclickMouse(event); } // Event.getButton() 按钮(左、中、右) // Event.getClickCount() 移动(0),单击(1),双击(2) // Event.getX()获取窗口坐标 // Event.getSceneX()获取屏幕坐标 private void onclickMouse(MouseEvent event) { if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() ==2){textArea.appendText("双击"+"\n");} //if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() ==1){textArea.appendText("单击"+"\n");} } });
阅读器
Suffix后缀、
// 取得文件名 fileName = file.getName(); firstName = getFileFirstName(fileName); // 根据文件后缀来判断文件的类型 String suffix = getFileSuffix(fileName); type = BAD_FORMAT; if (contains(txtTypes, suffix)) type = TEXT; else if (contains(imageTypes, suffix)) type = IMAGE;
Alert提示对话框
import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class dialogueDemo extends Application { Label label =new Label(); TextField username =new TextField(); PasswordField password = new PasswordField(); Button login = new Button("登录"); @Override public void start(Stage stage) throws Exception { stage.setTitle("AlertDemo"); try { label.setText("欢迎登入系统"); BorderPane borderPane = new BorderPane(); VBox vbox = new VBox(); vbox.setAlignment(Pos.CENTER); vbox.getChildren().addAll(label,username, password, login); borderPane.setCenter(vbox); //设置提示文字 username.setPromptText("用户名"); password.setPromptText("密码"); Scene scene =new Scene(borderPane,500,400); stage.setScene(scene); stage.show(); login.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { dologin(); } }); }catch (Exception e){ e.printStackTrace(); } } public void dologin() { String user1 =username.getText(); String pass1 = password.getText(); if (! user1.equals("qgs") || !pass1.equals("123456")){ System.out.println("用户名/密码错误"); Alert waring = new Alert(Alert.AlertType.WARNING); waring.setHeaderText("用户名/密码出错"); waring.setContentText("。。"); //showAndWait();当输入的焦点在对话框里,后面的界面无法输入(不往下走,知道对话框关闭) waring.showAndWait(); }else { Alert waring = new Alert(Alert.AlertType.INFORMATION); waring.setHeaderText("成功"); waring.setContentText("欢迎进入系统"); waring.showAndWait(); } } public static void main(String[] args) {launch();} }
详细说明
Alert waring = new Alert(Alert.AlertType.WARNING);
确认警报:CONFIRMATION警报类型将“警报”对话框配置为以某种方式显示,以表明该对话框的内容正在寻求用户的确认。
警告提示:WARNING警报类型将“警报”对话框配置为以某种方式显示,表明该对话框的内容向用户警告某些事实或操作。
无警报:NONE警报类型的作用是不在警报中设置任何默认属性。
信息警报:INFORMATION警报类型将Alert对话框配置为以某种方式显示,表明该对话框的内容正在通知用户一条信息。
错误警报:ERROR警报类型将Alert对话框配置为以某种表明出现问题的方式出现。
自定义对话框
TextInputDialog文本输入框
ChoiceDialog选择对话框
Dialog对话框
Dialog:用于显示一个自定义的对话框
Dialog->DialogPane->(Node + Buttons)
ButtonType 标准化按钮
显示对话框,并等待关闭 showAndWai
当对话框关闭时将返回一个结果
Optional result = dlg.showAndWait();
If(result.isPresent()) //是否有返回值
result.get().getButtonData() == ButtonBar.ButtonData.OK_DONE 看用户点了那个按钮
案例
import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.util.Optional; public class dialogpaneDemo extends Application { static TextArea textArea =new TextArea(); TextField id =new TextField(); TextField name =new TextField(); TextField phone =new TextField(); @Override public void start(Stage stage) throws Exception { stage.setTitle("dialogpaneDemo"); try{ BorderPane borderPane =new BorderPane(); borderPane.setCenter(textArea); Button add =new Button("添加学生"); borderPane.setTop(add); add.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { onAdd(); } }); Scene scene =new Scene(borderPane,400,400); stage.setScene(scene); }catch (Exception e){ e.printStackTrace(); } stage.show(); } //对话框 private void onAdd() { VBox Content =new VBox(); id.setPromptText("学号"); name.setPromptText("姓名"); phone.setPromptText("手机号"); Content.setSpacing(10); Content.getChildren().addAll(id,name,phone); DialogPane dialogPane =new DialogPane(); //将VBox放置到dialogPane dialogPane.setContent(Content); //添加按钮 ButtonType ok =new ButtonType("确定", ButtonBar.ButtonData.OK_DONE); dialogPane.getButtonTypes().add(ok); //创建对话框 Dialog<ButtonType> dlg =new Dialog<>(); //将dialogPane放置到Dialog dlg.setDialogPane(dialogPane); dlg.setTitle("学生信息"); Optional<ButtonType> result =dlg.showAndWait(); System.out.println(result.isPresent()); if (result.isPresent() && result.get().getButtonData() == ButtonBar.ButtonData.OK_DONE ){ int _id = Integer.parseInt(id.getText()); String _name =name.getText(); String _phone = phone.getText(); textArea.appendText("学号:"+_id+"姓名:"+_name+"手机号:"+_phone+"\n"); } } public static void main(String[] args) { launch(); } }
FileChooser文件对话框
public class FileChooserDemo2 extends Application { Stage stage; HTMLEditor htmlEditor =new HTMLEditor(); TextArea textArea =new TextArea(); @Override public void start(Stage stage) throws Exception { this.stage =stage; stage.setTitle("FileChooserDemo2"); BorderPane borderPane =new BorderPane(); HBox hBox=new HBox(); Button fileOpen = new Button("打开"); Button fileSave = new Button("保存"); hBox.getChildren().addAll(fileOpen,fileSave); VBox vbox =new VBox(); vbox.setMaxWidth(200); vbox.getChildren().addAll(textArea); //打开文件 fileOpen.setOnAction((e)->{ openfile(); }); //保存文件 fileSave.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Savefile(); } }); borderPane.setTop(hBox); borderPane.setLeft(vbox); borderPane.setCenter(htmlEditor); Scene scene =new Scene(borderPane); stage.setScene(scene); stage.show(); } private void openfile() { FileChooser fileChooser =new FileChooser(); // //getInitialDirectory() fileChooser.setTitle("打开文件"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Text File","*.txt") ,new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif") ,new FileChooser.ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac") ,new FileChooser.ExtensionFilter("All Files", "*.*") ); File file =fileChooser.showOpenDialog(stage); textArea.appendText(file.getPath()); if (file !=null){ try { String text =TextFileUtils.read(file,"utf-8"); htmlEditor.setHtmlText(text); }catch (Exception c){ c.printStackTrace(); } }else { return; } } private void Savefile() { FileChooser fileChooser =new FileChooser(); fileChooser.setTitle("保存文件"); //设置扩展过滤器来确定在文件选择器中打开哪些文件,getExtensionFilters获取扩展筛选器 fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text File","*.txt")); File file =fileChooser.showSaveDialog(stage); if (file !=null){ try { String text =htmlEditor.getHtmlText(); TextFileUtils.write(file,text,"utf-8"); }catch (Exception e){ e.printStackTrace(); } }else { return; } } public static void main(String[] args) { launch(); } }
2D图形绘制Canvas
在javafx里使用Canvas对象进行2D绘制
创建Canvas(画布)
在Canvas上绘制 点、线、几何图形、图片
import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.ImageView; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Stage; public class CanvasDemo extends Application { @Override public void start(Stage stage) throws Exception { try{ Pane pane =new Pane(); Canvas canvas =new Canvas(300,300); pane.getChildren().add(canvas); //绘制 draw(canvas); Scene scene = new Scene(pane,400,400, Color.LIGHTBLUE); scene.getStylesheets().addAll(this.getClass().getResource("style.css").toExternalForm()); stage.setScene(scene); stage.show(); }catch (Exception e){ e.printStackTrace(); } } private void draw(Canvas canvas) { double w =canvas.getWidth(); double h =canvas.getHeight(); GraphicsContext gc=canvas.getGraphicsContext2D(); gc.setFill(Color.PAPAYAWHIP); gc.fillRect(0,0,200,100); } public static void main(String[] args) { launch(); } } 颜色定义 RGB / YVU / HSB RGB方式是最常见的方式 (255,0,0)红色、(0,0,0)黑色 绘制文字 stroskText()绘制线条 fillText填充 gc.setFont(new Font("微软雅黑",40)); gc.fillText("hello world",200,200); //文字基线(顶部对齐) gc.setTextBaseline(VPos.TOP); //水平方向对齐 gc.setTextAlign(TextAlignment.CENTER); gc.fillOval(0,0,200,200);//椭圆
手拉手JavaFX UI控件与springboot3+FX桌面开发(下):https://developer.aliyun.com/article/1431716