手拉手JavaFX UI控件与springboot3+FX桌面开发

目录

javaFx文本

javaFX颜色

字体

Label标签

Button按钮

     //按钮单击事件

鼠标、键盘事件

//(鼠标)双击事件

     //键盘事件

单选按钮RadioButton

快捷键、键盘事件

CheckBox复选框

ChoiceBox选择框

Text文本

TextField(输入框)、TextArea文本域

//过滤 (传入一个参数(过滤后)返回一个参数)

//过滤2

案例

password密码字段

Hyperlink超链接

ProgressBar进度条、ProgressIndicator进度指示器

ScrollBar滚动条

DatePicker日历选择器

ColorPicker颜色选择器

FileChooser文件选择器

SeparatorMenuItem

RadioMenuItem单选多选菜单项

单选

多选

禁用设置

CustomMenuItem 自定义菜单栏

SplitMenuButton

ContextMenu

Separator分隔符

comboBox下拉框

HTMLEditor富文本编辑器

分页

listView列表

表格

TreeTableView树表视图

图形

案例

鼠标事件

阅读器

Alert提示对话框

自定义对话框

案例

FileChooser文件对话框

2D图形绘制Canvas

drawImage绘制图片

样式单CSS

图片背景

SceneBuilder可视化设计

Eclipse添加javafx组件

Eclpise-jdk11-javaFx

媒体播放器

Eclpise应用程序的发布

IEDA 应用程序的发布

登入窗口+小知识点

Springboot3+JavaFX


javaFx文本

Text text = new Text("测试");

text.setFont(Font.font("宋体",10));

//设置大小

text.setFont(Font.font(20));borderPane.getChildren().add(text);

//设置提示

Tooltip toop =new Tooltip();test.setTooltip();

javaFX颜色

Opacity不透明度、

案例:

