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