JavaFx:基本的访问mysql的demo(手动构建方式)

Posted 你是小KS

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaFx:基本的访问mysql的demo(手动构建方式)相关的知识,希望对你有一定的参考价值。

开发环境:jdk8openjfx11.0.2eclipse

1. 声明

当前内容主要学习和了解javafx来实现窗体程序,主要为基本的代码方式实现mysql访问校验器,当前内容主要参考:java官方文档

主要为:

  1. 表格的创建
  2. 获取和写入输入框输入文本
  3. button的点击事件

2.前期准备

1.下载javafx的库openjfx-11.0.2_windows-x64_bin-sdk(本人以库的方式导入,来使用):openjfx

2.直接解压,然后拷贝lib到项目工程中,并加入依赖:

由于是openjfx是使用java 11编译,但是项目中只使用java8,所以还是可以使用,只是有的可能不能正常使用(基本的还是可以使用的)

基本pom,mysql的依赖

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>6.0.6</version>
</dependency>

3.开始编写程序


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
/**
 * 
 * @author hy
 * @createTime 2021-07-18 15:53:32
 * @description 一个简单的mysql连接器的javafx的demo
 *
 */
public class JavaFxMySqlConnectionTest extends Application {
	private static boolean hasDriver = false;
	static {
		//	开始加载驱动
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			hasDriver = true;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void start(Stage primaryStage) throws Exception {
		primaryStage.setTitle("JavaFX Welcome");
		GridPane grid = drawContent();
		Scene scene = new Scene(grid, 300, 275);
		primaryStage.setScene(scene);
		primaryStage.show();
		
	}

	/**
	 * 
	 * @author hy
	 * @createTime 2021-07-18 15:51:52
	 * @description 开始画表格,并填充表格
	 * @return
	 *
	 */
	private GridPane drawContent() {
		// 这里是开始画图设置网格table
		GridPane grid = new GridPane();
		grid.setAlignment(Pos.CENTER);
		grid.setHgap(10);
		grid.setVgap(10);
		grid.setPadding(new Insets(25, 25, 25, 25));

		Text scenetitle = new Text("欢迎使用mysql访问测试工具");
		scenetitle.setFont(Font.font("宋体", FontWeight.NORMAL, 20));
		grid.add(scenetitle, 0, 0, 2, 1);

		Label hostLable = new Label("mysql host:");
		grid.add(hostLable, 0, 1);

		TextField hostField = new TextField();
		grid.add(hostField, 1, 1);

		Label port = new Label("mysql port:");
		grid.add(port, 0, 2);

		TextField portField = new TextField();
		grid.add(portField, 1, 2);

		Label userName = new Label("mysql username:");
		grid.add(userName, 0, 3);

		TextField userTextField = new TextField();
		grid.add(userTextField, 1, 3);

		Label pw = new Label("mysql password:");
		grid.add(pw, 0, 4);

		PasswordField passwordField = new PasswordField();
		grid.add(passwordField, 1, 4);

		Button btn = new Button("test");
		HBox hbBtn = new HBox(10);
		hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
		hbBtn.getChildren().add(btn);
		grid.add(hbBtn, 1, 5);

		final Text actiontarget = new Text();
		grid.add(actiontarget, 1, 7);
		if (!hasDriver) {
			actiontarget.setFill(Color.GREEN);
			actiontarget.setText("无法加载驱动......");
			btn.setDisable(true);
		}

		// 开始添加点击事件
		addBtnClickEvent(btn, actiontarget, userTextField, passwordField, portField, hostField);
		return grid;
	}

	ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2);

