本文目录导读:

我将为您提供几个JavaFX的实用案例,从基础到进阶,帮助您快速上手。
基础案例:计算器
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
public class CalculatorDemo extends Application {
private TextField displayField;
private double firstNumber = 0;
private String operator = "";
private boolean startNewNumber = true;
@Override
public void start(Stage primaryStage) {
// 创建显示区域
displayField = new TextField();
displayField.setEditable(false);
displayField.setAlignment(Pos.CENTER_RIGHT);
displayField.setPrefHeight(50);
displayField.setStyle("-fx-font-size: 20px;");
// 创建按钮布局
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20));
// 按钮数组
String[][] buttonLabels = {
{"7", "8", "9", "/"},
{"4", "5", "6", "*"},
{"1", "2", "3", "-"},
{"0", ".", "=", "+"},
{"C", "CE", "", ""}
};
// 创建按钮并添加到网格
for (int row = 0; row < buttonLabels.length; row++) {
for (int col = 0; col < buttonLabels[row].length; col++) {
String label = buttonLabels[row][col];
if (label.isEmpty()) continue;
Button button = new Button(label);
button.setPrefSize(60, 50);
button.setStyle("-fx-font-size: 16px;");
// 设置按钮样式
if (label.matches("[0-9.]")) {
button.setStyle("-fx-font-size: 16px; -fx-background-color: #f0f0f0;");
} else if (label.equals("=")) {
button.setStyle("-fx-font-size: 16px; -fx-background-color: #4CAF50; -fx-text-fill: white;");
} else {
button.setStyle("-fx-font-size: 16px; -fx-background-color: #ff9800; -fx-text-fill: white;");
}
// 绑定事件
button.setOnAction(e -> handleButtonClick(label));
grid.add(button, col, row);
}
}
// 整体布局
GridPane root = new GridPane();
root.setPadding(new Insets(20));
root.setVgap(10);
root.add(displayField, 0, 0);
root.add(grid, 0, 1);
Scene scene = new Scene(root, 300, 350);
primaryStage.setTitle("JavaFX 计算器");
primaryStage.setScene(scene);
primaryStage.show();
}
private void handleButtonClick(String value) {
switch (value) {
case "C":
clearAll();
break;
case "CE":
clearEntry();
break;
case "=":
calculate();
break;
case "+":
case "-":
case "*":
case "/":
setOperator(value);
break;
default:
inputNumber(value);
}
}
private void inputNumber(String digit) {
if (startNewNumber) {
displayField.setText(digit);
startNewNumber = false;
} else {
if (digit.equals(".") && displayField.getText().contains(".")) {
return;
}
displayField.setText(displayField.getText() + digit);
}
}
private void setOperator(String op) {
if (!displayField.getText().isEmpty()) {
firstNumber = Double.parseDouble(displayField.getText());
operator = op;
startNewNumber = true;
}
}
private void calculate() {
if (!operator.isEmpty() && !displayField.getText().isEmpty()) {
double secondNumber = Double.parseDouble(displayField.getText());
double result = 0;
switch (operator) {
case "+": result = firstNumber + secondNumber; break;
case "-": result = firstNumber - secondNumber; break;
case "*": result = firstNumber * secondNumber; break;
case "/":
if (secondNumber != 0) {
result = firstNumber / secondNumber;
} else {
displayField.setText("错误:除数不能为0");
startNewNumber = true;
operator = "";
return;
}
break;
}
displayField.setText(String.valueOf(result));
operator = "";
startNewNumber = true;
}
}
private void clearAll() {
displayField.clear();
firstNumber = 0;
operator = "";
startNewNumber = true;
}
private void clearEntry() {
displayField.clear();
startNewNumber = true;
}
public static void main(String[] args) {
launch(args);
}
}
进阶案例:待办事项管理器
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class TodoListDemo extends Application {
private ListView<TodoItem> listView;
private TextField taskField;
private DatePicker datePicker;
@Override
public void start(Stage primaryStage) {
// 创建标题
Label title = new Label("待办事项管理器");
title.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
// 创建输入区域
taskField = new TextField();
taskField.setPromptText("输入待办事项...");
taskField.setPrefWidth(250);
datePicker = new DatePicker();
datePicker.setValue(LocalDate.now());
Button addButton = new Button("添加");
addButton.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white;");
Button deleteButton = new Button("删除");
deleteButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
HBox inputBox = new HBox(10);
inputBox.setAlignment(Pos.CENTER);
inputBox.getChildren().addAll(taskField, datePicker, addButton, deleteButton);
// 创建列表
listView = new ListView<>();
listView.setPrefSize(500, 300);
listView.setPlaceholder(new Label("暂无待办事项"));
// 事件处理
addButton.setOnAction(e -> addTodoItem());
deleteButton.setOnAction(e -> deleteTodoItem());
taskField.setOnAction(e -> addTodoItem());
// 布局
VBox topBox = new VBox(10);
topBox.setAlignment(Pos.CENTER);
topBox.getChildren().addAll(title, inputBox);
BorderPane root = new BorderPane();
root.setTop(topBox);
root.setCenter(listView);
root.setPadding(new Insets(20));
Scene scene = new Scene(root, 550, 400);
primaryStage.setTitle("待办事项管理器");
primaryStage.setScene(scene);
primaryStage.show();
}
private void addTodoItem() {
String task = taskField.getText().trim();
if (!task.isEmpty()) {
TodoItem item = new TodoItem(task, datePicker.getValue());
listView.getItems().add(item);
taskField.clear();
}
}
private void deleteTodoItem() {
TodoItem selected = listView.getSelectionModel().getSelectedItem();
if (selected != null) {
listView.getItems().remove(selected);
}
}
// 内部类:待办事项
private class TodoItem {
private String task;
private LocalDate date;
private boolean completed;
public TodoItem(String task, LocalDate date) {
this.task = task;
this.date = date;
this.completed = false;
}
@Override
public String toString() {
String status = completed ? "✓" : "○";
String dateStr = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
return String.format("%s %s (截止: %s)", status, task, dateStr);
}
}
public static void main(String[] args) {
launch(args);
}
}
综合案例:学生成绩管理系统
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.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class StudentGradeDemo extends Application {
private TableView<Student> tableView;
private TextField nameField, idField, scoreField;
private ComboBox<String> gradeComboBox;
private ObservableList<Student> studentList;
@Override
public void start(Stage primaryStage) {
// 创建示例数据
studentList = FXCollections.observableArrayList();
studentList.addAll(
new Student("张一", "2024001", 85.5, "优秀"),
new Student("李二", "2024002", 72.0, "良好"),
new Student("王三", "2024003", 58.5, "及格"),
new Student("赵四", "2024004", 45.0, "不及格")
);
// 创建表格
tableView = new TableView<>();
tableView.setItems(studentList);
// 创建列
TableColumn<Student, String> nameCol = new TableColumn<>("姓名");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
nameCol.setPrefWidth(100);
TableColumn<Student, String> idCol = new TableColumn<>("学号");
idCol.setCellValueFactory(new PropertyValueFactory<>("studentId"));
idCol.setPrefWidth(100);
TableColumn<Student, Double> scoreCol = new TableColumn<>("成绩");
scoreCol.setCellValueFactory(new PropertyValueFactory<>("score"));
scoreCol.setPrefWidth(100);
TableColumn<Student, String> gradeCol = new TableColumn<>("等级");
gradeCol.setCellValueFactory(new PropertyValueFactory<>("grade"));
gradeCol.setPrefWidth(100);
tableView.getColumns().addAll(nameCol, idCol, scoreCol, gradeCol);
// 创建输入表单
GridPane formGrid = new GridPane();
formGrid.setHgap(10);
formGrid.setVgap(10);
formGrid.setPadding(new Insets(10));
nameField = new TextField();
nameField.setPromptText("姓名");
idField = new TextField();
idField.setPromptText("学号");
scoreField = new TextField();
scoreField.setPromptText("成绩");
gradeComboBox = new ComboBox<>();
gradeComboBox.getItems().addAll("优秀", "良好", "中等", "及格", "不及格");
gradeComboBox.setPromptText("选择等级");
formGrid.add(new Label("姓名:"), 0, 0);
formGrid.add(nameField, 1, 0);
formGrid.add(new Label("学号:"), 0, 1);
formGrid.add(idField, 1, 1);
formGrid.add(new Label("成绩:"), 0, 2);
formGrid.add(scoreField, 1, 2);
formGrid.add(new Label("等级:"), 0, 3);
formGrid.add(gradeComboBox, 1, 3);
// 按钮
Button addBtn = new Button("添加学生");
addBtn.setStyle("-fx-background-color: #4CAF50; -fx-text-fill: white;");
Button updateBtn = new Button("更新学生");
updateBtn.setStyle("-fx-background-color: #2196F3; -fx-text-fill: white;");
Button deleteBtn = new Button("删除学生");
deleteBtn.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
Button clearBtn = new Button("清空表单");
HBox buttonBox = new HBox(10);
buttonBox.getChildren().addAll(addBtn, updateBtn, deleteBtn, clearBtn);
// 统计信息
Label statsLabel = new Label();
statsLabel.setStyle("-fx-font-size: 14px;");
Button statsBtn = new Button("计算统计");
statsBtn.setOnAction(e -> {
double avg = studentList.stream()
.mapToDouble(Student::getScore)
.average()
.orElse(0);
double max = studentList.stream()
.mapToDouble(Student::getScore)
.max()
.orElse(0);
double min = studentList.stream()
.mapToDouble(Student::getScore)
.min()
.orElse(0);
statsLabel.setText(String.format("平均分: %.2f, 最高分: %.2f, 最低分: %.2f", avg, max, min));
});
// 事件处理
addBtn.setOnAction(e -> addStudent());
updateBtn.setOnAction(e -> updateStudent());
deleteBtn.setOnAction(e -> deleteStudent());
clearBtn.setOnAction(e -> clearForm());
// 选中表格行时填充表单
tableView.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
fillForm(newSelection);
}
});
// 布局
VBox leftBox = new VBox(10);
leftBox.setPadding(new Insets(10));
leftBox.getChildren().addAll(
new Label("学生信息管理"),
tableView,
statsBtn,
statsLabel
);
VBox rightBox = new VBox(10);
rightBox.setPadding(new Insets(10));
rightBox.setPrefWidth(300);
rightBox.getChildren().addAll(
new Label("学生信息录入"),
formGrid,
buttonBox
);
BorderPane root = new BorderPane();
root.setCenter(leftBox);
root.setRight(rightBox);
Scene scene = new Scene(root, 800, 500);
primaryStage.setTitle("学生成绩管理系统");
primaryStage.setScene(scene);
primaryStage.show();
}
private void addStudent() {
if (validateForm()) {
Student student = new Student(
nameField.getText(),
idField.getText(),
Double.parseDouble(scoreField.getText()),
gradeComboBox.getValue()
);
studentList.add(student);
clearForm();
showAlert("添加成功", "学生信息已添加");
}
}
private void updateStudent() {
Student selected = tableView.getSelectionModel().getSelectedItem();
if (selected != null && validateForm()) {
selected.setName(nameField.getText());
selected.setStudentId(idField.getText());
selected.setScore(Double.parseDouble(scoreField.getText()));
selected.setGrade(gradeComboBox.getValue());
tableView.refresh();
clearForm();
showAlert("更新成功", "学生信息已更新");
} else {
showAlert("错误", "请先选择要更新的学生");
}
}
private void deleteStudent() {
Student selected = tableView.getSelectionModel().getSelectedItem();
if (selected != null) {
studentList.remove(selected);
clearForm();
showAlert("删除成功", "学生信息已删除");
} else {
showAlert("错误", "请先选择要删除的学生");
}
}
private void fillForm(Student student) {
nameField.setText(student.getName());
idField.setText(student.getStudentId());
scoreField.setText(String.valueOf(student.getScore()));
gradeComboBox.setValue(student.getGrade());
}
private void clearForm() {
nameField.clear();
idField.clear();
scoreField.clear();
gradeComboBox.setValue(null);
}
private boolean validateForm() {
if (nameField.getText().isEmpty() ||
idField.getText().isEmpty() ||
scoreField.getText().isEmpty() ||
gradeComboBox.getValue() == null) {
showAlert("错误", "请填写所有必填字段");
return false;
}
try {
double score = Double.parseDouble(scoreField.getText());
if (score < 0 || score > 100) {
showAlert("错误", "成绩必须在0-100之间");
return false;
}
} catch (NumberFormatException e) {
showAlert("错误", "成绩必须是数字");
return false;
}
return true;
}
private void showAlert(String title, String message) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
// 学生类
public static class Student {
private String name;
private String studentId;
private double score;
private String grade;
public Student(String name, String studentId, double score, String grade) {
this.name = name;
this.studentId = studentId;
this.score = score;
this.grade = grade;
}
// Getter和Setter
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getStudentId() { return studentId; }
public void setStudentId(String studentId) { this.studentId = studentId; }
public double getScore() { return score; }
public void setScore(double score) { this.score = score; }
public String getGrade() { return grade; }
public void setGrade(String grade) { this.grade = grade; }
}
}
图表案例:数据可视化
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.chart.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class ChartDemo extends Application {
@Override
public void start(Stage primaryStage) {
VBox root = new VBox(20);
root.setPadding(new javafx.geometry.Insets(20));
// 1. 柱状图
CategoryAxis xAxis = new CategoryAxis();
NumberAxis yAxis = new NumberAxis(0, 100, 10);
BarChart<String, Number> barChart = new BarChart<>(xAxis, yAxis);
barChart.setTitle("各科成绩");
XYChart.Series<String, Number> series = new XYChart.Series<>();
series.setName("成绩");
series.getData().addAll(
new XYChart.Data<>("语文", 85),
new XYChart.Data<>("数学", 92),
new XYChart.Data<>("英语", 78),
new XYChart.Data<>("物理", 88),
new XYChart.Data<>("化学", 95)
);
barChart.getData().add(series);
// 2. 饼图
ObservableList<PieChart.Data> pieData = FXCollections.observableArrayList(
new PieChart.Data("学习", 30),
new PieChart.Data("工作", 40),
new PieChart.Data("休闲", 20),
new PieChart.Data("其他", 10)
);
PieChart pieChart = new PieChart(pieData);
pieChart.setTitle("时间分配");
// 3. 折线图
NumberAxis xAxis2 = new NumberAxis(1, 12, 1);
NumberAxis yAxis2 = new NumberAxis(0, 100, 10);
LineChart<Number, Number> lineChart = new LineChart<>(xAxis2, yAxis2);
lineChart.setTitle("全年销量");
XYChart.Series<Number, Number> lineSeries = new XYChart.Series<>();
lineSeries.setName("月度销量");
lineSeries.getData().addAll(
new XYChart.Data<>(1, 45),
new XYChart.Data<>(2, 60),
new XYChart.Data<>(3, 55),
new XYChart.Data<>(4, 75),
new XYChart.Data<>(5, 82),
new XYChart.Data<>(6, 70),
new XYChart.Data<>(7, 90),
new XYChart.Data<>(8, 85),
new XYChart.Data<>(9, 76),
new XYChart.Data<>(10, 88),
new XYChart.Data<>(11, 92),
new XYChart.Data<>(12, 95)
);
lineChart.getData().add(lineSeries);
root.getChildren().addAll(barChart, pieChart, lineChart);
ScrollPane scrollPane = new ScrollPane(root);
scrollPane.setFitToWidth(true);
Scene scene = new Scene(scrollPane, 800, 1200);
primaryStage.setTitle("数据可视化");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
使用建议
-
运行时需要添加JavaFX依赖,如果使用Maven,添加:
<dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>17.0.6</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-fxml</artifactId> <version>17.0.6</version> </dependency>
-
运行前配置VM参数(IDEA):
--module-path /path/to/javafx-sdk/lib --add-modules javafx.controls,javafx.fxml -
学习建议:
- 从基础控件开始练习
- 理解事件处理机制
- 熟悉FXML布局文件
- 多实践实际项目案例
这些案例涵盖了JavaFX的核心功能,您可以根据需求修改和扩展,希望这些示例对您有帮助!
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播