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(); } @Override public 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>() { @Override public 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("被点击了"); // } // });
//按钮单击事件写法2 button.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>() { @Override public 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>() { @Override public void handle(KeyEvent event) { if (event.getCode().getName().equals(KeyCode.A.getName())) { System.out.println("按下"+event.getCode().getName()); } } }); //释放 button.setOnKeyReleased(new EventHandler<KeyEvent>() { @Override public 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); } @Override public 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>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { System.out.println("当前是否选中:"+newValue); } }); //ToggleGroup监听 tg.selectedToggleProperty().addListener(new ChangeListener<Toggle>() { @Override public 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); } @Override public 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+O KeyCombination 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() { @Override public 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>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { //被选中的下标oldValue oldValue //被选中新的下标newValue newValue System.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); //字体倾斜30 text1.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(); //移动光标在下标3 textArea.positionCaret(3); //选择到最后 textArea.selectEnd(); //清楚 //textArea.clear(); //cope //textArea.copy(); //设置滚动 textArea.setScrollLeft(10); textArea.setScrollTop(10); //选择监听 textArea.selectedTextProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { System.out.println(newValue); } }); //文本监听 textArea.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { } });
//过滤 (传入一个参数(过滤后)返回一个参数)
textArea.setTextFormatter(new TextFormatter<String>(new UnaryOperator<Change>() { @Override public 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>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { //value从哪里来到哪里去 ta.setTextFormatter(new TextFormatter<String>(new StringConverter<String>() { @Override public String toString(String object) { System.out.println("object: "+ object); return object; } @Override public 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(); @Override public 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>() { @Override public 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>() { @Override public 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>() { @Override public 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); } @Override public 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>() { @Override public 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 { @Override public 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); @Override public String toString(LocalDate date) { if (date != null) { return dateFormatter.format(date); } else { return ""; } } @Override public 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>() { @Override public DateCell call(final DatePicker datePicker) { return new DateCell() { @Override public 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>() { @Override public DateCell call(final DatePicker datePicker) { return new DateCell() { @Override public 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 { @Override public 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()); //颜色选择器Event colorPicker.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>(){ @Override public 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(); @Override public void start(Stage stage) throws Exception { this.stage =stage; stage.setTitle("FileChooserDemo2"); BorderPane borderPane =new BorderPane(); HBox hBox=new HBox(); Button fileOpen = new Button("打开"); Button fileSave = new Button("保存"); hBox.getChildren().addAll(fileOpen,fileSave); //打开文件 fileOpen.setOnAction((e)->{ openfile(); }); //保存文件 fileSave.setOnAction(new EventHandler<ActionEvent>() { @Override public 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(); } }
手拉手JavaFX UI控件与springboot3+FX桌面开发(中):https://developer.aliyun.com/article/1431715