	void addBtnClickEvent(Button btn, Text actiontarget, TextField userTextField, PasswordField passwordField,
			TextField portField, TextField hostField) {

		// 这个表示为Sign in添加一个动作时间
		btn.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent e) {
				cleanUpForm(actiontarget,userTextField,passwordField,portField,hostField);
				//System.out.println("Sign in按钮点击事件:" + e.getEventType());
				String usernameString = userTextField.getText();
				String passwordString = passwordField.getText();
				String portString = portField.getText();
				String hostString = hostField.getText();
				if (isBlack(hostString)) {
					hostString = "localhost";
					hostField.setText("localhost");
				}
				if (isBlack(portString)) {
					portField.setText("3306");
					portString = "3306";
				}

				Integer port = null;
				try {
					port = Integer.valueOf(portString);
				} catch (Exception e2) {
				}

				if (port == null || port <= 0) {
					actiontarget.setFill(Color.GREEN);
					actiontarget.setText("请输入正确的端口!");
					return;
				}

				if (isBlack(usernameString)) {
					userTextField.setText("root");
					usernameString = "root";
				}
				if (isBlack(passwordString)) {
					passwordField.setText("root");
					passwordString = "root";
				}
				final String conHost = hostString;
				final String conUsername = usernameString;
				final String conPassword = passwordString;
				final int conPort = port;
				//System.out.println("username=" + usernameString + ",password=" + passwordString + ",port=" + port);
				newFixedThreadPool.submit(() -> {
					btn.setDisable(true);
					boolean testCanConnection = testCanConnection(conHost, conPort, conUsername, conPassword);
					showConnectionResult(testCanConnection, actiontarget);
					btn.setDisable(false);
				});

			}
		});
	}

	/**
	 * 重写当前的停止的方法
	 */
	@Override
	public void stop() throws Exception {
		// TODO Auto-generated method stub
		super.stop();
		newFixedThreadPool.shutdownNow();
	}

	/**
	 * 
	 * @author hy
	 * @createTime 2021-07-18 15:49:36
	 * @description 清空当前的填写的表单信息和当前的提示信息
	 * @param actiontarget
	 * @param userTextField
	 * @param passwordField
	 * @param portField
	 * @param hostField
	 *
	 */
	private void cleanUpForm(Text actiontarget, TextField userTextField, PasswordField passwordField,
			TextField portField, TextField hostField) {
		// 清空颜色
		actiontarget.setFill(Color.WHITE);
		actiontarget.setText("");
		String emptyValue = "";
		userTextField.setText(emptyValue);
		passwordField.setText(emptyValue);
		portField.setText(emptyValue);
		hostField.setText(emptyValue);
	}

	/**
	 * 
	 * @author hy
	 * @createTime 2021-07-18 15:49:57
	 * @description 检查当前的字符串是否为空
	 * @param text
	 * @return
	 *
	 */
	private boolean isBlack(String text) {
		if (text == null || "".equals(text.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @author hy
	 * @createTime 2021-07-18 15:50:11
	 * @description 测试是否可以连接当前的mysql
	 * @param host
	 * @param port
	 * @param username
	 * @param password
	 * @return
	 *
	 */
	public boolean testCanConnection(String host, int port, String username, String password) {
		String connString = "jdbc:mysql://" + host + ":" + port
				+ "/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
		Connection conn = null;
		boolean success = false;
		try {
			conn = DriverManager.getConnection(connString, username, password);
			success = true;
		} catch (SQLException e) {

		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {

				}
			}
		}
		return success;
	}

	/**
	 * 
	 * @author hy
	 * @createTime 2021-07-18 15:50:25
	 * @description 显示最后的连接结果(测试是否连接成功或者连接失败)
	 * @param testCanConnection
	 * @param actiontarget
	 *
	 */
	private void showConnectionResult(boolean testCanConnection, Text actiontarget) {
		if (testCanConnection) {
			actiontarget.setFill(Color.GREEN);
			actiontarget.setText("连接mysql成功!");
		} else {
			actiontarget.setFill(Color.RED);
			actiontarget.setText("连接mysql失败!");
		}
	}

	public static void main(String[] args) {
		launch(args);
	}
}

4. 开始测试

点击test

成功会显示绿色,不成功显示红色

以上是关于JavaFx:基本的访问mysql的demo(手动构建方式)的主要内容,如果未能解决你的问题,请参考以下文章

利用JavaFX访问MySQL数据库

JavaFX不会连接到MYSQL [重复]

J3002.JavaFX组件扩展——StringField

javaFx(记事本)Demo

JavaFX入门:简单Demo-学习NetBeans开发平台

在 JavaFX Spinner 中手动输入文本不会更新值(除非用户按 ENTER)