手拉手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.rhkb.cn/news/244761.html

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

相关文章

开始学习vue2(Vue方法)

一、过滤器 过滤器&#xff08;Filters&#xff09;是 vue 为开发者提供的功能&#xff0c;常用于文本的格式 化。过滤器可以用在两个地方&#xff1a;插值表达式 和 v-bind 属性绑定。 过滤器应该被添加在 JavaScript 表达式的尾部&#xff0c;由“管道符 ”进行 调用&#…

USB-C接口给显示器带来怎样的变化?

随着科技的不断发展&#xff0c;Type-C接口已经成为现代电子设备中常见的接口标准。它不仅可以提供高速的数据传输&#xff0c;还可以实现快速充电和视频传输等功能。因此&#xff0c;使用Type-C接口的显示器方案也受到了广泛的关注。本文将介绍Type-C接口显示器的优势、应用场…

[MRCTF2020]你传你呢1

尝试了几次&#xff0c;发现是黑名单过滤&#xff0c;只要包含文件后缀有ph就传不了&#xff0c;同时也有类型检测&#xff0c;需要抓包修改content-type 尝试了上传.htaccess&#xff0c;成功了&#xff0c;可以利用这让服务器将jpg文件当作php来解析&#xff0c;详见超详细文…

【K8S 云原生】K8S的图形化工具——Rancher

目录 一、rancher概述 1、rancher概念 2、rancher和K8S的区别&#xff1a; 二、实验 1、安装部署 2、给集群添加监控&#xff1a; 3、创建命名空间&#xff1a; 4、创建deployment&#xff1a; 5、创建service&#xff1a; 6、创建ingress&#xff1a; 7、创建hpa 8…

qt-C++笔记之使用信号和槽实现跨类成员变量同步响应

qt-C笔记之使用信号和槽实现跨类成员变量同步响应 —— 杭州 2024-01-24 code review! 文章目录 qt-C笔记之使用信号和槽实现跨类成员变量同步响应1.运行2.main.cpp3.test.pro4.编译 1.运行 2.main.cpp 代码 #include <QCoreApplication> #include <QObject> #…

leetcode刷题(剑指offer) 105.从前序与中序遍历序列构造二叉树

105.从前序与中序遍历序列构造二叉树 给定两个整数数组 preorder 和 inorder &#xff0c;其中 preorder 是二叉树的先序遍历&#xff0c; inorder 是同一棵树的中序遍历&#xff0c;请构造二叉树并返回其根节点。 示例 1: 输入: preorder [3,9,20,15,7], inorder [9,3,15,…

Webpack5 基本使用 - 1

Webpack 是什么 webpack 的核心目的是打包&#xff0c;即把源代码一个一个的 js 文件&#xff0c;打包汇总为一个总文件 bundle.js。 基本配置包括mode指定打包模式&#xff0c;entry指定打包入口&#xff0c;output指定打包输出目录。 另外&#xff0c;由于 webpack默认只能打…

kali安装LAMP和DVWA

LANMP简介 LANMP是指一组通常用来搭建动态网站或者服务器的开源软件&#xff0c;本身都是各自独立的程序&#xff0c;但是因为常被放在一起使用&#xff0c;拥有了越来越高的兼容度&#xff0c;共同组成了一个强大的Web应用程序平台。 L:指Linux&#xff0c;一类Unix计算机操作…

静态web服务器实战

准备html页面&#xff0c;包含两个页面(index.html, index2.html)和一个404(404html)页面&#xff0c;目录示意&#xff1a; 1.返回固定页面 with open("website/index.html","r") as file: import socket# # 返回固定的页面 website/index.html if __na…

静态分析C语言生成函数调用关系的利器——cally和egypt

大纲 准备工作安装graphviz安装cally安装egypt简单分析GCC产生RTL&#xff08;Register transfer language&#xff09;文件callyegypt总结 高级分析callyegypt 总结参考资料 在《静态分析C语言生成函数调用关系的利器——cflow》和《静态分析C语言生成函数调用关系的利器——c…

HarmonyOS鸿蒙学习基础篇 - Text文本组件