public class Color_01 extends Application {public static void main(String[] args) {launch();}@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("Drawing Text");//布局Group root = new Group();//平台Scene scene = new Scene(root, 300, 250, Color.WHITE);int x = 100;int y = 100;int red = 30;int green = 40;int blue = 100;Text text = new Text(x, y, "JavaFX 2.0");text.setFont(Font.font("宋体",30));//0-1之间//text.setFill(new Color(0.7,0.4,0.7,1.0));//web颜色text.setFill(Color.web("#000000"));//text.setFill(Color.RED);//text.setFill(Color.rgb(red, green, blue, .99));text.setRotate(5);root.getChildren().add(text);stage.setScene(scene);stage.show();}}

字体

FontWeight 字体粗细、FontPosture 字体姿态、Posture姿势

public void start(Stage stage) throws Exception {stage.setTitle("Fontdemo");BorderPane borderPane = new BorderPane();Text text = new Text("this a the  text");//加粗,斜体text.setFont(Font.font("宋体", FontWeight.BOLD, FontPosture.ITALIC,24));borderPane.setTop(text);Scene scene = new Scene(borderPane,600,300);stage.setScene(scene);stage.show();}

列出已安装的字体系列和名称

List<String> fontFamilies = Font.getFamilies();List<String> fontNames    = Font.getFontNames();for(String item : fontFamilies) {System.out.println(item);}for(String item : fontNames) {System.out.println(item);}

Label标签

Rotat旋转、Entered进入、Pressed按下

public void start(Stage stage) throws Exception {stage.setTitle("labeldemo");Group group =new Group();GridPane gridPane =new GridPane();gridPane.setPadding(new Insets(5));gridPane.setHgap(10);gridPane.setVgap(10);//        Label label1 =new Label("test");//        Label label2 =new Label("test");//        Label label3 =new Label("test");//        Label label4 =new Label("test");//        gridPane.add(label1,0,0);//        gridPane.add(label2,1,0);//        gridPane.add(label3,0,1);//        gridPane.add(label4,1,1);Label label5 = new Label();Label label6 = new Label("Name");//旋转label6.setRotate(60);Image image = new Image("中国风1.JPG");Label label7 = new Label("Name", new ImageView(image));//label6.setGraphic(new ImageView(image));//设置字体颜色//label6.setTextFill(Color.web("#0076a3"));label6.setTextFill(Color.RED);//        Label label8 = new Label("dgiueagfuoaebgipeahgaeop");//        //包装标签:自动换行//        label8.setWrapText(true);//label事件label7.setOnMouseClicked(e-> System.out.println("鼠标点击了"));label7.setOnMouseMoved(e-> System.out.println("鼠标移动了"));label7.setOnMouseEntered(e-> System.out.println("鼠标进入了"));label7.setOnKeyPressed(e-> System.out.println("鼠标按下了"));group.getChildren().addAll(gridPane,label7,label5,label6);Scene scene = new Scene(group,600,500);stage.setScene(scene);stage.show();}label.setOnMouseClicked(new EventHandler<MouseEvent>() {@Overridepublic void handle(MouseEvent event) {System.out.println(" 鼠标点击名:" + event.getButton().name());textField.setText(" 鼠标点击名:" + event.getButton().name());if (event.getClickCount()==2&& event.getButton().name().equals(MouseButton.PRIMARY.name())) {//获取鼠标点击名System.out.println(event.getButton().name());System.out.println("鼠标双击");textField.setText(" 鼠标左双击" );}if (event.getClickCount()==2&& event.getButton().name().equals(MouseButton.SECONDARY.name())) {//获取鼠标点击名System.out.println(event.getButton().name());System.out.println("鼠标双击");textField.setText(" 鼠标右双击" );}}});

Button按钮

//设置button标题Button button =new Button("按钮");button.setText("按钮");button.setTextFill(Paint.valueOf("#cdcdcd"));//设置位置button.setLayoutX(50);button.setLayoutY(50);//设置按钮大小button.setPrefHeight(200);button.setPrefWidth(200);//设置字体button.setFont(Font.font("宋体",40));//设置背景填充//   BackgroundFill bgf =new BackgroundFill(Paint.valueOf("#0078d7"), new CornerRadii(20), new Insets(10));//   Background bg =new Background(bgf);//   button.setBackground(bg);//设置边框                             颜色                     边框风格BorderStroke bos =new BorderStroke(Paint.valueOf("#cdcdcd"), BorderStrokeStyle.SOLID, new CornerRadii(20), new BorderWidths(5));Border bo =new Border(bos);button.setBorder(bo);//设置背景,填充2(推荐)button.setStyle("-fx-background-color:#0078d7;"+"-fx-background-radius:20;"+"-fx-Text-fill:#fe993f;");

    

     //按钮单击事件

//   button.setOnAction(new EventHandler<ActionEvent>() {

//     

//      @Override

//      public void handle(ActionEvent event) {

//         System.out.println("被点击了");

//      }

//   });   

  //按钮单击事件写法2button.setOnAction((e)->{System.out.println("被点击了2");});

案例

public void start(Stage stage) throws Exception {stage.setTitle("buttonDemo");HBox hbox = new HBox(50);//图片按钮ImageView imageView =new ImageView(new Image("中国风1.JPG"));Button imgbutton =new Button("设置",imageView);//imgbutton.setStyle("-fx-background-image:url(中国风1.JPG);-fx-font-size:20");imgbutton.setFont(Font.font("宋体",30));Text text =new Text();text.setFont(Font.font("宋体",30));Button btn = new Button();btn.setText("Say 'Hello World'");btn.setOnAction((e)->{text.setText("按钮被点击了");});//单选按钮ToggleGroup group = new ToggleGroup();RadioButton button1 = new RadioButton("单选按钮1");button1.setToggleGroup(group);button1.setSelected(true);RadioButton button2 = new RadioButton("单选按钮2");button2.setToggleGroup(group);//切换按钮ToggleGroup group1 =new ToggleGroup();ToggleButton tb1 =new ToggleButton("切换按钮1");tb1.setToggleGroup(group1);ToggleButton tb2 =new ToggleButton("切换按钮2");tb2.setToggleGroup(group1);hbox.getChildren().addAll(btn,text,imgbutton,button1,button2,tb1,tb2);Scene scene =new Scene(hbox,600,500);stage.setScene(scene);stage.show();}

鼠标、键盘事件

//(鼠标)双击事件

    

button.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {@Overridepublic void handle(MouseEvent event) {//System.out.println(event.getButton().name());//System.out.println("鼠标单击");//双击+左键if (event.getClickCount()==2&& event.getButton().name().equals(MouseButton.PRIMARY.name())) {//获取鼠标点击名System.out.println(event.getButton().name());System.out.println("鼠标双击");//event.getButton().name().equals(MouseButton.)}}});

    

     //键盘事件

    
   

  //按下button.setOnKeyPressed(new EventHandler<KeyEvent>() {@Overridepublic void handle(KeyEvent event) {if (event.getCode().getName().equals(KeyCode.A.getName())) {System.out.println("按下"+event.getCode().getName());}}});//释放button.setOnKeyReleased(new EventHandler<KeyEvent>() {@Overridepublic void handle(KeyEvent event) {if (event.getCode().getName().equals(KeyCode.A.getName())) {System.out.println("释放"+event.getCode().getName());}}});

   

单选按钮RadioButton

public class RadioButtonDemo extends Application{public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("单选按钮RadioButtonDemo");AnchorPane an =new AnchorPane();an.setStyle("-fx-background-color: #ffffff");HBox hbox =new HBox();ToggleGroup tg =new ToggleGroup();//单选按钮RadioButton r1 =new RadioButton("r1");RadioButton r2 =new RadioButton("r2");RadioButton r3 =new RadioButton("r3");r1.setToggleGroup(tg);r2.setToggleGroup(tg);r3.setToggleGroup(tg);//默认选择//r1.setSelected(true);tg.selectToggle(r1);hbox.getChildren().addAll(r1,r2,r3);AnchorPane.setTopAnchor(hbox, 100.0);AnchorPane.setLeftAnchor(hbox, 100.0);an.getChildren().add(hbox);Scene scene =new Scene(an);stage.setScene(scene);stage.setWidth(800);stage.setHeight(800);stage.show();//RadioButton选择监听r1.selectedProperty().addListener(new ChangeListener<Boolean>() {@Overridepublic void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {System.out.println("当前是否选中:"+newValue);}});//ToggleGroup监听tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {@Overridepublic void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {RadioButton r =(RadioButton)newValue;System.out.println("当前是否选中:"+r.getText());}});}}

快捷键、键盘事件

package javafx;import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.control.TextField;import javafx.scene.input.KeyCharacterCombination;import javafx.scene.input.KeyCode;import javafx.scene.input.KeyCodeCombination;import javafx.scene.input.KeyCombination;import javafx.scene.input.Mnemonic;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class Shortcutkey extends Application{private int i;TextField textField =new TextField();TextField textField2 =new TextField();public int getI() {return i;}public void setI(int i) {this.i = i;}public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("Shortcut key");VBox hBox =new VBox();Button b1 =new Button("button");Button t =new Button("t2");hBox.getChildren().addAll(b1,textField,textField2,t);b1.setOnAction((e)->{setI(getI()+1);textField.setText("被点击了: "+getI());});t.setOnAction((e)->{diaoyong();});Scene scene =new Scene(hBox,400,500);//快捷键第一种方式   ctrl+Alt+C  KeyCombination kc1 =new KeyCodeCombination(KeyCode.C,KeyCodeCombination.CONTROL_DOWN  , KeyCodeCombination.ALT_DOWN);Mnemonic mnemonic1 =new Mnemonic(b1, kc1);//触发b1事件scene.addMnemonic(mnemonic1);//快捷键第二种方式 ctrl+OKeyCombination kc2 =new KeyCharacterCombination("O",KeyCodeCombination.CONTROL_DOWN);Mnemonic mnemonic2 =new Mnemonic(b1, kc2);//触发b1事件scene.addMnemonic(mnemonic2);//ctrl+Y(推荐这种方式)KeyCombination kc3 =new KeyCodeCombination(KeyCode.Y,KeyCombination.SHORTCUT_DOWN);scene.getAccelerators().put(kc3, new Runnable() {@Overridepublic void run() {System.out.println("run方法");System.out.println("当前线程名:"+Thread.currentThread().getName());//调用方法//diaoyong();//调用t事件t.fire();         }});stage.setScene(scene);stage.show();}private void diaoyong() {setI(getI()+1);textField2.setText("ctrl+Y  :"+getI());}}

//第五种    

KeyCombination kc5 = KeyCombination.valueOf("Enter");//KeyCombination kc5 = KeyCombination.valueOf("alt +k");Mnemonic mnemonic1 =new Mnemonic(hBox, kc5);//触发hBox事件scene.addMnemonic(mnemonic1);

CheckBox复选框

public void start(Stage stage) throws Exception {stage.setTitle("checkboxdemo");VBox vbox = new VBox();stage.setWidth(300);stage.setHeight(150);CheckBox cb1 = new CheckBox("checkBox1");CheckBox cb2 = new CheckBox("checkBox2");CheckBox cb3 = new CheckBox("checkBox3");//默认选择cb1.setSelected(true);//不确定的cb2.setIndeterminate(true);//允许不确定cb3.setAllowIndeterminate(true);//监听事件cb1.selectedProperty().addListener(new ChangeListener<Boolean>() {public void changed(ObservableValue<? extends Boolean> ov,Boolean old_val, Boolean new_val) {System.out.println(cb1.isSelected());}});vbox.getChildren().addAll(cb1,cb2,cb3);Scene scene = new Scene(vbox);stage.setWidth(500);stage.setHeight(500);stage.setScene(scene);stage.show();}

ChoiceBox选择框

SelectionModel 选择模型

selectedIndexProperty 所选索引属性

addListener 添加侦听器

ObservableList可观察列表

Collections收藏

案例1

public void start(Stage stage) throws Exception {stage.setTitle("ChoioceDemo");HBox hbox =new HBox(10);hbox.setAlignment(Pos.CENTER);Label label = new Label();String[] greetings =new String[]{"男","女"};ChoiceBox<String> cd =new ChoiceBox<String>(FXCollections.observableArrayList("男","女"));//得到每次选中的下标cd.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {@Overridepublic void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {//被选中的下标oldValue oldValue//被选中新的下标newValue newValueSystem.out.println("原来的值"+oldValue.intValue());System.out.println("新选中的值"+newValue.intValue());label.setText(greetings[newValue.intValue()]);}});//设置默认值cd.setValue("男");//hbox.getChildren().addAll(cd);hbox.getChildren().addAll(cd,label);Scene scene =new Scene(hbox,600,500);stage.setScene(scene);scene.setFill(Color.LIGHTBLUE);stage.show();}

案例2

public void start(Stage stage) throws Exception {ObservableList cursors = FXCollections.observableArrayList(Cursor.DEFAULT,Cursor.CROSSHAIR,Cursor.WAIT,Cursor.TEXT,Cursor.HAND,Cursor.MOVE,Cursor.N_RESIZE,Cursor.NE_RESIZE,Cursor.E_RESIZE,Cursor.SE_RESIZE,Cursor.S_RESIZE,Cursor.SW_RESIZE,Cursor.W_RESIZE,Cursor.NW_RESIZE,Cursor.NONE,RED,Color.YELLOW);ChoiceBox choiceBoxRef = new ChoiceBox(cursors);VBox vbox = new VBox();vbox.getChildren().add(choiceBoxRef);Scene scene = new Scene(vbox,300, 250);stage.setScene(scene);stage.show();scene.cursorProperty().bind(choiceBoxRef.getSelectionModel().selectedItemProperty());Image image =new Image("中国风1.JPG");}

Text文本

Stroke轻抚,描边、Strikethrough删除线

public void start(Stage stage) throws Exception {stage.setTitle("Text文本");//\n换行符Text text1 = new Text("text1\nfeagaega");text1.setFill(Color.RED);//描边颜色text1.setStroke(Color.GREEN);//设置坐标//        text1.setY(100);//        text1.setX(100);//字体倾斜30text1.setRotate(30);//文字换行宽度text1.setWrappingWidth(200);//删除线text1.setStrikethrough(true);//水平平滑text1.setFontSmoothingType(FontSmoothingType.GRAY);// text1.setFontSmoothingType(FontSmoothingType.LCD);text1.setFont(Font.font("宋体", FontWeight.BOLD,40));Scene scene =new Scene(new HBox(text1),300,250);stage.setScene(scene);stage.show();}

TextField(输入框)、TextArea文本域

TextArea textArea =new TextArea();//设置文本内容textArea.setText("wery");//换行符文本s//textArea.setWrapText(true);//行数//textArea.setPrefRowCount(2);//列数//textArea.setPrefColumnCount(2);//追加文本textArea.appendText("hello");//删除文本                            (下标0到3)textArea.deleteText(0,3);//默认焦点textArea.requestFocus();//插入文本  下标3插入文本textArea.insertText(3, "你好");//替换textArea.replaceText(0, 2, "hello");//选择全部//textArea.selectAll();//移动光标在下标3textArea.positionCaret(3);//选择到最后textArea.selectEnd();//清楚//textArea.clear();//cope//textArea.copy();//设置滚动textArea.setScrollLeft(10);textArea.setScrollTop(10);//选择监听textArea.selectedTextProperty().addListener(new ChangeListener<String>() {@Overridepublic void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {System.out.println(newValue);}});//文本监听textArea.textProperty().addListener(new ChangeListener<String>() {@Overridepublic void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {}});

//过滤 (传入一个参数(过滤后)返回一个参数)

    

textArea.setTextFormatter(new TextFormatter<String>(new UnaryOperator<Change>() {@Overridepublic Change apply(Change t) {//System.out.println(t.getText());String valueString =t.getText();//matches("[a-z]*")正则表达式if (valueString.matches("[a-z]*")) {return t;}return null;}}));

//过滤2

ta.textProperty().addListener(new ChangeListener<String>() {@Overridepublic void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {//value从哪里来到哪里去ta.setTextFormatter(new TextFormatter<String>(new StringConverter<String>() {@Overridepublic String toString(String object) {System.out.println("object: "+ object);return object;}@Overridepublic String fromString(String string) {System.out.println("str: " + string);if (string.contains("6")) {String value=string.replace("6", "老六");return value;}return string;}}));//提交ta.commitValue();}});public void start(Stage stage) throws Exception {VBox vbox =new VBox();Label label1 =new Label("账户:");TextField textField1 =new TextField();textField1.setMaxWidth(200);textField1.setPromptText("请输入用户名");textField1.setPrefColumnCount(10);Label label2 =new Label("密码:");TextField textField2 =new TextField();textField2.setPromptText("请输入密码");textField2.setMaxWidth(200);Button login =new Button("登入");login.setOnAction(e-> System.out.println(textField1.getText()+"\n"+textField2.getText()));vbox.getChildren().addAll(label1,textField1,label2,textField2,login);Scene scene =new Scene(vbox,300,200);stage.setScene(scene);stage.show();}//设置提示textField.setPromptText("请输入***");

案例

public class testFieldAreaDemo extends Application {HBox hBox =new HBox();TextField textField =new TextField();Button button =new Button("添加");TextArea textArea =new TextArea();@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("testFieldArea案例");try {hBox.getChildren().addAll(textField,button);HBox.setHgrow(textField, Priority.ALWAYS);BorderPane borderPane =new BorderPane();borderPane.setTop(hBox);borderPane.setCenter(textArea);Scene scene =new Scene(borderPane,400,400);stage.setScene(scene);stage.show();button.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(ActionEvent event) {gettext();}});}catch (Exception e){e.printStackTrace();}}public void gettext(){String str =textField.getText();textArea.appendText(str+"\n");textField.clear();}public static void main(String[] args) {launch();}}

//设置输入字符个数限制    

 TextField text =new TextField();text.setFont(Font.font("宋体",20));text.setPromptText("输入的字符<=7个");text.textProperty().addListener(new ChangeListener<String>() {@Overridepublic void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {if (newValue.length() > 7) {text.setText(oldValue);}}});

password密码字段

public void start(Stage stage) throws Exception {stage.setTitle("passwordField");GridPane gridPane =new GridPane();gridPane.setAlignment(Pos.CENTER);Label username =new Label("用户名:");TextField inputusername =new TextField();inputusername.setPromptText("请输入用户名");Label password =new Label("用户名:");PasswordField pwd =new PasswordField();pwd.setPromptText("请输入密码");HBox hBox =new HBox(10);hBox.setAlignment(Pos.CENTER);hBox.setPadding(new Insets(5,5,5,5));Button regist = new Button("注册");Button button = new Button("登入");hBox.getChildren().addAll(regist,button);gridPane.add(username,0,0);gridPane.add(inputusername,1,0);gridPane.add(password,0,1);gridPane.add(pwd,1,1);gridPane.add(hBox,1,3);Scene scene =new Scene(gridPane,600,500);stage.setScene(scene);stage.show();}

Hyperlink超链接

public void start(Stage stage) throws Exception {stage.setTitle("HyperLink");//VBox vbox =new VBox();BorderPane borderPane = new BorderPane();TextField url = new TextField();Button button =new Button("搜索");HBox top =new HBox(50);top.getChildren().add(url);top.getChildren().add(button);url.setMaxWidth(900);VBox left =new VBox();left.setMinWidth(100);top.setMinHeight(100);WebView webview =new WebView();//        webview.setMinHeight(1000);//        webview.setMaxWidth(1000);//        ScrollPane scrollPane =new ScrollPane(webview);borderPane.setCenter(webview);borderPane.setTop(top);borderPane.setLeft(left);button.setOnAction(e->{url1 = url.getText();System.out.println(url1);webview.getEngine().load(url1);});webview.autosize();webview.getEngine().load(url1);webview.getEngine().locationProperty().addListener(new ChangeListener<String>() {@Overridepublic void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {Desktop d = Desktop.getDesktop();URI address;try {address = new URI(observable.getValue());d.browse(address);} catch (URISyntaxException | IOException e) {e.printStackTrace();}}});//        Hyperlink link =new Hyperlink("https://www.baidu.com/");//        link.setText("https://www.baidu.com/");//        link.setOnAction(e-> System.out.println("https://www.baidu.com/"));// vbox.getChildren().addAll(link);Scene scene =new Scene(borderPane,1000,1000);stage.setScene(scene);stage.show();}

案例2

public class HyperlinkDemo extends Application{public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage stage) throws Exception {VBox box =new VBox();//Hyperlink link = new Hyperlink("https://www.baidu.com/");Hyperlink link = new Hyperlink("https://www.baidu.com/",new Button("帮助网址:"));//跳转事件link.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(ActionEvent event) {HostServices hostServices = getHostServices();hostServices.showDocument(link.getText());System.out.println("ok");}});box.getChildren().add(link);Scene scene =new Scene(box);stage.setScene(scene);stage.setTitle("HyperlinkDemo超链接");stage.setWidth(500);stage.setHeight(400);stage.setResizable(false);stage.show();}}

ProgressBar进度条、ProgressIndicator进度指示器

public void start(Stage stage) throws Exception {stage.setTitle("progressbar");BorderPane borderPane =new BorderPane();HBox hbox =new HBox();//进度条ProgressBar pb =new ProgressBar();pb.setProgress(0.4);//进度指示器ProgressIndicator p1 =new ProgressIndicator();ProgressIndicator p2 =new ProgressIndicator(0.7);Button button1 =new Button("start");Button button2 =new Button("close");hbox.getChildren().addAll(pb,button1,button2,p1,p2);borderPane.setBottom(hbox);p2.setProgress(0.8);Scene scene =new Scene(borderPane,600,500);stage.setScene(scene);stage.show();}

ScrollBar滚动条

public void start(Stage stage) throws Exception {

        stage.setTitle("ScrollBar");

        BorderPane borderPane =new BorderPane();

        Text t1 =new Text();

        //text.setFont(Font.font("宋体", FontWeight.BOLD,30));

        t1.setFont(Font.font("宋体", FontWeight.BOLD,30));

        t1.setText("计算机难赚钱");

        HBox hbox =new HBox();

        //hbox.setStyle("-fx-background-color: #330000;");

        borderPane.setTop(hbox);

        ScrollBar scrollBar =new ScrollBar();

        scrollBar.setMax(1000);

        scrollBar.setMin(0);

        scrollBar.setValue(100);

        //单位增量

        scrollBar.setUnitIncrement(30);

        //块增量

        scrollBar.setBlockIncrement(35);

        //滚动事件

        scrollBar.valueProperty().addListener((ObservableValue<? extends Number> ov,

                                        Number old_val, Number new_val) -> {//scrollBar对象进行改变值事件监听处理机制

               double d = new_val.doubleValue();

                t1.setText(String.valueOf(d));

        });

        hbox.getChildren().addAll(scrollBar,t1);

        Scene scene =new Scene(borderPane,600,500);

        stage.setScene(scene);

        stage.show();

    }

DatePicker日历选择器

public class DatePickerDemo extends Application {@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("DatePicker");VBox vBox =new VBox(5);DatePicker datePicker =new DatePicker();//使用setValue()方法设置日期值。//datePicker.setValue(LocalDate.of(2022, 10, 8));datePicker.setValue(LocalDate.now());//显示周数datePicker.setShowWeekNumbers(true);String pattern = "yyyy-MM-dd";//String pattern = "yyyy/MM/dd";DatePicker checkInDatePicker = new DatePicker();StringConverter<LocalDate> converter = new StringConverter<LocalDate>() {DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);@Overridepublic String toString(LocalDate date) {if (date != null) {return dateFormatter.format(date);} else {return "";}}@Overridepublic LocalDate fromString(String string) {if (string != null && !string.isEmpty()) {return LocalDate.parse(string, dateFormatter);} else {return null;}}};//设置转换器checkInDatePicker.setConverter(converter);//设置提示文本checkInDatePicker.setPromptText(pattern.toLowerCase());//禁用单元格 star在end日期的前面DatePicker startDatePicker = new DatePicker();DatePicker endDatePicker = new DatePicker();startDatePicker.setValue(LocalDate.now());final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() {@Overridepublic DateCell call(final DatePicker datePicker) {return new DateCell() {@Overridepublic void updateItem(LocalDate item, boolean empty) {super.updateItem(item, empty);if (item.isBefore(startDatePicker.getValue().plusDays(1))) {setDisable(true);setStyle("-fx-background-color: #EEEEEE;");}}};}};endDatePicker.setDayCellFactory(dayCellFactory);endDatePicker.setValue(startDatePicker.getValue().plusDays(1));//为每个日期单元格安装工具提示。DatePicker start1DatePicker = new DatePicker();DatePicker end1DatePicker = new DatePicker();start1DatePicker.setValue(LocalDate.now());final Callback<DatePicker, DateCell> dayCellFactory1 = new Callback<DatePicker, DateCell>() {@Overridepublic DateCell call(final DatePicker datePicker) {return new DateCell() {@Overridepublic void updateItem(LocalDate item, boolean empty) {super.updateItem(item, empty);long p = ChronoUnit.DAYS.between(start1DatePicker.getValue(), item);setTooltip(new Tooltip("You're about to stay for " + p + " days"));}};}};end1DatePicker.setDayCellFactory(dayCellFactory1);end1DatePicker.setValue(startDatePicker.getValue().plusDays(1));vBox.getChildren().addAll(new Label("选择日期"),datePicker,new Label("DatePicker使用系统区域设置和ISO日历系统定义的日期格式  "),checkInDatePicker,new Label("禁用单元格"),startDatePicker,endDatePicker,new Label("每个日期单元格安装工具提示"),start1DatePicker,end1DatePicker);Scene scene =new Scene(vBox,500,400);stage.setScene(scene);stage.show();}

ColorPicker颜色选择器

public class ColorPickerDemo extends Application {@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("ColorPicker");HBox hbox =new HBox();//颜色选择器ColorPicker colorPicker =new ColorPicker();colorPicker.setValue(Color.RED);Text text =new Text("ColorPicker");text.setFill(colorPicker.getValue());//颜色选择器EventcolorPicker.setOnAction((ActionEvent t)->{text.setFill(colorPicker.getValue());});hbox.getChildren().addAll(colorPicker,text);Scene scene =new Scene(hbox,500,400);stage.setScene(scene);stage.show();}

FileChooser文件选择器

打开文件

文件选择器可用作打开文件对话框,用于选择单个文件或多个文件,或作为文件保存对话框。以下代码创建一个FileChooser对象并设置其标题,然后显示给用户。

FileChooser fileChooser = new FileChooser();

fileChooser.setTitle("Open Resource File");

fileChooser.showOpenDialog(stage);

可以通过设置initialDirectory和title属性来配置文件选择器对话框窗口。

扩展过滤器

可以设置扩展过滤器来确定在文件选择器中打开哪些文件。

fileChooser.setTitle("View Pictures");fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));                fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Images", "*.*"),new FileChooser.ExtensionFilter("JPG", "*.jpg"),new FileChooser.ExtensionFilter("GIF", "*.gif"),new FileChooser.ExtensionFilter("BMP", "*.bmp"),new FileChooser.ExtensionFilter("PNG", "*.png"));

保存文件

FileChooser API允许用户为由应用程序保存的文件指定文件名及其文件夹。
showSaveDialog方法打开保存对话框窗口。

FileChooser fileChooser1 = new FileChooser();fileChooser1.setTitle("Save Image");System.out.println(pic.getId());File file = fileChooser1.showSaveDialog(stage);System.out.println(file);

案例:

public void start(Stage stage) throws Exception {stage.setTitle("FileChooser");BorderPane borderPane =new BorderPane();HBox hb = new HBox();VBox vb = new VBox();hb.setMinHeight(100);vb.setMinWidth(100);Text text =new Text("fdagragragaeg");borderPane.setTop(hb);borderPane.setLeft(vb);borderPane.setCenter(text);Button buttonload =new Button("本地文件");buttonload.setOnAction(new EventHandler<ActionEvent>(){@Overridepublic void handle(ActionEvent arg0) {//文件选择器FileChooser fileChooser = new FileChooser();//限制文件类型//FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");// fileChooser.getExtensionFilters().add(extFilter);File file = fileChooser.showOpenDialog(stage);System.out.println(file);text.setText("选择的文件名:"+file.getName());}});ColorPicker colorPicker =new ColorPicker();colorPicker.setOnAction((ActionEvent t)->{text.setFill(colorPicker.getValue());});hb.getChildren().addAll(buttonload,colorPicker);Scene scene = new Scene(borderPane,500,400);stage.setScene(scene);stage.show();}

案例2

import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.BorderPane;import javafx.scene.layout.HBox;import javafx.scene.web.HTMLEditor;import javafx.stage.FileChooser;import javafx.stage.Stage;import reader.TextFileUtils;import java.io.File;public class FileChooserDemo2 extends Application {Stage stage;HTMLEditor htmlEditor =new HTMLEditor();@Overridepublic 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);//打开文件fileOpen.setOnAction((e)->{openfile();});//保存文件fileSave.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(ActionEvent event) {Savefile();}});borderPane.setTop(hBox);borderPane.setCenter(htmlEditor);Scene scene =new Scene(borderPane);stage.setScene(scene);stage.show();}private void openfile() {FileChooser fileChooser =new FileChooser();fileChooser.setTitle("打开文件");fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text File","*.txt"));File file =fileChooser.showOpenDialog(stage);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();}}

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);}@Overridepublic 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>() {@Overridepublic 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作为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 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>() {@Overridepublic 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 {@Overridepublic 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 {@Overridepublic 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;}@Overridepublic 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();//写法1ObservableList<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);});//写法2ListView<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;}}@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("listView and observableList");BorderPane borderPane =new BorderPane();//写法1ObservableList<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);});//写法2ListView<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>>() {@Overridepublic 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>{@Overrideprotected 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;@Overridepublic 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>>() {@Overridepublic TableCell<Person, String> call(TableColumn<Person, String> personStringTableColumn) {Button btn = new Button("删除");TableCell<Person,String> cell = new TableCell<Person,String>(){@Overrideprotected 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 {@Overridepublic 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 {@Overridepublic 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>() {@Overridepublic void handle(MouseEvent event) {}});

案例

setOnMouseClicked(new EventHandler<MouseEvent>() {@Overridepublic 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("登录");@Overridepublic 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>() {@Overridepublic 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<ButtonType> 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();@Overridepublic 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>() {@Overridepublic 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放置到dialogPanedialogPane.setContent(Content);//添加按钮ButtonType ok =new ButtonType("确定", ButtonBar.ButtonData.OK_DONE);dialogPane.getButtonTypes().add(ok);//创建对话框Dialog<ButtonType> dlg =new Dialog<>();//将dialogPane放置到Dialogdlg.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();@Overridepublic 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>() {@Overridepublic 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 {@Overridepublic 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 / HSBRGB方式是最常见的方式(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);//椭圆

drawImage绘制图片

drawImage(Image img,double sx,double sy,double sw,double sh,double dx,double dy,double dw,double dh)

img:要绘制的图片

sx,sy,sw,sh:源矩形(s,source)

dx,dy,sw,dh:目标矩形(d,destination)

样式单CSS

CSS,Cascading Style Sheets

用于定义界面的显示样式(背景,边框,字体等)

-fx-padding:填充、-fx-font-size:字体大小、-fx-text-fill:文件颜色

新建javafx项目时,已经默认创建了一个CSS文件:application.css

图片背景

CSS文件

#pane{-fx-background-image: url("中国风1.JPG");/*-fx-background-repeat: stretch;-fx-background-size: 900 506;-fx-background-position: center center;*//*-fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0);*/}.root{-fx-background-image: url("中国风1.JPG");}Java文件public class CSSdemo extends Application {TextField textField =new TextField();@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("CSSdemo");BorderPane borderPane = new BorderPane();HBox hbox =new HBox(10);Button b =new Button("选择");Button c =new Button("提交");textField.getStyleClass().add("text");b.getStyleClass().add("button");hbox.getChildren().addAll(textField,b,c);// borderPane.setId("pane");borderPane.setTop(hbox);Scene scene =new Scene(borderPane,300,400);//scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());//scene.getStylesheets().add(CSSdemo.class.getResource("style.css").toExternalForm());stage.setScene(scene);stage.show();}public static void main(String[] args) {launch();}}

SceneBuilder可视化设计

Eclipse添加javafx组件

在Work with中添加:http://download.eclipse.org/efxclipse/updates-released/2.3.0/site/

Eclpise-jdk11-javaFx

https://openjfx.cn/

   

module Java11 {exports com;requires javafx.base;requires javafx.controls;requires javafx.fxml;requires javafx.graphics;requires javafx.media;requires javafx.swing;requires javafx.web;requires javafx-swt;}

媒体播放器

Javafx自带媒体播放的支持

Media:表示一个媒体文件(URL)

MediaPlayer:表示一个播放器(播放控件)

MediaView:表示一个播放控件(显示)

Eclpise应用程序的发布

创建一个文件夹,将jdk里的jre拷贝过去

创建启动脚本

IEDA 应用程序的发布

右击项目或模块

open module settings

选择ArtiFacts->JAR->From modules with dependencies

可以选择包含测试类或者不包含

第一个仅导出目标jar包

第二个导出目标jar包和项目所依赖的jar包

选择Include in project build

Build -> Build Artifacts -> Build

构建结果如下:

创建一个文件夹,将jdk里的jre拷贝过去

创建启动脚本

start jre\bin\javaw.exe -jar ch01.jar

登入窗口+小知识点

public class LoginDemo extends Application{public static void main(String[] args) {launch(args);}@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("Login");Label name =new Label("账号:");Label password = new Label("密码:");name.setFont(Font.font("宋体",20));TextField inname =new TextField();inname.setUserData("hello");PasswordField inPasswordField =new PasswordField();inPasswordField.setUserData("123456");Button login =new Button("登录");Button clear =new Button("清理");GridPane gr =new GridPane();gr.setStyle("-fx-background-color:#FFF5EE");//列,行gr.add(name, 0, 0);gr.add(inname, 1, 0);gr.add(password, 0, 1);gr.add(inPasswordField, 1, 1);gr.add(login, 1, 2);gr.add(clear, 0, 2);gr.setHgap(10);gr.setVgap(10);GridPane.setMargin(login, new Insets(0, 0, 0, 150));gr.setAlignment(Pos.CENTER);//清理事件clear.setOnAction(new EventHandler<ActionEvent>() {@Overridepublic void handle(ActionEvent event) {inname.setText("");inPasswordField.setText("");}});//登录事件login.setOnAction((e)->{String name1 =inname.getText();String password1 =inPasswordField.getText();if (inname.getUserData().equals(name1) && inPasswordField.getUserData().equals(password1)) {loginWindos lonWindos = new loginWindos(name1);stage.close();}else {Alert waring = new Alert(Alert.AlertType.WARNING);waring.setHeaderText("用户名/密码出错");waring.setContentText("请重新输入!");//showAndWait();当输入的焦点在对话框里,后面的界面无法输入(不往下走,知道对话框关闭)waring.showAndWait();//呼吸灯FadeTransition fade = new FadeTransition();fade.setDuration(javafx.util.Duration.seconds(2));fade.setNode(gr);fade.setFromValue(0);fade.setToValue(1);fade.play();}});Scene scene =new Scene(gr);stage.setScene(scene);stage.setWidth(400);stage.setHeight(500);stage.setResizable(false);stage.show();}class  loginWindos{private final Stage stage = new Stage();public loginWindos(String name) {stage.setTitle("qgs");Alert waring = new Alert(Alert.AlertType.INFORMATION);waring.setHeaderText("欢迎"+name+"来到qgs操作界面");waring.showAndWait();stage.show();}}}

Springboot3+JavaFX

Pom.xml加入依赖

<dependency><groupId>org.openjfx</groupId><artifactId>javafx-controls</artifactId><version>17.0.2</version>
</dependency>

package com.example.fx;import javafx.application.Application;import javafx.application.HostServices;import javafx.geometry.Rectangle2D;import javafx.scene.Cursor;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.layout.BorderPane;import javafx.scene.layout.HBox;import javafx.stage.Screen;import javafx.stage.Stage;public class fxmain extends Application {@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("SceneDemo");BorderPane borderPane =new BorderPane();TextArea textArea =new TextArea();HBox hbox =new HBox();Button openbaidu =new Button("打开百度");Button getScreenvalue = new Button("获取屏幕属性值");hbox.getChildren().addAll(openbaidu,getScreenvalue);openbaidu.setOnAction((e)->{HostServices hostServices = getHostServices();hostServices.showDocument("https://www.baidu.com/");});getScreenvalue.setOnAction((e)->{Screen primary = Screen.getPrimary();double dpi = primary.getDpi();System.out.println("当前屏幕dpi:"+dpi);Rectangle2D rec1 = primary.getBounds();Rectangle2D rec2 = primary.getVisualBounds();textArea.appendText("\n----全部屏幕--------");//            textArea.appendText("\n左上角x:"+rec1.getMinX()+"左上角y"+rec1.getMinY());//            textArea.appendText("\n右下角x--"+ rec1.getMaxX()+"右下角y--"+ rec1.getMaxY());textArea.appendText("\n宽度:"+rec1.getWidth()+"高度"+rec1.getHeight());textArea.appendText("\n----可以看到的屏幕--------");//            textArea.appendText("\n左上角x:"+rec2.getMinX()+"左上角y"+rec2.getMinY());//            textArea.appendText("\n右下角x--"+ rec2.getMaxX()+"右下角y--"+ rec2.getMaxY());textArea.appendText("\n宽度:"+rec2.getWidth()+"高度"+rec2.getHeight());});borderPane.setTop(hbox);borderPane.setCenter(textArea);Scene scene =new Scene(borderPane,400,400);scene.setCursor(Cursor.CLOSED_HAND);//手/*** scene.setCursor(Cursor.HAND);//手,箭头啥的* Cursor CROSSHAIR  光标十字光标* Cursor . DEFAULT 光标默认值* Cursor DISAPPEAR   光标消失* Cursor CLOSED_HAND 光标闭合手* Contextmenudemo 上下文菜单演示* Cursor E _ RESIZE 光标E _ RESIZE*/stage.setScene(scene);stage.show();}}

package com.example.fx;import com.example.domain.Corrdinate;
import com.example.util.EasyExcelUtil;
import javafx.application.Application;
import javafx.application.HostServices;
import javafx.geometry.Rectangle2D;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.FileChooser;
import javafx.stage.Screen;
import javafx.stage.Stage;import java.io.File;
import java.io.IOException;
import java.util.List;public class fxmain extends Application {private static String filePath =null;@Overridepublic void start(Stage stage) throws Exception {stage.setTitle("坐标验证");BorderPane borderPane =new BorderPane();TextArea textArea =new TextArea();HBox hbox =new HBox();Button openbaidu =new Button("打开百度");Button upFile =new Button("上传文件");Button executeFile =new Button("执行");Button getScreenvalue = new Button("获取屏幕属性值");hbox.getChildren().addAll(upFile,executeFile);openbaidu.setOnAction((e)->{HostServices hostServices = getHostServices();hostServices.showDocument("https://www.baidu.com/");});//上传文件upFile.setOnAction((e)->{FileChooser fileChooser = new FileChooser();fileChooser.setTitle("选择Excel文件");fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));//过滤fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Excel", "*.xlsx"),new FileChooser.ExtensionFilter("XLS", "*.xls"), new FileChooser.ExtensionFilter("XLSX", "*.xlsx"));File file = fileChooser.showOpenDialog(stage);try {System.out.println("路径:"+file.getCanonicalPath());textArea.setText("路径:"+file.getCanonicalPath());filePath=file.getCanonicalPath();} catch (IOException ex) {throw new RuntimeException(ex);}if (file != null) {}});//执行executeFile.setOnAction((e)->{List<Corrdinate> list = EasyExcelUtil.importExcel(filePath);textArea.setText("生成文件路径C:\\Users\\Administrator\\Desktop\\demofile");for (Corrdinate corrdinate : list) {textArea.appendText("\n"+corrdinate.toString());}});getScreenvalue.setOnAction((e)->{Screen primary = Screen.getPrimary();double dpi = primary.getDpi();System.out.println("当前屏幕dpi:"+dpi);Rectangle2D rec1 = primary.getBounds();Rectangle2D rec2 = primary.getVisualBounds();textArea.appendText("\n----全部屏幕--------");
//            textArea.appendText("\n左上角x:"+rec1.getMinX()+"左上角y"+rec1.getMinY());
//            textArea.appendText("\n右下角x--"+ rec1.getMaxX()+"右下角y--"+ rec1.getMaxY());textArea.appendText("\n宽度:"+rec1.getWidth()+"高度"+rec1.getHeight());textArea.appendText("\n----可以看到的屏幕--------");
//            textArea.appendText("\n左上角x:"+rec2.getMinX()+"左上角y"+rec2.getMinY());
//            textArea.appendText("\n右下角x--"+ rec2.getMaxX()+"右下角y--"+ rec2.getMaxY());textArea.appendText("\n宽度:"+rec2.getWidth()+"高度"+rec2.getHeight());});borderPane.setTop(hbox);borderPane.setCenter(textArea);Scene scene =new Scene(borderPane,400,400);scene.setCursor(Cursor.CLOSED_HAND);//手/*** scene.setCursor(Cursor.HAND);//手,箭头啥的* Cursor CROSSHAIR  光标十字光标* Cursor . DEFAULT 光标默认值* Cursor DISAPPEAR   光标消失* Cursor CLOSED_HAND 光标闭合手* Contextmenudemo 上下文菜单演示* Cursor E _ RESIZE 光标E _ RESIZE*/stage.setScene(scene);stage.show();}
}

jdk1.8以上的版本(jdk9,jdk11,jdk17等)没有jre的问题

D:\Program Files\Java\jdk-17目录下执行

bin\jlink.exe --module-path jmods --add-modules java.desktop --output jre

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/646177.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

短剧小程序分销系统开发:创新与机遇的融合

一、引言 随着移动互联网的快速发展&#xff0c;短剧作为一种新兴的娱乐形式&#xff0c;正逐渐成为人们生活中的一部分。短剧小程序分销系统的开发&#xff0c;不仅为短剧的传播提供了新的渠道&#xff0c;同时也为相关产业带来了新的商业机会。本文将探讨短剧小程序分销系统…

web架构师编辑器内容-图层拖动排序功能的开发

新的学习方法 用手写简单方法实现一个功能然后用比较成熟的第三方解决方案即能学习原理又能学习第三方库的使用 从两个DEMO开始 Vue Draggable Next: Vue Draggable NextReact Sortable HOC: React Sortable HOC 列表排序的三个阶段 拖动开始&#xff08;dragstart&#x…

[BJDCTF2020]ZJCTF,不过如此(特详解)

php特性 1.先看代码&#xff0c;提示了next.php&#xff0c;绕过题目的要求去回显next.php 2.可以看到要求存在text内容而且text内容强等于后面的字符串&#xff0c;而且先通过这个if才能执行下面的file参数。 3.看到用的是file_get_contents()函数打开text。想到用data://协…

缓存高并发问题

Redis 做缓存虽减轻了 DBMS 的压力&#xff0c;减小了 RT&#xff0c;但在高并发情况下也是可能会出现各种问题的。 缓存穿透 当用户访问的数据既不在缓存也不在数据库中时&#xff0c;就会导致每个用户查询都会“穿透”缓存“直抵”数据库。这种情况就称为缓存穿透。当高度发…

python222网站实战(SpringBoot+SpringSecurity+MybatisPlus+thymeleaf+layui)-后台管理主页面实现

锋哥原创的SpringbootLayui python222网站实战&#xff1a; python222网站实战课程视频教程&#xff08;SpringBootPython爬虫实战&#xff09; ( 火爆连载更新中... )_哔哩哔哩_bilibilipython222网站实战课程视频教程&#xff08;SpringBootPython爬虫实战&#xff09; ( 火…

程序员手把手教你参与开源!拿捏!

一、前言 有一些同学提问&#xff0c;希望在自己的简历上增加一些有含金量的项目经历&#xff0c;最好能够去参与一些开源项目的开发&#xff0c;但由于对一个庞大的开源项目缺乏认知&#xff0c;难以着手。同时也担心自己能力不足&#xff0c;不知道自己写的代码是否会被接纳。…

flutter 五点一点四:MaterialApp Theme 给你一堆颜色看看

ColorScheme colorScheme, // 拥有30种颜色(这个数可能过几个版本会变化吧)&#xff0c;可用于配置大多数组件的颜色。 A set of 30 colors based on the[Material spec] that can be used to configure the color properties of most components.Color canvasColor, // Mater…

五分钟学会接口自动化测试框架

今天&#xff0c;我们来聊聊接口自动化测试。 接口自动化测试是什么&#xff1f;如何开始&#xff1f;接口自动化测试框架如何搭建&#xff1f; 自动化测试 自动化测试&#xff0c;这几年行业内的热词&#xff0c;也是测试人员进阶的必备技能&#xff0c;更是软件测试未来发…

05.Elasticsearch应用(五)

Elasticsearch应用&#xff08;五&#xff09; 1.Mapping介绍 Mapping是对索引库中文档的约束&#xff0c;类似于数据表结构&#xff0c;作用如下&#xff1a; 定义索引中的字段的名称定义字段的数据类型&#xff0c;例如字符串&#xff0c;数字&#xff0c;布尔等字段&…

FreeRFTOS中的临界段(代码)

前言 本片文章记录我学习FreeRTOS中的“临界段”知识点&#xff0c;同时也希望我的分享能给你带来帮助 目录 前言 一、临界段&#xff08;临界区&#xff09; 二、任务级临界段代码 三、中断级临界段代码保护 四、结语 一、临界段&#xff08;临界区&#xff09; 在Fr…

仅使用 Python 创建的 Web 应用程序(前端版本)第06章_登录页面

从本章开始,我们将创建每个页面。 本栏的例子 可以访问这里, WTS 首先是登录页面。 完成后的图像如下 创建过程如下 No类型内容1Model创建继承BaseDataModel的数据类User、Session2MockDB创建用户表并添加管理员/成员用户3Service创建AuthAPIClient、UserAPIClient4Page定义…

程序员必备的20个学习网站

今天好学编程小编整理了20个程序员必备的学习网站&#xff0c;此篇对于新手程序员比较有用&#xff0c;技术老鸟们也可以查缺补漏。话不多说&#xff0c;纯纯干货呈上&#xff0c;赶紧点个赞收藏&#xff0c;以后会用得上&#xff01; 技术网站类 1、博客园 一个面向开发者的…

SpringBoot 3.1.7 集成Kafka 3.5.0

一、背景 写这边篇文章的目的&#xff0c;是记录我在集成kafka客户端遇到的一些问题&#xff0c;文章会记录整个接入的过程&#xff0c;其中会遇到几个坑&#xff0c;如果需要最终版本&#xff0c;直接看最后一节就行了&#xff0c;感觉Spring-Kafka的文档太少了&#xff0c;如…

【github】使用github action 拉取国外docker镜像

使用github action 拉取国外docker镜像 k8s部署经常用到国外镜像&#xff0c;如果本地无法拉取可以考虑使用github action环境 github action的ci服务器在国外&#xff0c;不受中国防火墙影响github action 自带docker命令运行时直接将你仓库代码拉取下来 步骤 你的国内dock…

React16源码: React中的unwindWork的源码实现

unwindWork 1 &#xff09;概述 在 renderRoot 的 throw Exception 里面, 对于被捕获到错误的组件进行了一些处理并且向上去寻找能够处理这些异常的组件&#xff0c;比如说 class component 里面具有getDerivedStateFromError 或者 componentDidCatch 这样的生命周期方法这个c…

QT发生弹出警告窗口

QTC开发程序弹出警告窗口&#xff0c;如上图 实施代码&#xff1a; #include <QMessageBox> int main() {// 在发生错误的地方QMessageBox::critical(nullptr, "错误", "发生了一个错误&#xff0c;请检查您的操作。");}上面的文字可以更改&#x…

【学网攻】 第(5)节 -- Cisco VTP的使用

文章目录 【学网攻】 第(1)节 -- 认识网络【学网攻】 第(2)节 -- 交换机认识及使用【学网攻】 第(3)节 -- 交换机配置聚合端口【学网攻】 第(4)节 -- 交换机划分Vlan 前言 网络已经成为了我们生活中不可或缺的一部分&#xff0c;它连接了世界各地的人们&#xff0c;让信息和资…

社区信息员灾情上报系统-计算机毕业设计源码13263

摘 要 科技进步的飞速发展引起人们日常生活的巨大变化&#xff0c;电子信息技术的飞速发展使得电子信息技术的各个领域的应用水平得到普及和应用。信息时代的到来已成为不可阻挡的时尚潮流&#xff0c;人类发展的历史正进入一个新时代。在现实运用中&#xff0c;应用软件的工作…

初识Docker(架构、安装Docker)

一、什么是Docker Docker 是一个开源的应用容器引擎&#xff0c;它允许开发者将应用程序及其依赖打包到一个轻量级、可移植的容器中。这些容器可以在不同的计算平台上运行&#xff0c;如Linux和Windows&#xff0c;并且可以实现虚拟化。Docker 的设计目标是提供一种快速且轻量…

【数据类型转换】C语言中的数据类型转换

1.定义 数据类型转换&#xff0c;听这个名字你就懂了&#xff0c;就是将数据从一种类型转换为另一种类型。 2.自动类型转换 自动类型转换就是编译器默默地、隐式地、偷偷地进行的数据类型转换&#xff0c;这种转换不需要程序员干预&#xff0c;会自动发生。比如说&#xff1a…