1.相关jar包依赖如下
<dependencies>
<dependency>
<groupId>de.roskenet</groupId>
<artifactId>springboot-javafx-support</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.6.7</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<version>2.6.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.6.7</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
<exclusions>
<exclusion>
<artifactId>spring-boot-autoconfigure</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
<exclusion>
<artifactId>spring-boot-starter</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
<exclusion>
<artifactId>spring-boot-starter-jdbc</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
<!-- 必须使用对应版本,否则会出现循环依赖问题 -->
</dependency>
</dependencies>
2.需要用到javafx的xml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane prefHeight="387.0" prefWidth="514.0" xmlns="http://javafx.com/javafx/8.0.202" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.sample.controller.StudentEditController">
<children>
<TextField fx:id="userIdTF" layoutX="154.0" layoutY="24.0" visible="false"/>
<Label layoutX="89.0" layoutY="71.0" text="姓名:"/>
<TextField fx:id="userNameTF" layoutX="154.0" layoutY="67.0" prefHeight="23.0" prefWidth="241.0"/>
<Label layoutX="89.0" layoutY="121.0" text="性别:"/>
<ChoiceBox fx:id="selectSex" layoutX="154.0" layoutY="117.0" prefHeight="23.0" prefWidth="241.0"/>
<Label layoutX="89.0" layoutY="174.0" text="年龄:"/>
<TextField fx:id="ageTF" layoutX="154.0" layoutY="170.0" prefHeight="23.0" prefWidth="241.0"/>
<Label layoutX="89.0" layoutY="233.0" text="手机:"/>
<TextField fx:id="phoneTF" layoutX="154.0" layoutY="229.0" prefHeight="23.0" prefWidth="241.0"/>
<Label layoutX="89.0" layoutY="288.0" text="地址:"/>
<TextField fx:id="addressTF" layoutX="154.0" layoutY="284.0" prefHeight="23.0" prefWidth="241.0"/>
<Button fx:id="resetBtn" layoutX="275.0" layoutY="341.0" mnemonicParsing="false" onAction="#resetClick" text="重置"/>
<Button fx:id="okBtn" layoutX="355.0" layoutY="341.0" mnemonicParsing="false" onAction="#submitClick" text="确定"/>
</children>
</AnchorPane>
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.text.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<GridPane hgap="10.0" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="1000.0" prefWidth="1400.0" vgap="10.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.sample.controller.MyController">
<columnConstraints>
<ColumnConstraints hgrow="SOMETIMES" maxWidth="617.0" minWidth="10.0" prefWidth="242.0"/>
<ColumnConstraints hgrow="SOMETIMES" maxWidth="1127.0" minWidth="10.0" prefWidth="1001.0"/>
</columnConstraints>
<rowConstraints>
<RowConstraints maxHeight="581.0" minHeight="10.0" prefHeight="471.0" vgrow="SOMETIMES"/>
<RowConstraints maxHeight="662.0" minHeight="10.0" prefHeight="519.0" vgrow="SOMETIMES"/>
</rowConstraints>
<children>
<Button fx:id="button1" mnemonicParsing="false" onAction="#btn1Click" text="按钮1">
<GridPane.margin>
<Insets bottom="400.0" left="20.0" right="20.0"/>
</GridPane.margin>
</Button>
<Button fx:id="btnFour" mnemonicParsing="false" text="按钮4" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0"/>
</GridPane.margin>
</Button>
<ImageView fx:id="imgView" fitHeight="297.0" fitWidth="302.0" pickOnBounds="true" preserveRatio="true">
<GridPane.margin>
<Insets left="10.0" right="10.0" top="120.0"/>
</GridPane.margin>
</ImageView>
<TableView fx:id="tableView" editable="true" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="412.0" prefWidth="1055.0" GridPane.columnIndex="1">
<GridPane.margin>
<Insets bottom="60.0" left="10.0" right="50.0" top="10.0"/>
</GridPane.margin>
<padding>
<Insets bottom="5.0" left="5.0" right="5.0" top="5.0"/>
</padding>
<columns>
<TableColumn fx:id="mColumnSelect" prefWidth="58" sortable="false" style="-fx-alignment:CENTER" text="选择"/>
</columns>
</TableView>
<Label fx:id="text" prefHeight="31.0" prefWidth="118.0">
<GridPane.margin>
<Insets bottom="400.0" left="120.0" right="10.0"/>
</GridPane.margin>
</Label>
<Button mnemonicParsing="false" onAction="#deleteSelected" prefHeight="23.0" prefWidth="67.0" text="删除选中">
<GridPane.margin>
<Insets bottom="400.0" left="210.0" right="10.0"/>
</GridPane.margin>
</Button>
<Button fx:id="btnSelectAll" mnemonicParsing="false" onAction="#selectAllOrNot" prefHeight="29.0" prefWidth="100.0">
<GridPane.margin>
<Insets bottom="300.0" left="210.0"/>
</GridPane.margin>
</Button>
<CheckBox fx:id="mSelectAll" mnemonicParsing="false" onAction="#selectAll2" prefHeight="28.0" prefWidth="60.0" text="全选">
<GridPane.margin>
<Insets bottom="200.0" left="210.0"/>
</GridPane.margin>
</CheckBox>
<Button fx:id="btnPrev" mnemonicParsing="false" onAction="#prevPage" text="上一页" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="180.0" top="160.0"/>
</GridPane.margin>
</Button>
<Button fx:id="btnNext" mnemonicParsing="false" onAction="#nextPage" text="下一页" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="720.0" top="160.0"/>
</GridPane.margin>
</Button>
<ChoiceBox fx:id="selectPage" prefWidth="86.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="10.0" top="160.0"/>
</GridPane.margin>
</ChoiceBox>
<Label text="前往:" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="790.0" top="160.0"/>
</GridPane.margin>
</Label>
<TextField fx:id="toPageNoText" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="23.0" prefWidth="51.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="850.0" top="160.0"/>
</GridPane.margin>
</TextField>
<Label text="页,共" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="920.0" top="160.0"/>
</GridPane.margin>
</Label>
<TextField fx:id="totalCountText" maxHeight="-Infinity" maxWidth="-Infinity" prefHeight="23.0" prefWidth="50.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="970.0" top="160.0"/>
</GridPane.margin>
</TextField>
<Button mnemonicParsing="false" text="条" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="1036.0" top="160.0"/>
</GridPane.margin>
</Button>
<Pagination fx:id="pagination" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="500.0" prefWidth="1055.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="160.0" left="10.0" top="162.0"/>
</GridPane.margin>
</Pagination>
<HBox fx:id="pageNoHBox" alignment="CENTER" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="23.0" prefWidth="430.0" spacing="10" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="240.0" top="160.0"/>
</GridPane.margin>
</HBox>
<Label text="共" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="100.0" top="160.0"/>
</GridPane.margin>
</Label>
<Text fx:id="totalPageText" strokeType="OUTSIDE" strokeWidth="0.0" wrappingWidth="36.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="120.0" top="160.0"/>
</GridPane.margin>
</Text>
<Label text="页" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="750.0" left="160.0" top="160.0"/>
</GridPane.margin>
</Label>
<Separator maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="10.0" prefWidth="1055.0" GridPane.columnIndex="1" GridPane.rowIndex="1">
<GridPane.margin>
<Insets bottom="540.0" left="10.0" top="10.0"/>
</GridPane.margin>
</Separator>
</children>
</GridPane>
3.对应的controller
StudentEditController控制器代码
package com.sample.controller;
import com.mysql.cj.util.StringUtils;
import com.sample.domain.Student;
import com.sample.service.StudentService;
import com.sample.utils.SpringContextUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.URL;
import java.util.Map;
import java.util.Objects;
import java.util.ResourceBundle;
@Component
public class StudentEditController implements Initializable {
public TextField userIdTF;
public TextField userNameTF;
public TextField ageTF;
public TextField phoneTF;
public TextField addressTF;
public ChoiceBox<String> selectSex;
public Button resetBtn;
public Button okBtn;
@Autowired
StudentService studentService;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public void resetClick(ActionEvent actionEvent) {
final String id = this.userIdTF.getText();
final Student student = this.studentService.selectByPrimaryKey(Long.valueOf(id));
if (Objects.nonNull(student)) {
final MyController controller = SpringContextUtil.getBean(MyController.class);
this.userIdTF.setText(student.getId() + "");
this.userNameTF.setText(student.getUserName());
final Map<String, String> sexData = controller.sexData();
ObservableList<String> options = FXCollections.observableArrayList(controller.options(sexData));
this.selectSex.setItems(options);
this.selectSex.setValue(controller.selectDefault(sexData, student));
this.ageTF.setText(student.getAge() + "");
this.phoneTF.setText(student.getMobilePhone());
this.addressTF.setText(student.getAddress());
}
}
public void submitClick(ActionEvent actionEvent) {
final String id = this.userIdTF.getText();
final String userName = this.userNameTF.getText();
final String sex = this.selectSex.getSelectionModel().getSelectedItem();
final String age = this.ageTF.getText();
final String phone = this.phoneTF.getText();
final String address = this.addressTF.getText();
Student student = new Student(Long.valueOf(id), userName, convertSex(sex), Integer.parseInt(age), phone, address);
this.studentService.updateByPrimaryKeySelective(student);
SpringContextUtil.getBean(MyController.class).setTableViewItems(this.studentService.selectAll());
}
private Integer convertSex(String str) {
if (StringUtils.isNullOrEmpty(str)) {
return null;
} else if ("女".equals(str)) {
return 0;
} else if ("男".equals(str)) {
return 1;
} else {
return 2;
}
}
}
MyController控制器代码
package com.sample.controller;
import com.github.pagehelper.PageInfo;
import com.sample.data.Checkbox;
import com.sample.data.controls.CusAlertUtil;
import com.sample.domain.Student;
import com.sample.service.StudentService;
import de.felixroske.jfxsupport.FXMLController;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;
@FXMLController
public class MyController implements Initializable {
private static final Logger log = LoggerFactory.getLogger(MyController.class);
@FXML
public Button button1;
public ImageView imgView;
public TableView<Student> tableView;
public Label text;
public TableColumn<Student, String> select;
public CheckBox mSelectAll;
public TableColumn<Student, CheckBox> mColumnSelect;
public Button btnSelectAll;
public Button btnPrev;
public Button btnNext;
public ChoiceBox<String> selectPage;
public TextField toPageNoText;
public TextField totalCountText;
@FXML
public Pagination pagination;
public HBox pageNoHBox;
public Text totalPageText;
public Button btnFour;
@Resource
StudentService studentService;
public Set<Long> checkedIdList = new HashSet<>();
int count = 0;
List<Button> buttonList = new ArrayList<>();
@Autowired
StudentEditController studentEditController;
Integer currentPage = 1;
public void btn1Click(ActionEvent actionEvent) throws IOException {
count += 1;
final Object source = actionEvent.getSource();
if (source instanceof Button) {
Button btn = (Button) source;
log.info("按钮名称:{},点击了:{}次", btn.getText(), count);
}
if (Objects.isNull(imgView.getImage())) {
imgView.setImage(new Image(getClass().getResourceAsStream("/image/login.jpg")));
} else {
log.info("图片已经加载了");
List<String> list = new ArrayList<>();
list.add("logo.jpg");
list.add("start.png");
list.add("upaiyun.gif");
list.add("seven.png");
list.add("eight.png");
list.add("login.jpg");
final int nextInt = new Random().nextInt(list.size());
final InputStream inputStream = getClass().getResourceAsStream("/image/" + list.get(nextInt));
if (inputStream != null) {
imgView.setImage(new Image(inputStream));
log.info("图片切换到---{}", list.get(nextInt));
inputStream.close();
}
}
String[] lArr = new String[]{"标签", "瓦打我的", "1111", "大大", "哦哦哦"};
final int nextInt = new Random().nextInt(lArr.length);
text.setText(lArr[nextInt]);
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
final PageInfo<Student> tablePage = getTablePage(currentPage, pageSize);
final long pageTotal = tablePage.getTotal();
if (pageTotal == 0) {
btnPrev.setDisable(true);
btnNext.setDisable(true);
} else {
btnPrev.setDisable(false);
btnNext.setDisable(false);
}
final int[] pageNums = tablePage.getNavigatepageNums();
log.info("分页组件----{}", pageNums);
setHBoxPaginationBtn(pageSize, pageNums);
btnPrev.setDisable(tablePage.getPrePage() == 0);
btnNext.setDisable(tablePage.getNextPage() == 0);
toPageNoText.setText(currentPage + "");
totalCountText.setText(pageTotal + "");
totalPageText.setText(tablePage.getPages() + "");
setTableViewItems(tablePage.getList());
pagination.setCurrentPageIndex(0);
pagination.setPageCount(tablePage.getPages());
pagination.setPageFactory(param -> createPage(param, pagination));
pagination.getParent().getScene().widthProperty().addListener((observable, oldValue, newValue) -> pagination.setMaxSize(newValue.doubleValue(), newValue.doubleValue()));
pagination.setStyle("-fx-text-fill: white;" +
"-fx-background-color: #fffffe;" +
"-fx-font: Courier New;" +
"-fx-font-family: Courier New;" +
"-fx-font-weight: bold;" +
"-fx-font-size: 14px;");
int buttonSize = 30;
pagination.setStyle(String.format("-fx-font-size: %dpx;", (int) (0.45 * buttonSize)));
}
@Override
public void initialize(URL location, ResourceBundle resources) {
btnSelectAll.setText("未选中");
text.setText("dasdadada");
button1.setText("按钮1");
final List<String> stringList = pageSizeSelectData().values().stream().sorted(Comparator.comparingInt(String::hashCode)).collect(Collectors.toList());
selectPage.getItems().addAll(FXCollections.observableList(stringList));
selectPage.setValue(stringList.get(0));
selectPage.getSelectionModel().selectedIndexProperty().addListener((observable, oldValue, newValue) -> {
int pageSize = getPageSize((Integer) newValue);
final PageInfo<Student> page = getTablePage(currentPage, pageSize);
final int pagePages = page.getPages();
if (currentPage == 1) {
btnPrev.setDisable(true);
btnNext.setDisable(false);
} else if (currentPage > 1 && currentPage < pagePages) {
btnPrev.setDisable(false);
btnNext.setDisable(false);
} else {
btnPrev.setDisable(false);
btnNext.setDisable(true);
}
final String text = toPageNoText.getText();
if (page.getTotal() == 0 || text.equals("")) {
toPageNoText.setText("1");
totalCountText.setText("0");
} else {
if (currentPage > pagePages) {
currentPage = pagePages;
}
toPageNoText.setText(currentPage + "");
totalCountText.setText(page.getTotal() + "");
}
totalPageText.setText(pagePages + "");
setHBoxPaginationBtn(pageSize, page.getNavigatepageNums());
setTableViewItems(page.getList());
});
// 设置自适应宽度
tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
tableView.setStyle(String.format("-fx-font-size: %dpx;", (int) (0.45 * 30)));
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
tableView.setEditable(true);
// 单击选中行
tableView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (Objects.nonNull(newValue)) {
final Checkbox checkbox = newValue.getCb();
final ObservableList<Student> items = tableView.getItems();
if (checkbox.isSelected()) {
checkbox.setSelected(false);
checkedIdList.remove(newValue.getId());
if (checkedIdList.size() == 0) {
btnSelectAll.setText("未选中");
}
if (checkedIdList.size() != 0 && checkedIdList.size() < items.size()) {
btnSelectAll.setText("部分选中");
}
} else {
checkbox.setSelected(true);
checkedIdList.add(newValue.getId());
if (checkedIdList.size() < items.size() && checkedIdList.size() > 0) {
btnSelectAll.setText("部分选中");
}
if (checkedIdList.size() == items.size()) {
btnSelectAll.setText("选中所有");
}
}
}
});
mColumnSelect.setCellFactory(new Callback<TableColumn<Student, CheckBox>, TableCell<Student, CheckBox>>() {
@Override
public TableCell<Student, CheckBox> call(TableColumn p) {
return new TableCell<Student, CheckBox>() {
@Override
public void updateItem(CheckBox item, boolean empty) {
super.updateItem(item, empty);
setGraphic(item);
if (Objects.nonNull(item)) {
item.selectedProperty().addListener((observable, oldValue, newValue) -> {
boolean booSelectAll = true;
final ObservableList<Student> items = tableView.getItems();
if (!CollectionUtils.isEmpty(items)) {
for (Student student : items) {
if (!student.getCb().isSelected()) {
booSelectAll = false;
btnSelectAll.setText("未选中");
break;
} else {
btnSelectAll.setText("选中所有");
}
}
}
mSelectAll.setSelected(booSelectAll);
});
}
}
};
}
});
// 初始化所有checkbox复选框
mColumnSelect.setCellValueFactory(param -> {
final ObservableValue<CheckBox> observableValue = param.getValue().getCb().getCheckBox();
final CheckBox checkBox = observableValue.getValue();
checkBox.setOnAction(event -> {
final Long id = param.getValue().getId();
final ObservableList<Student> items = tableView.getItems();
if (checkBox.isSelected()) {
checkedIdList.add(id);
if (checkedIdList.size() < items.size() && checkedIdList.size() > 0) {
btnSelectAll.setText("部分选中");
}
tableView.setSelectionModel(tableView.getSelectionModel());
} else {
checkedIdList.remove(id);
if (checkedIdList.size() < items.size() && checkedIdList.size() > 0) {
btnSelectAll.setText("部分选中");
tableView.setSelectionModel(tableView.getSelectionModel());
}
if (checkedIdList.size() == 0) {
btnSelectAll.setText("未选中");
}
}
});
return observableValue;
});
TableColumn<Student, String> idColumn = new TableColumn<>("ID");
idColumn.setCellValueFactory(param -> new SimpleStringProperty(String.valueOf(param.getValue().getId())));
TableColumn<Student, String> nameColumn = new TableColumn<>("姓名");
nameColumn.setEditable(true);
nameColumn.setOnEditCommit(event -> {
Student student = event.getRowValue();
student.setUserName(event.getNewValue());
final int result = studentService.updateName(student);
log.info("更新成功,执行条数:{},ID:{}", result, student.getId());
if (student.getCb().isSelected()) {
student.getCb().setSelected(false);
checkedIdList.remove(student.getId());
}
tableView.refresh();
});
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getUserName()));
TableColumn<Student, String> sexColumn = new TableColumn<>("性别");
sexColumn.setCellValueFactory(param -> new SimpleStringProperty(convertSex(param.getValue().getSex())));
TableColumn<Student, String> ageColumn = new TableColumn<>("年龄");
ageColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getAge() + ""));
TableColumn<Student, String> phoneColumn = new TableColumn<>("手机");
phoneColumn.setCellValueFactory(param -> new SimpleStringProperty(String.valueOf(param.getValue().getMobilePhone())));
TableColumn<Student, String> addressColumn = new TableColumn<>("地址");
addressColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getAddress()));
TableColumn<Student, Student> editColumn = new TableColumn<>("编辑");
// TODO 先赋值单元格
editColumn.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue()));
editColumn.setCellFactory(new Callback<TableColumn<Student, Student>, TableCell<Student, Student>>() {
@Override
public TableCell<Student, Student> call(TableColumn<Student, Student> tableColumn) {
return new TableCell<Student, Student>() {
@Override
public void updateItem(Student student, boolean empty) {
super.updateItem(student, empty);
if (!empty) {
Button editBtn = new Button("编辑");
Button delBtn = new Button("删除");
HBox pane = new HBox(20, editBtn, delBtn);
setGraphic(pane);
editBtn.setOnAction(event -> showStudentView(student));
delBtn.setOnAction(event -> {
final String pageNoTextText = toPageNoText.getText();
studentService.deleteByPrimaryKey(student.getId());
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
PageInfo<Student> tablePage = getTablePage(Integer.parseInt(pageNoTextText), pageSize);
if (currentPage > tablePage.getPages()) {
currentPage = tablePage.getPages();
}
toPageNoText.setText(tablePage.getPageNum() + "");
totalCountText.setText(tablePage.getTotal() + "");
totalPageText.setText(tablePage.getPages() + "");
setHBoxPaginationBtn(pageSize, tablePage.getNavigatepageNums());
setTableViewItems(tablePage.getList());
});
}
}
};
}
});
List<TableColumn<Student, ?>> columnList = new ArrayList<>();
columnList.add(idColumn);
columnList.add(nameColumn);
columnList.add(sexColumn);
columnList.add(ageColumn);
columnList.add(phoneColumn);
columnList.add(addressColumn);
columnList.add(editColumn);
tableView.getColumns().addAll(columnList);
btnNext.setDisable(true);
btnPrev.setDisable(true);
btnFour.setStyle(
"-fx-background-color: cadetblue;" +
"-fx-background-radius: 5;" +
"-fx-text-fill: antiquewhite;" +
"-fx-font-family: 'Microsoft YaHei UI';" +
"-fx-font-size: 14");
}
private TableView<Student> createPage(int pageNo, Pagination pagination) {
TableView<Student> studentTableView = new TableView<>();
studentTableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
TableColumn<Student, String> idColumn = new TableColumn<>("ID");
idColumn.setCellValueFactory(param -> new SimpleStringProperty(String.valueOf(param.getValue().getId())));
TableColumn<Student, String> nameColumn = new TableColumn<>("姓名");
nameColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getUserName()));
TableColumn<Student, String> sexColumn = new TableColumn<>("性别");
sexColumn.setCellValueFactory(param -> new SimpleStringProperty(convertSex(param.getValue().getSex())));
TableColumn<Student, String> ageColumn = new TableColumn<>("年龄");
ageColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getAge() + ""));
TableColumn<Student, String> phoneColumn = new TableColumn<>("手机");
phoneColumn.setCellValueFactory(param -> new SimpleStringProperty(String.valueOf(param.getValue().getMobilePhone())));
TableColumn<Student, String> addressColumn = new TableColumn<>("地址");
addressColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getAddress()));
TableColumn<Student, Student> editColumn = new TableColumn<>("编辑");
editColumn.setStyle("margin-left:100px;");
editColumn.setCellValueFactory(param -> new SimpleObjectProperty<>(param.getValue()));
editColumn.setCellFactory(new Callback<TableColumn<Student, Student>, TableCell<Student, Student>>() {
@Override
public TableCell<Student, Student> call(TableColumn<Student, Student> tableColumn) {
return new TableCell<Student, Student>() {
@Override
public void updateItem(Student student, boolean empty) {
super.updateItem(student, empty);
if (!empty) {
Button editBtn = new Button("编辑");
Button delBtn = new Button("删除");
HBox pane = new HBox(20, editBtn, delBtn);
setGraphic(pane);
editBtn.setOnAction(event -> showStudentView(student));
delBtn.setOnAction(event -> {
final Long id = student.getId();
final int result = studentService.deleteByPrimaryKey(id);
if (result > 0) {
int paginationPageNo = pageNo + 1;
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
PageInfo<Student> tablePage = getTablePage(paginationPageNo, pageSize);
// 总页数
final int totalPages = tablePage.getPages();
// 总条数
final long totalCount = tablePage.getTotal();
// 上一页码
final int prePageNo = tablePage.getPrePage();
// 下一页码
final int nextPageNo = tablePage.getNextPage();
// 当前页码
final int currPageNo = tablePage.getPageNum();
log.info("分页返回返回当前页码:{},上一页:{},下一页:{},总条数:{},总页数:{} ", currPageNo, prePageNo, nextPageNo, totalCount, totalPages);
studentTableView.setItems(FXCollections.observableList(tablePage.getList()));
pagination.setPageCount(totalPages);
if (paginationPageNo < currPageNo) {
if (prePageNo == 1) {
pagination.setCurrentPageIndex(1);
} else {
pagination.setCurrentPageIndex(paginationPageNo);
}
} else if (paginationPageNo == currPageNo) {
if (prePageNo != 0 && nextPageNo != 0) {
} else if (prePageNo == 0 && nextPageNo != 0) {
pagination.setCurrentPageIndex(1);
} else {
pagination.setCurrentPageIndex(totalPages);
}
} else {
if (prePageNo == 0) {
pagination.setCurrentPageIndex(1);
} else {
pagination.setCurrentPageIndex(paginationPageNo - 1);
}
}
studentTableView.refresh();
}
});
}
}
};
}
});
List<TableColumn<Student, ?>> columnList = new ArrayList<>();
columnList.add(idColumn);
columnList.add(nameColumn);
columnList.add(sexColumn);
columnList.add(ageColumn);
columnList.add(phoneColumn);
columnList.add(addressColumn);
columnList.add(editColumn);
studentTableView.getColumns().addAll(columnList);
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
final PageInfo<Student> page = getTablePage(pageNo + 1, pageSize);
studentTableView.refresh();
studentTableView.setItems(FXCollections.observableList(page.getList()));
return studentTableView;
}
private String convertSex(Integer sex) {
if (sex == null) {
return "无";
} else if (sex == 0) {
return "女";
} else if (sex == 1) {
return "男";
} else {
return "其他";
}
}
public void setTableViewItems(List<Student> list) {
tableView.setItems(FXCollections.observableList(list));
tableView.refresh();
}
/**
* 删除选中
*
* @param actionEvent 点击事件
* @author Administrator
* @date 2022-05-11 17:22:24
*/
public void deleteSelected(ActionEvent actionEvent) {
if (checkedIdList.size() == 0) {
CusAlertUtil.init(Alert.AlertType.WARNING, "提示", "当前未选中", "确定", ButtonBar.ButtonData.FINISH);
return;
}
final List<Student> studentList = studentService.selectAll();
if (studentList.size() == 0) {
CusAlertUtil.init(Alert.AlertType.WARNING, "提示", "当前无数据,不需要删除", "确定", ButtonBar.ButtonData.FINISH);
return;
}
final int count = studentService.deleteByIds(checkedIdList);
if (count > 0) {
log.info("成功删除:{} 条,id数组:{}", count, checkedIdList);
final Alert alert = CusAlertUtil.init(Alert.AlertType.INFORMATION, "提示", "成功删除:" + count + "条数据", "确定", ButtonBar.ButtonData.YES);
// 对话框关闭调用
alert.setOnCloseRequest(event -> {
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
final PageInfo<Student> tablePage = getTablePage(currentPage, pageSize);
if (currentPage > tablePage.getPages()) {
currentPage = tablePage.getPages();
}
toPageNoText.setText(currentPage + "");
totalCountText.setText(tablePage.getTotal() + "");
setTableViewItems(tablePage.getList());
if (tablePage.getList().size() == 0) {
btnSelectAll.setText("未选中");
}
});
}
checkedIdList.clear();
}
public void selectAllOrNot(ActionEvent actionEvent) {
checkedIdList.clear();
ObservableList<Student> items = tableView.getItems();
final String text = btnSelectAll.getText();
Alert alert = new Alert(Alert.AlertType.NONE, text, new ButtonType("确定", ButtonBar.ButtonData.YES));
alert.setTitle("提示");
alert.setOnCloseRequest(event -> log.info("对话框关闭了"));
alert.show();
}
public void selectAll2(ActionEvent actionEvent) {
checkedIdList.clear();
ObservableList<Student> items = tableView.getItems();
if (mSelectAll.isSelected()) {
for (Student student : items) {
student.getCb().setSelected(true);
checkedIdList.add(student.getId());
}
if (checkedIdList.size() == studentService.selectAll().size()) {
btnSelectAll.setText("全选");
}
} else {
for (Student student : items) {
student.getCb().setSelected(false);
}
checkedIdList.clear();
}
}
public void showStudentView(Student student) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(new ClassPathResource("layout/dataEdit.fxml").getURL());
loader.setControllerFactory(param -> studentEditController);
AnchorPane anchorPane = loader.load();
StudentEditController controller = loader.getController();
controller.userIdTF.setText(student.getId() + "");
controller.userNameTF.setText(student.getUserName());
ObservableList<String> options = FXCollections.observableArrayList(options(sexData()));
controller.selectSex.setItems(options);
controller.selectSex.setValue(selectDefault(sexData(), student));
controller.ageTF.setText(student.getAge() + "");
controller.phoneTF.setText(student.getMobilePhone());
controller.addressTF.setText(student.getAddress());
Stage stage = new Stage();
stage.setTitle("数据编辑");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(anchorPane);
stage.setScene(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public Map<String, String> sexData() {
Map<String, String> map = new HashMap<>(3);
map.put("0", "女");
map.put("1", "男");
map.put("2", "其他");
return map;
}
public Map<String, String> pageSizeSelectData() {
Map<String, String> map = new HashMap<>(5);
map.put("5", "5条/页");
map.put("10", "10条/页");
map.put("20", "20条/页");
map.put("50", "50条/页");
map.put("100", "100条/页");
return map;
}
public Integer pageSizeSelected(Map<String, String> map, String value) {
int pageSize = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
if (Objects.equals(entry.getValue(), value)) {
pageSize = Integer.parseInt(entry.getKey());
break;
}
}
return pageSize;
}
public ObservableList<String> options(Map<String, String> map) {
return FXCollections.observableArrayList(map.values());
}
public String selectDefault(Map<String, String> map, Student student) {
String str = null;
for (Map.Entry<String, String> entry : map.entrySet()) {
if (Objects.equals(entry.getKey(), student.getSex() + "")) {
str = entry.getValue();
break;
}
}
return str;
}
private void setHBoxPaginationBtn(int pageSize, int[] pageNums) {
if (pageNums.length > 0) {
buttonList.clear();
final ObservableList<Node> noHBoxChildren = pageNoHBox.getChildren();
noHBoxChildren.clear();
for (int pageNum : pageNums) {
final Button button = new Button(String.valueOf(pageNum));
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
button.setOnAction(event -> {
toPageNoText.setText(pageNum + "");
PageInfo<Student> pageInfo = getTablePage(pageNum, pageSize);
totalCountText.setText(pageInfo.getTotal() + "");
setTableViewItems(pageInfo.getList());
});
buttonList.add(button);
}
noHBoxChildren.addAll(buttonList);
}
}
public void prevPage(ActionEvent actionEvent) {
final String pageNoTextText = toPageNoText.getText();
this.currentPage = Integer.parseInt(pageNoTextText) - 1;
Button buttonPrev = (Button) actionEvent.getSource();
btnPrev.setDisable(pageNoTextText.equals("1"));
final String countTextText = totalCountText.getText();
if (countTextText.equals("0")) {
buttonPrev.setDisable(true);
btnNext.setDisable(true);
} else {
toPageNoText.setText(this.currentPage + "");
if (currentPage == 0) {
toPageNoText.setText("1");
this.currentPage = 1;
final Alert alert = CusAlertUtil.init(Alert.AlertType.INFORMATION, "提示", "已经到第一页啦", "确定", ButtonBar.ButtonData.YES);
buttonPrev.setDisable(true);
btnNext.setDisable(false);
return;
}
buttonPrev.setDisable(false);
btnNext.setDisable(false);
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
final PageInfo<Student> page = getTablePage(currentPage, pageSize);
totalCountText.setText(page.getTotal() + "");
totalPageText.setText(page.getPages() + "");
setTableViewItems(page.getList());
final int[] pageNums = page.getNavigatepageNums();
log.info("上一页分页页码数组----{}", pageNums);
setHBoxPaginationBtn(pageSize, pageNums);
}
}
public void nextPage(ActionEvent actionEvent) {
final String value = selectPage.getItems().get(selectPage.getSelectionModel().selectedIndexProperty().getValue());
int pageSize = pageSizeSelected(pageSizeSelectData(), value);
// 当前页码
final String pageNoTextText = toPageNoText.getText();
this.currentPage = Integer.parseInt(pageNoTextText) + 1;
Button buttonNext = (Button) actionEvent.getSource();
final String countTextText = totalCountText.getText();
if (countTextText.equals("0")) {
buttonNext.setDisable(true);
btnPrev.setDisable(true);
} else {
toPageNoText.setText(this.currentPage + "");
final PageInfo<Student> page = getTablePage(currentPage, pageSize);
final int pagePages = page.getPages();
if (currentPage >= pagePages) {
toPageNoText.setText(String.valueOf(pagePages));
final Alert alert = CusAlertUtil.init(Alert.AlertType.INFORMATION, "提示", "已经到最后一页啦", "确定", ButtonBar.ButtonData.YES);
buttonNext.setDisable(true);
btnPrev.setDisable(false);
return;
}
buttonNext.setDisable(false);
btnPrev.setDisable(false);
totalCountText.setText(page.getTotal() + "");
totalPageText.setText(page.getPages() + "");
setTableViewItems(page.getList());
final int[] pageNums = page.getNavigatepageNums();
log.info("下一页分页页码数组----{}", pageNums);
setHBoxPaginationBtn(pageSize, pageNums);
}
}
private int getPageSize(Integer newValue) {
final String value = selectPage.getItems().get(newValue);
return pageSizeSelected(pageSizeSelectData(), value);
}
private PageInfo<Student> getTablePage(Integer currentPage, Integer pageSize) {
return this.studentService.getPage(currentPage, pageSize);
}
}
其中一些测试需要的图片组件请自行将图片放入resources对应的目录下即可
4.对应实体及service等
实体类等
package com.sample.data;
import javafx.beans.InvalidationListener;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.CheckBox;
public class Checkbox {
CheckBox checkbox = new CheckBox();
public ObservableValue<CheckBox> getCheckBox() {
return new ObservableValue<CheckBox>() {
@Override
public void addListener(ChangeListener<? super CheckBox> listener) {
}
@Override
public void removeListener(ChangeListener<? super CheckBox> listener) {
}
@Override
public CheckBox getValue() {
return checkbox;
}
@Override
public void addListener(InvalidationListener listener) {
}
@Override
public void removeListener(InvalidationListener listener) {
}
};
}
public Boolean isSelected() {
return checkbox.isSelected();
}
public void setSelected(boolean selected) {
checkbox.setSelected(selected);
}
}
package com.sample.domain;
import com.sample.data.Checkbox;
import java.io.Serializable;
import java.util.StringJoiner;
public class Student implements Serializable {
private static final long serialVersionUID = -5397888192572707455L;
public Student() {
super();
}
public Student(Long id, String userName, Integer sex, Integer age, String mobilePhone, String address) {
this.id = id;
this.userName = userName;
this.sex = sex;
this.age = age;
this.mobilePhone = mobilePhone;
this.address = address;
}
private Long id;
private String userName;
private Integer sex;
private Integer age;
private String mobilePhone;
private String address;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
private Checkbox cb = new Checkbox();
public Checkbox getCb() {
return cb;
}
public void setSelected(Checkbox cb) {
this.cb = cb;
}
@Override
public String toString() {
return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
.add("id=" + id)
.add("userName='" + userName + "'")
.add("sex=" + sex)
.add("age=" + age)
.add("mobilePhone='" + mobilePhone + "'")
.add("address='" + address + "'")
.toString();
}
}
接口及实现类
package com.sample.service;
import com.github.pagehelper.PageInfo;
import com.sample.domain.Student;
import java.util.Collection;
import java.util.List;
public interface StudentService {
int deleteByPrimaryKey(Long id);
int insert(Student record);
Student selectByPrimaryKey(Long id);
List<Student> selectAll();
int updateName(Student record);
int deleteByIds(Collection<Long> checkedIdList);
PageInfo<Student> getPage(Integer currentPage, Integer pageSize);
}
package com.sample.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sample.domain.Student;
import com.sample.mapper.StudentMapper;
import com.sample.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
@Service
@Transactional(rollbackFor = Exception.class)
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public int deleteByPrimaryKey(Long id) {
return studentMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(Student record) {
return studentMapper.insert(record);
}
@Override
@Transactional(readOnly = true)
public Student selectByPrimaryKey(Long id) {
return studentMapper.selectByPrimaryKey(id);
}
@Override
@Transactional(readOnly = true)
public List<Student> selectAll() {
return studentMapper.selectAll();
}
@Override
public int updateName(Student record) {
return studentMapper.updateName(record);
}
@Override
public int deleteByIds(Collection<Long> checkedIdList) {
return studentMapper.deleteByIds(checkedIdList);
}
@Override
@Transactional(readOnly = true)
public PageInfo<Student> getPage(Integer currentPage, Integer pageSize) {
PageHelper.startPage(currentPage, pageSize);
final List<Student> students = this.selectAll();
return new PageInfo<>(students);
}
}
mybatis的xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sample.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.sample.domain.Student">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="user_name" jdbcType="VARCHAR" property="userName"/>
<result column="sex" jdbcType="TINYINT" property="sex"/>
<result column="age" jdbcType="INTEGER" property="age"/>
<result column="mobile_phone" jdbcType="VARCHAR" property="mobilePhone"/>
<result column="address" jdbcType="VARCHAR" property="address"/>
</resultMap>
<sql id="Base_Column_List">
id, user_name, sex, age, mobile_phone, address
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from fx_student
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete
from fx_student
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.sample.domain.Student">
insert into fx_student (id, user_name, sex,
age, mobile_phone, address)
values (#{id,jdbcType=BIGINT}, #{userName,jdbcType=VARCHAR}, #{sex,jdbcType=TINYINT},
#{age,jdbcType=INTEGER}, #{mobilePhone,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR})
</insert>
<select id="selectAll" resultMap="BaseResultMap">
SELECT <include refid="Base_Column_List"/> FROM fx_student
</select>
<update id="updateName">
UPDATE fx_student SET user_name = #{userName,jdbcType=VARCHAR} WHERE id = #{id,jdbcType=BIGINT}
</update>
<delete id="deleteByIds">
DELETE FROM fx_student WHERE id IN
<if test="ids != null and ids.size() != 0">
<foreach collection="ids" item="item" index="index" open="(" separator="," close=")">
#{item,jdbcType=BIGINT}
</foreach>
</if>
</delete>
</mapper>
建表SQL
CREATE TABLE `fx_student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` varchar(255) DEFAULT NULL COMMENT '姓名',
`sex` tinyint(25) DEFAULT NULL COMMENT '0:女;1:男;3:其他',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`mobile_phone` varchar(12) DEFAULT NULL COMMENT '手机号',
`address` varchar(255) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
SpringContextUtil工具类
package com.sample.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return applicationContext.getBean(clz);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
}
5.springboot启动类设置
package com.sample;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
@MapperScan(basePackages = "com.sample.mapper")
@SpringBootApplication
public class FxApplicationMain extends AbstractJavaFxApplicationSupport implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(FxApplicationMain.class);
public static void main(String[] args) {
launch(FxApplicationMain.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("系统正在启动中....");
// 假装加载资源1.5s
Thread.sleep(1500);
}
@Override
public void start(Stage primaryStage) throws Exception {
// 使用了springboot故使用ClassPathResource加载fxml文件
Parent root = FXMLLoader.load(new ClassPathResource("layout/sample.fxml").getURL());
final Scene scene = new Scene(root);
primaryStage.setTitle("Hello World");
super.start(primaryStage);
}
}
6.查看表格分页效果
点击“按钮1”即可看到分页的效果
7.Javafx本身的插件及idea的javafx插件
请自行安装JavaFX Scene Builder 2.0并且在idea中配置(这里就不详细说明了)
如若遇到javafx的xml直接点击Scene Builder出现错误提示,请自行安装JavaFX与JavaFX Runtime for Plugins插件即可