该组件从API Version 7开始支持。后续版本如有新增内容&#xff0c;则采用上角标单独标记该内容的起始版本。 Text文本组件是可以显示一段文本的组件。该组件从API Version 7开始支持&#xff0c;从API version 9开始&#xff0c;该接口支持在ArkTS卡片中使用。 子组件 可…

Flutter 页面嵌入 Android原生 View

前言 文章主要讲解Flutter页面如何使用Android原生View&#xff0c;但用到了Flutter 和 Android原生 相互通信知识&#xff0c;建议先看完这篇讲解通信的文章 Flutter 与 Android原生 相互通信&#xff1a;BasicMessageChannel、MethodChannel、EventChannel-CSDN博客 数据观…

Java面试题50道

文章目录 1.谈谈你对Spring的理解2.Spring的常用注解有哪些3.Spring中的bean线程安全吗4.Spring中的设计模式有哪些5.Spring事务传播行为有几种6.Spring是怎么解决循环依赖的7.SpringBoot自动配置原理8.SpringBoot配置文件类型以及加载顺序9.SpringCloud的常用组件有哪些10.说一…

rabbitmq基础-java-5、Topic交换机

1、简介 Topic类型的Exchange与Direct相比&#xff0c;都是可以根据RoutingKey把消息路由到不同的队列。 只不过Topic类型Exchange可以让队列在绑定BindingKey 的时候使用通配符&#xff01; BindingKey 一般都是有一个或多个单词组成&#xff0c;多个单词之间以.分割&#x…

(SSO单点登录)多个系统之间如何实现账号互通

SSO具有以下优点&#xff1a; 降低访问第三方网站风险&#xff1b;降低用户名和密码的管理成本&#xff1b;提高用户试用满意度&#xff1b;SSO使用标准的身份认证和授权协议&#xff0c;如OAuth、OpenID Connect等&#xff0c;可以保障用户身份的安全性和隐私性。 单点登录最大…

文件上传技术总结

语言可解析的后缀 &#xff08;前提&#xff1a;在Apache httpd.conf 配置文件中有特殊语言的配置 AddHandler application/x-httpd-php .php 搭配大小写、双重、空格来进行 其中&#xff1a; phtml、pht、php3、php4和php5都是Apache和php认可的php程序的文件后缀 常见的…

C#使用IsLeapYear方法判断指定年份是否为闰年

目录 一、判断指定年是否为闰年的2个方法 1.使用IsLeapYear方法判断指定年份是否为闰年 2.使用自定义的算法计算指定年份是否为闰年 二、示例 1.方法1的实例 2.方法2的实例 一、判断指定年是否为闰年的2个方法 1.使用IsLeapYear方法判断指定年份是否为闰年 使用IsLeapY…

【立创EDA-PCB设计基础】6.布线铺铜实战及细节详解

前言&#xff1a;本文进行布线铺铜实战及详解布线铺铜的细节 在本专栏中【立创EDA-PCB设计基础】前面完成了布线铺铜前的设计规则的设置&#xff0c;接下来进行布线 布局原则是模块化布局&#xff08;优先布局好确定位置的器件&#xff0c;例如排针、接口、主控芯片&#xff…

司铭宇老师:门店经理培训:如何成为一位卓越的门店经理

门店经理培训&#xff1a;如何成为一位卓越的门店经理 在激烈的市场竞争中&#xff0c;门店经理作为门店的灵魂人物&#xff0c;肩负着提升门店业绩、维护品牌形象、带领团队成长等重要职责。本文将为您解析如何成为一位卓越的门店经理&#xff0c;助力您的职业生涯迈向新高峰…

【latex】在Overleaf的IEEE会议模板中,快速插入参考文献

【LaTeX】在Overleaf的IEEE会议模板中&#xff0c;快速插入参考文献 写在最前面第一步&#xff1a;在文献检索网站导出引用文献的bib文件第二步&#xff1a;编辑overleaf模版方法二&#xff1a;EduBirdie生成参考文献&#xff08;补充&#xff09;使用LaTeX在Overleaf的IEEE会议…