JavaFx+Mysql 实现学籍管理系统

 前言

最近初学MySQL,利用MySQL与Javafx写了一个小型学籍管理系统。因为是初学,在很多方面技术都太成熟,写的很乱(原因是中间剽窃了很多人的智慧,借鉴了不少人的代码),最终才写完了一个勉强能看的作品。

ER图

 MAIN方法

package application;
	
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import java.util.Objects;
/*
 * 程序入口
 */
public class Main extends Application{
	public void start(Stage primaryStage) {
		try {
			Pane loginPane = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/resources/fxml_Login.fxml")));
			Scene loginScene = new Scene(loginPane,450,300);
			primaryStage.setScene(loginScene);
			primaryStage.setTitle("懿儇的垃圾系统");
			primaryStage.show();
			primaryStage.setResizable(false);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		launch(args);
	}
}

连接数据库

package application;

import table.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



public class DataBase {


	Connection connection = null;
	ResultSet rs = null;
	//mysql数据库url

	private static String userName=null;
	private static String password=null;
	private static String url= "jdbc:mysql://localhost:3306/stumanager?user=root&password=123456&useUnicode=true&characterEncoding=gbk&useSSL=false";
//	Connection connect;
	boolean pd;
	public DataBase() {
		try {
			//mysql数据库设置驱动程序类型
			Class.forName("com.mysql.jdbc.Driver"); 
			System.out.println("mysql数据库驱动加载成功");
		}
		catch(java.lang.ClassNotFoundException e) {
			e.printStackTrace();
		}
	}


	public DataBase(String a, String b) {
		this();
		DataBase.userName=a;
		DataBase.password=b;
		String sql = "select * from user where userName= ? and password = ?; ";
	}


	/*public boolean DataBase(String a, String b) throws Exception{
		//执行SQL语句,并接收结果
		String sql = "select * from user where userName= ? and password = ?; ";

		PreparedStatement ps = connect.prepareStatement(sql);
		ps.setString(1,a);
		ps.setString(2,b);
		ResultSet rs = ps.executeQuery();

		if(rs.next()){
			pd= true;
		}else{
			pd = false;
		}
		ps.close();
		return pd;
	}*/

    /*
	public boolean yanzheng (String a,String b) throws Exception{
		//执行SQL语句,并接收结果
		String sql = "select * from user where userName= ? and password = ?; ";
		PreparedStatement ps;
		ps = connection().Statement(sql);
		ps.setString(1,a);
		ps.setString(2,b);
		ResultSet rs = ps.executeQuery();
		boolean pdd=false;
		while (rs.next()){
			pdd=true;
		}
		System.out.println(a+"er");
		System.out.println(pdd+"wer");
		ps.close();
		return pdd;
	}*/
	//连接数据库
	public boolean connect()
	{
		if(url==null)
		{
			return false;
		}

		try{
			//mysql数据库
			connection = DriverManager.getConnection(url);
			//sqlserver数据库
			//connection = DriverManager.getConnection(urlSqlServer);
			if(connection!=null){
				System.out.println("数据库连接成功");
				return true;
			}
			return false;
		}
		catch(Exception e){
			//e.printStackTrace();
			System.out.println("数据库连接失败");
			return false;
		}
	}
	/*public Connection connect()
	{

		try{
			//mysql数据库
			return DriverManager.getConnection(url);
		}
		catch(Exception e){
			System.out.println("数据库连接失败");
		}
		return null;
	}*/
	//连接失败
	public void disconnect(){
		try{
			if(connection != null){
				connection.close();
				connection = null;
			}
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	//查询
	public ResultSet executeQuery(String sql) {
		try {
			System.out.println("executeQuery(SQL) = " + sql);
			PreparedStatement pstm = connection.prepareStatement(sql);
			// 执行查询
			rs = pstm.executeQuery();
		} 
		catch(SQLException ex) { 
			ex.printStackTrace();
		}
		return rs;
	}
	public ResultSet executeQuery1(String sql,String un, String pw) {
		try {
			System.out.println(sql + un+pw);
			PreparedStatement pstm = connection.prepareStatement(sql);
			pstm.setString(1,un);
			pstm.setString(2,pw);
			// 执行查询
			rs=pstm.executeQuery();

		}
		catch(SQLException ex) {
			ex.printStackTrace();
		}
		return rs;
	}
	public void executeQuery2(String sql,String un, String pw) {
		try {
			System.out.println(sql + un+pw);
			PreparedStatement pstm = connection.prepareStatement(sql);
			pstm.setString(1,un);
			pstm.setString(2,pw);
			// 执行查询
			pstm.executeUpdate();

		}
		catch(SQLException ex) {
			ex.printStackTrace();
		}
	}
	//executeUpdate 的返回值是一个整数,指示受影响的行数(即更新计数)。
	public int executeUpdate(String sql) {
		int count = 0;
		connect();
		try {
			Statement stmt = connection.createStatement();
			count = stmt.executeUpdate(sql);
			} 
		catch(SQLException ex) { 
			System.err.println(ex.getMessage());
			return -1;
		}
		disconnect();
		return count;
	}


}

登录界面

登录界面FX代码

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="300.0" prefWidth="450.0" style="-fx-background-color: #90EE90;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="control.LoginControl">
   <children>
      <Label layoutX="74.0" layoutY="168.0" text="密码" textAlignment="CENTER">
         <font>
            <Font size="20.0" />
         </font>
      </Label>
      <PasswordField fx:id="mima" layoutX="149.0" layoutY="167.0" promptText="" />
      <Button fx:id="btn_login" layoutX="150.0" layoutY="206.0" mnemonicParsing="false" onAction="#loginDataBase" prefHeight="30.0" prefWidth="80.0" text="登录" textFill="RED">
         <font>
            <Font size="18.0" />
         </font>
      </Button>
      <Label contentDisplay="CENTER" layoutX="106.0" layoutY="214.0" textAlignment="CENTER" wrapText="true">
         <font>
            <Font size="14.0" />
         </font>
      </Label>
      <ImageView fitHeight="32.0" fitWidth="32.0" layoutX="114.0" layoutY="255.0">
         <image>
            <Image url="@../image/time.png" />
         </image>
      </ImageView>
      <TextField fx:id="text_time" alignment="CENTER" disable="true" editable="false" layoutX="196.0" layoutY="254.0" prefHeight="34.0" prefWidth="150.0" text="1970年1月1日">
         <font>
            <Font size="16.0" />
         </font>
      </TextField>
      <Label alignment="CENTER" contentDisplay="CENTER" layoutX="117.0" layoutY="29.0" text="欢迎使用懿儇的垃圾系统" textAlignment="CENTER" wrapText="true">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <ComboBox fx:id="asd" editable="true" layoutX="150.0" layoutY="72.0" prefWidth="150.0" promptText="选择方式" />
      <Label layoutX="74.0" layoutY="124.0" text="账号">
         <font>
            <Font size="20.0" />
         </font>
      </Label>
      <TextField fx:id="zhang" layoutX="149.0" layoutY="123.0" />
      <Button fx:id="btn_login_deng" layoutX="271.0" layoutY="206.0" mnemonicParsing="false" onAction="#btn_login_denglu" prefHeight="30.0" prefWidth="80.0" text="注册" textFill="#bf26d3">
         <font>
            <Font size="18.0" />
         </font>
      </Button>
   </children>
</AnchorPane>d

登陆界面FXMLcontrol

package control;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.ResourceBundle;

import application.DataBase;
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.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.control.ComboBox;
import table.User;
import javax.swing.*;

public class LoginControl implements Initializable{
	@FXML
	public PasswordField mima;
	public TextField zhang;

	//private TextField text_userName;
	//private TextField text_DataBaseName;
	@FXML
	private Button btn_login;
	@FXML
	private TextField text_time;
	@FXML
	private ComboBox<String> asd;
	@FXML
	private TextField text_IP;
	final static String[] optionsName =new String[] {"学生登录","教师登录"};

	@Override //时间和IP显示
	public void initialize(URL location, ResourceBundle resources)
	{
		Date date =new Date();
		DateFormat longFormat=DateFormat.getDateInstance(DateFormat.LONG);
		InetAddress localAddress=null;
		try {
			localAddress=InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		text_time.setText(longFormat.format(date));
		text_time.setTooltip(new Tooltip("当前时间"));

		mima.requestFocus();
		ObservableList<String> Options =
				FXCollections.observableArrayList(optionsName);
		asd.setItems(Options);
		asd.setTooltip(new Tooltip("选择一个查询项"));
	}
	@FXML    //登录
	void loginDataBase(ActionEvent event) throws Exception {
		DataBase DB=new DataBase();
      System.out.println(mima.getText().trim());
		if(DB.connect()){
			if(User.yanzheng(zhang.getText().trim(),mima.getText().trim())){
			actionStage();//切换场景到选择面板
			DB.disconnect();
		}
		}else{
			System.out.println("登录失败");
			Alert loginError = new Alert(Alert.AlertType.ERROR);
			loginError.initStyle(StageStyle.UNIFIED);//最少平台显示
			loginError.setHeaderText("登录失败");
			loginError.setTitle("错误");
			String ERROR_TEXT="1.请检查账号是否输入正确";
			loginError.setContentText(ERROR_TEXT);
			loginError.show();
		}


	}

	//登陆成功界面跳转
	private void actionStage() throws IOException
	{

		//获取当前场景且关闭
     Stage loginStage = (Stage) btn_login.getScene().getWindow();
       loginStage.close();
		//选择场景出现
		try {
			int index=0;
			for(int i=0;i<optionsName.length;++i)
			{
				if(optionsName[i].compareTo(asd.getValue().trim())==0)
				{
					index=i;
					break;
				}
			}     //学生登陆
			if(index==0){
//            FXMLLoader fxmlLoader = new FXMLLoader(LoginControl.class.getResource("/fxml_Student.fxml"));
				Pane loginPane = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/resources/fxml_Student.fxml")));
				Stage stage =new Stage();
				Scene scene = new Scene(loginPane, 500, 410);
				stage.setScene(scene);
				stage.show();
			}


			else{   //教师登录
				Pane teachertPane = FXMLLoader.load(getClass().getResource("/resources/fxml_Teacher.fxml"));
				Scene teacherScene = new Scene(teachertPane,1520,800);
				Stage teacherStage=new Stage();
				teacherStage.setScene(teacherScene);
				teacherStage.setTitle("学籍信息管理");
				teacherStage.show();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void btn_login_denglu(ActionEvent actionEvent) throws IOException {
		Stage loginStage = (Stage) btn_login.getScene().getWindow();
		loginStage.close();
		Pane loginPane = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/resources/fxml_zhuce.fxml")));
		Stage stage =new Stage();
		Scene scene = new Scene(loginPane, 500, 350);
		stage.setScene(scene);
		stage.show();
	}}




注册界面

注册界面FX

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>

<AnchorPane prefHeight="350.0" prefWidth="500.0" style="-fx-background-color: #87CEFA;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="control.ZhuceControl">
   <children>
      <Label layoutX="190.0" layoutY="51.0" text="注册新用户">
         <font>
            <Font size="27.0" />
         </font>
      </Label>
      <Label layoutX="94.0" layoutY="127.0" text="账号">
         <font>
            <Font size="21.0" />
         </font>
      </Label>
      <Label layoutX="94.0" layoutY="199.0" text="密码">
         <font>
            <Font size="21.0" />
         </font>
      </Label>
      <TextField fx:id="mmm" layoutX="166.0" layoutY="198.0" />
      <Button fx:id="ddd" layoutX="224.0" layoutY="263.0" mnemonicParsing="false" onAction="#sss" text="注册">
         <font>
            <Font size="20.0" />
         </font>
      </Button>
      <TextField fx:id="zzz" layoutX="166.0" layoutY="126.0" />
   </children>
</AnchorPane>

注册界面control

package control;

import application.DataBase;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import table.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

public class ZhuceControl {
    public static DataBase DB=new DataBase();
    @FXML
    private Button ddd;

    @FXML
    private TextField zzz;

    @FXML
    private TextField mmm;

    @FXML
    void sss(ActionEvent event) throws Exception {

            DataBase DB=new DataBase();
            if(DB.connect()) {

                    if  (User.yanzheng(zzz.getText().trim(), mmm.getText().trim())) {
                        System.out.println("注册失败");
                        Alert loginError = new Alert(Alert.AlertType.ERROR);
                        loginError.initStyle(StageStyle.UNIFIED);//最少平台显示
                        loginError.setHeaderText("注册失败");
                        loginError.setTitle("错误");
                        String ERROR_TEXT = "请检查账号是否重复";
                        loginError.setContentText(ERROR_TEXT);
                        loginError.show();
                    }else{
                        if (User.zhuce(zzz.getText().trim(), mmm.getText().trim())) {
                    DB.disconnect();
                    System.out.println("注册成功");
                    Stage loginStage = (Stage) ddd.getScene().getWindow();
                    loginStage.close();
                    Pane loginPane = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("/resources/fxml_Login.fxml")));
                    Stage stage =new Stage();
                    Scene scene = new Scene(loginPane, 450, 300);
                    stage.setScene(scene);
                    stage.show();
                    }
                }}



            }}












教师界面

 教师界面FX

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.collections.*?>
<?import javafx.scene.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.paint.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="650.0" prefWidth="1500.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="control.TeacherControl">

   <top>
      <MenuBar fx:id="menus" prefHeight="4.0" prefWidth="652.0" BorderPane.alignment="CENTER">
        <menus>
          <Menu fx:id="menu_edit" mnemonicParsing="false" text="编辑" />
          
          <Menu fx:id="menu_help" mnemonicParsing="false" text="帮助" />
          
        </menus>
      </MenuBar>
   </top>
   <center>
      <BorderPane prefWidth="615.0" BorderPane.alignment="CENTER">
         <bottom>
            <HBox fx:id="HBox_application" prefHeight="35.0" prefWidth="600.0" BorderPane.alignment="CENTER">
               <children>
                  <Button fx:id="btn_add" mnemonicParsing="false" onAction="#addStudent" prefHeight="35.0" prefWidth="100.0" text="新增" />
                  <ComboBox fx:id="comboBox" onAction="#comboBoxSelectOption" prefHeight="35.0" prefWidth="100.0" value="请选择">
                  	
				  </ComboBox>
                   	
                  <TextField fx:id="text_select" prefHeight="35.0" prefWidth="250.0" />
                  <Button fx:id="btn_select" mnemonicParsing="false" onAction="#selectStudent" prefHeight="40.0" prefWidth="60.0" text="查询" />
                  <Button fx:id="btn_modify" mnemonicParsing="false" onAction="#modifyStudent" prefHeight="35.0" prefWidth="70.0" text="修改" />
                  <Button fx:id="btn_delete" mnemonicParsing="false" onAction="#deleteStudent" prefHeight="35.0" prefWidth="100.0" text="删除" textFill="#f20c0c" />
               </children>
            </HBox>
         </bottom>
         <center>
            <ScrollPane fx:id="scrollpane" fitToHeight="true" fitToWidth="true" prefHeight="330.0" prefViewportHeight="360.0" prefViewportWidth="605.0" prefWidth="610.0" vbarPolicy="ALWAYS" BorderPane.alignment="CENTER">
               <content>
                  <TableView fx:id="tableView" editable="true" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" BorderPane.alignment="CENTER">
                    <columns>
                      <TableColumn fx:id="table_StudentID" minWidth="100.0" prefWidth="150.0" text="学号" />
                      <TableColumn fx:id="table_Name" minWidth="100.0" prefWidth="150.0" text="姓名" />
                        <TableColumn fx:id="table_Sex" minWidth="100.0" prefWidth="150.0" text="性别" />
                        <TableColumn fx:id="table_ClassName" minWidth="100.0" prefWidth="150.0" text="班级" />
                        <TableColumn fx:id="table_Department" minWidth="100.0" prefWidth="150.0" text="院系" />
                        <TableColumn fx:id="table_birthday" minWidth="100.0" prefWidth="150.0" text="生日" />
                        <TableColumn fx:id="table_Native_Place" minWidth="100.0" prefWidth="150.0" text="籍贯" />
                        <TableColumn fx:id="table_Reward" minWidth="100.0" prefWidth="150.0" text="奖励" />
                        <TableColumn fx:id="table_Punishment" minWidth="100.0" prefWidth="150.0" text="处罚" />
                        <TableColumn fx:id="table_MyChange" minWidth="100.0" prefWidth="150.0" text="变动" />
                    </columns>
                  </TableView>
               </content>
            </ScrollPane>
         </center>
      </BorderPane>
   </center>
   <bottom>
      <HBox fx:id="HBox_bottom" prefHeight="25.0" prefWidth="600.0" style="-fx-background-color: #F8F8F8;" BorderPane.alignment="CENTER">
         <children>
            <ImageView fitHeight="25.0" fitWidth="25.0">
               <image>
                  <Image url="@../image/time.png" />
               </image>
            </ImageView>
            <Label fx:id="label_time" alignment="CENTER" prefHeight="25.0" prefWidth="150.0" style="-fx-border-color: #000000;" text="1970年1月1日" textAlignment="CENTER" textFill="#b209e1">
               <font>
                  <Font name="System Bold Italic" size="15.0" />
               </font>
            </Label>
            <Label disable="true" prefWidth="200.0" />
            <ImageView fitHeight="25.0" fitWidth="25.0">
               <image>
                  <Image url="@../image/IP.png" />
               </image>
            </ImageView>
            <Label fx:id="label_IP" alignment="CENTER" prefHeight="25.0" prefWidth="160.0" style="-fx-border-color: #000000;" text="192.168.0.1" textAlignment="CENTER">
               <font>
                  <Font name="System Bold Italic" size="15.0" />
               </font>
            </Label>
         </children>
      </HBox>
   </bottom>
</BorderPane>

教师界面control

package control;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.ResourceBundle;

import application.Person;
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.fxml.JavaFXBuilderFactory;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import table.MyChange;
import table.Punishment;
import table.Reward;
import table.Student;

public class TeacherControl implements Initializable {
   
	@FXML
	private ScrollPane scrollpane;
	@FXML
	private HBox HBox_bottom;
	@FXML
    private HBox HBox_application;
	
	@FXML
    private MenuBar menus;
	@FXML
    private Menu menu_edit;
    @FXML
    private Menu menu_help;

    @FXML
    private ComboBox<String> comboBox;

    @FXML
    private TextField text_select;

    @FXML
    private Label label_IP;
    @FXML
    private Label label_time;
    @FXML
    private Button btn_select;
    @FXML
    private Button btn_add;
    @FXML
    private Button btn_modify;
    @FXML
    private Button btn_delete;
    
    @FXML
    private TableView<Person> tableView;
    @FXML
    private TableColumn<Person, String> table_StudentID;
    @FXML
    private TableColumn<Person, String> table_Name;
    @FXML
    private TableColumn<Person, String> table_Sex;
    @FXML
    private TableColumn<Person, String> table_ClassName;
    @FXML
    private TableColumn<Person, String> table_Department;
    @FXML
    private TableColumn<Person, String> table_birthday;
    @FXML
    private TableColumn<Person, String> table_Native_Place;
    @FXML
    private TableColumn<Person, String> table_Reward;
    @FXML
    private TableColumn<Person, String> table_Punishment;
    @FXML
    private TableColumn<Person, String> table_MyChange;
    ObservableList<Person> data;
	//选择按钮
    final static String[] optionsName =new String[] {"请选择","学号","姓名","班级","院系"};
	@Override//初始化教师顶部和底部
	public void initialize(URL location, ResourceBundle resources) {
		
		//布局初始化
		HBox_bottom.setAlignment(Pos.CENTER);
		HBox_application.setAlignment(Pos.CENTER);
		
		text_select.setText("点击查询返回全部信息");
		
		//表格初始化
		tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);//表格自动填充
		data =FXCollections.observableArrayList();//数据
		tableView.setItems(data);//添加数据
		tableView.setStyle( "-fx-alignment: CENTER;");
		data.clear();
		data.addAll(Person.getPeopleFromSQL(Student.getStudentIDFromSQL()));
		
		//每一列初始化
		InitTableColumes();
		
		
		//标签初始化
		Date date =new Date();
    	DateFormat longFormat=DateFormat.getDateInstance(DateFormat.LONG);
    	
		InetAddress localAddress=null;
    	try {
			localAddress=InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	label_IP.setText(localAddress.getHostAddress());
    	label_IP.setTooltip(new Tooltip("本机IP"));
    	label_time.setText(longFormat.format(date));
    	label_time.setTooltip(new Tooltip("当前时间"));
    	
    	//下拉栏初始化
    	ObservableList<String> Options = 
    		    FXCollections.observableArrayList(optionsName);
    	comboBox.setItems(Options);
    	comboBox.setTooltip(new Tooltip("选择一个查询项"));
    	
    	//菜单栏初始化
    	//编辑栏
    	 MenuItem menu_add = new MenuItem("新增");
    	 menu_add.setGraphic(new ImageView(new Image("image/add.png")));
    	 menu_add.setOnAction((ActionEvent t) -> {
    		 	addStudent(t);
    	        });
    	 
    	 
    	 
    	 MenuItem menu_modify = new MenuItem("修改");
    	 menu_modify.setGraphic(new ImageView(new Image("image/modify.png")));
    	 menu_modify.setOnAction((ActionEvent t) -> {
    		 modifyStudent(t);
    	        });
    	 
    	 MenuItem menu_delete = new MenuItem("删除");
    	 menu_delete.setGraphic(new ImageView(new Image("image/delete.png")));
    	 menu_delete.setOnAction((ActionEvent t) -> {
    		 deleteStudent(t);
    	        });
    	 MenuItem menu_exit = new MenuItem("退出");
    	 menu_exit.setGraphic(new ImageView(new Image("image/exit.png")));
    	 menu_exit.setOnAction((ActionEvent t) -> {
    		 System.exit(0);
    	        });
    	 
    	 menu_edit.getItems().addAll(menu_add,menu_modify,menu_delete,menu_exit);
    	 //帮助栏 
    	 MenuItem menu_FU = new MenuItem("刘哲");
    	 MenuItem menu_MO = new MenuItem("刘懿儇");
    	 menu_help.getItems().addAll(menu_FU,menu_MO);
    	
	}
	@FXML//新增事件(新增学生)
    void addStudent(ActionEvent event) {
		Pane addStudentPane=null;
		URL location=null;
		//System.out.println("添加学生");
		
		location = getClass().getResource("/resources/fxml_AddStudent.fxml");
		
		FXMLLoader fxmlLoader = new FXMLLoader();
	    fxmlLoader.setLocation(location);
	    fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
	    try {
			 addStudentPane =fxmlLoader.load(location.openStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    AddStudentControl control=(AddStudentControl)fxmlLoader.getController();
	    		
		Scene sc =new Scene(addStudentPane);
		Stage stage=new Stage();
		stage.setScene(sc);
		stage.initOwner(btn_add.getScene().getWindow());
		stage.setTitle("添加学生");
		stage.initStyle(StageStyle.UNIFIED);
		stage.initModality(Modality.WINDOW_MODAL);
		stage.showAndWait();
		
		if(control.newPerson!=null)
		{
			data.add(control.newPerson);
		}
    }
	@FXML //查询学生
	void selectStudent(ActionEvent event)
	{
		//System.out.println("查询学生");
		if(text_select.getText()==null || text_select.getText().trim().isEmpty())
		{
			Alert Error = new Alert(Alert.AlertType.ERROR);
			Error.initStyle(StageStyle.UNIFIED);//最少平台显示
			Error.setHeaderText("查询失败");
			Error.setTitle("错误");
			Error.setContentText("请输入内容");
			Error.show();
			return ;
		}
		int index=0;
		for(int i=0;i<optionsName.length;++i)
		{
			if(optionsName[i].compareTo(comboBox.getValue().trim())==0)
			{
				index=i;
				break;
			}		
		}
		switch(index)
		{
		case 0://返回全部学生
			data.clear();
			data.addAll(Person.getPeopleFromSQL(Student.getStudentIDFromSQL()));
			break;
		case 1://学号查询
			data.clear();
			data.add(Person.getPersonFromSQL(text_select.getText().trim()));
			break;
		case 2://名称
			data.clear();
			data.addAll(Person.getPeopleFromSQLWithStudent(Student.getStudentFromSQLWithName(text_select.getText().trim())));
			break;
		case 3://班级
			data.clear();
			data.addAll(Person.getPeopleFromSQLWithStudent(Student.getStudentFromSQLWithClassName(text_select.getText().trim())));
			break;
		case 4:// 院系
			data.clear();
			data.addAll(Person.getPeopleFromSQLWithStudent(Student.getStudentFromSQLWithDepartmentName(text_select.getText().trim())));
			break;		
		}	
	}
	@FXML  //修改学生
	void modifyStudent(ActionEvent event)
	{
		//System.out.println("修改学生信息");
		Person person=tableView.getSelectionModel().getSelectedItem();
		int index=-1;
		index=tableView.getSelectionModel().getSelectedIndex();
		if(index<0)
		{
			Alert  Error= new Alert(Alert.AlertType.ERROR);
			Error.initStyle(StageStyle.UNIFIED);//最少平台显示
			Error.setHeaderText("修改失败");
			Error.setTitle("错误");
			Error.setContentText("请先选择一个行");
			Error.show();
		}
		else {
		
		Alert alert = new Alert(AlertType.CONFIRMATION);
    	alert.setTitle("确认");
    	alert.setHeaderText("确定要修改学号为\""+person.student.StudentID+"\"的信息?");
    	Optional<ButtonType> result = alert.showAndWait();
    	if (result.get() == ButtonType.OK){
    		
		//面板出现
		Pane modifyStudentPane=null;
		URL location=null;
		//System.out.println("添加学生");
		
		location = getClass().getResource("/resources/fxml_ModifyStudent.fxml");
		
		FXMLLoader fxmlLoader = new FXMLLoader();
	    fxmlLoader.setLocation(location);
	    fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
	    try {
	    	modifyStudentPane =fxmlLoader.load(location.openStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    ModifyStudentControl control=(ModifyStudentControl)fxmlLoader.getController();
	    control.person=person;
	    control.ChangePaneWithPerson();		
		Scene sc =new Scene(modifyStudentPane);
		Stage stage=new Stage();
		stage.setScene(sc);
		stage.initOwner(btn_modify.getScene().getWindow());
		stage.setTitle("修改学生信息");
		stage.initStyle(StageStyle.UNIFIED);
		stage.initModality(Modality.WINDOW_MODAL);
		stage.showAndWait();
		
		//信息更新
		data.clear();
		data.addAll(Person.getPeopleFromSQL(Student.getStudentIDFromSQL()));
    	}
    	}
	}
	@FXML   //删除学生
	void deleteStudent(ActionEvent event)
	{
		//System.out.println("删除学生");
		Person delPerson=tableView.getSelectionModel().getSelectedItem();
		int index=-1;
		index=tableView.getSelectionModel().getSelectedIndex();
		
		if(index<0)
		{
			Alert  Error= new Alert(Alert.AlertType.ERROR);
			Error.initStyle(StageStyle.UNIFIED);//最少平台显示
			Error.setHeaderText("删除失败");
			Error.setTitle("错误");
			Error.setContentText("请先选择一个行");
			Error.show();
		}
		else 
		{
			Alert alert = new Alert(AlertType.CONFIRMATION);
	    	alert.setTitle("确认");
	    	alert.setHeaderText("确定要删除学号为\""+delPerson.student.StudentID+"\"的信息?");
	    	Optional<ButtonType> result = alert.showAndWait();
	    	if (result.get() == ButtonType.OK)
	    	{
	    		data.remove(index);
	    		Person.deletePersonToSQL(delPerson);
			}
		}
	}
	@FXML   //检索框
	void comboBoxSelectOption(ActionEvent event)
	{
		System.out.println("更改了一个选项");
		text_select.setText(null);
		if(comboBox.getValue().length()<=2)
		{
			text_select.setPromptText("请输入一个"+comboBox.getValue());
		}
		else 
		{
			text_select.setText("点击查询返回全部信息");
		}
		
	}
	//初始换中间学生表格信息
	private void InitTableColumes()
	{
		table_StudentID.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
				{
					@Override
					public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
						// TODO Auto-generated method stub
						SimpleStringProperty StudentID=new SimpleStringProperty(param.getValue().student.StudentID);
						return StudentID;
					}
				});
		table_StudentID.setStyle( "-fx-alignment: CENTER;");
		//table_StudentID.setEditable(true);
		//table_StudentID.setCellFactory(TextFieldTableCell.forTableColumn());
		
		table_Name.setStyle( "-fx-alignment: CENTER;");
		table_Name.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty Name=new SimpleStringProperty(param.getValue().student.Name);
				return Name;
			}
		});
		
		table_Sex.setStyle( "-fx-alignment: CENTER;");
		table_Sex.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty Sex=new SimpleStringProperty(param.getValue().student.Sex);
				return Sex;
			}
		});
		
		table_ClassName.setStyle( "-fx-alignment: CENTER;");
		table_ClassName.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty ClassName=new SimpleStringProperty(param.getValue().student.myclass.Name);
				return ClassName;
			}
		});
		
		table_Department.setStyle( "-fx-alignment: CENTER;");
		table_Department.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty DepartmentName=new SimpleStringProperty(param.getValue().student.department.Name);
				return DepartmentName;
			}
		});
		
		table_birthday.setStyle( "-fx-alignment: CENTER;");
		table_birthday.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty Birthday=new SimpleStringProperty(param.getValue().student.Birthday);
				return Birthday;
			}
		});
		
		table_Native_Place.setStyle("-fx-alignment: CENTER;");
		table_Native_Place.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty Native_Place=new SimpleStringProperty(param.getValue().student.Native_Place);
				return Native_Place;
			}
		});
		
		table_Reward.setStyle("-fx-alignment: CENTER;");
		table_Reward.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty reward=new SimpleStringProperty(Reward.REWARD_LEVELS[param.getValue().reward.Levels]);
				return reward;
			}
		});
		
		table_Punishment.setStyle("-fx-alignment: CENTER;");
		table_Punishment.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty punishment=new SimpleStringProperty(Punishment.PUNISH_LEVELS[param.getValue().punishment.Levels]);
				return punishment;
			}
		});
		
		
		table_MyChange.setStyle("-fx-alignment: CENTER;");
		table_MyChange.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Person,String>,ObservableValue<String>>()
		{
			@Override
			public ObservableValue<String> call(CellDataFeatures<Person, String> param) {
				// TODO Auto-generated method stub
				SimpleStringProperty mychange=new SimpleStringProperty(MyChange.CHANGE_LEVELS[param.getValue().mychange.Code]);
				return mychange;
			}
		});
		
		
	}
}

学生界面

 学生界面FX

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.paint.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.image.*?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.HBox?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="410.0" prefWidth="500.0" style="-fx-background-color: #FFF8DC;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="control.StudentControl">
   <children>
      <Label layoutX="52.0" layoutY="18.0" text="学号" textAlignment="CENTER" textOverrun="CENTER_ELLIPSIS" wrapText="true">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <TextField fx:id="text_StudentID" layoutX="108.0" layoutY="15.0" promptText="请输入学号查询自己的信息" />
      <Button fx:id="btn_Select" layoutX="380.0" layoutY="26.0" mnemonicParsing="false" onAction="#selcetData" text="查询">
         <font>
            <Font size="19.0" />
         </font></Button>
      <Label layoutX="52.0" layoutY="72.0" text="姓名">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <TextField fx:id="text_Name" layoutX="110.0" layoutY="69.0" prefHeight="30.0" prefWidth="100.0" />
      <Label layoutX="300.0" layoutY="109.0" text="性别">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <ComboBox fx:id="comboBox_Sex" layoutX="372.0" layoutY="106.0" prefHeight="30.0" prefWidth="80.0" />
      <Label layoutX="52.0" layoutY="124.0" text="生日">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <Label layoutX="52.0" layoutY="176.0" text="籍贯">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <TextField fx:id="text_Birthday" layoutX="110.0" layoutY="121.0" prefHeight="30.0" prefWidth="120.0" />
      <TextField fx:id="text_NativePlace" layoutX="110.0" layoutY="173.0" prefHeight="30.0" prefWidth="175.0" />
      <Label layoutX="52.0" layoutY="235.0" text="班级">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <Button fx:id="btn_updata" layoutX="209.0" layoutY="366.0" mnemonicParsing="false" onAction="#upData" text="更新" textFill="RED" visible="false">
         <font>
            <Font size="18.0" />
         </font>
      </Button>
      <ComboBox fx:id="comboBox_Class" layoutX="110.0" layoutY="235.0" prefWidth="150.0" />
      <Label layoutX="277.0" layoutY="235.0" text="学籍">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <TextField fx:id="text_Change" disable="true" editable="false" layoutX="318.0" layoutY="235.0" prefHeight="30.0" prefWidth="65.0" />
      <Label layoutX="52.0" layoutY="288.0" text="院系">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <ComboBox fx:id="comboBox_Department" layoutX="110.0" layoutY="285.0" prefHeight="30.0" prefWidth="330.0" />
      <Label layoutX="46.0" layoutY="335.0" text="奖励">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <TextField fx:id="text_Reward" editable="false" layoutX="110.0" layoutY="330.0" prefHeight="30.0" prefWidth="150.0" />
      <Label layoutX="277.0" layoutY="335.0" text="处分">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <TextField fx:id="text_Punishment" editable="false" layoutX="318.0" layoutY="330.0" prefHeight="30.0" prefWidth="120.0" />
      <Button fx:id="btn_more" layoutX="350.0" layoutY="150.0" mnemonicParsing="false" onAction="#moreInfo" text="更多信息" textFill="#001eff" visible="false" />
   </children>
</AnchorPane>

学生界面control

package control;

import table.Class;
import table.Department;
import table.MyChange;
import table.Punishment;
import table.Reward;
import table.Student;

import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;

import application.Person;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;

public class StudentControl implements Initializable {

    @FXML
    private TextField text_Change;

    @FXML
    private ComboBox<String> comboBox_Department;

    @FXML
    private TextField text_Birthday;

    @FXML
    private TextField text_NativePlace;

    @FXML
    private TextField text_StudentID;

    @FXML
    private ComboBox<String> comboBox_Class;
    
    @FXML
    private ComboBox<String> comboBox_Sex;

    @FXML
    private Button btn_updata;

    @FXML
    private Button btn_Select;
    
    @FXML
    private Button btn_more;

    @FXML
    private TextField text_Reward;

    @FXML
    private TextField text_Name;

    @FXML
    private TextField text_Punishment;
    
    Person person;

    @Override   //初始化学生信息表
	public void initialize(URL location, ResourceBundle resources) {
    	
    	ObservableList<String> OptionsSex = 
    		    FXCollections.observableArrayList("男","女");
    	
    	comboBox_Sex.setItems(OptionsSex);
    	ArrayList<String> listClass=Class.getClassNameFromSQL();
    	ObservableList<String> OptionsClass = 
    		    FXCollections.observableArrayList(listClass);
    	comboBox_Class.setItems(OptionsClass);
    	ArrayList<String> listDepartment=Department.getDepartmentNameFromSQL();
    	ObservableList<String> OptionsDepartment = 
    		    FXCollections.observableArrayList(listDepartment);
    	comboBox_Department.setItems(OptionsDepartment);

	}
    @FXML  //查询学生正确就显示,粗了就报错
    void selcetData(ActionEvent event) {
    	//System.out.println("查询了"+text_StudentID.getText());
    	
    	btn_more.setVisible(true);
    	btn_updata.setVisible(true);
    	person=new Person();
    	
    	if(Student.isStudentFromSQL(text_StudentID.getText().trim()))
    	{
    		//从数据库中用ID获得person类
    		person=Person.getPersonFromSQL(text_StudentID.getText().trim());
    		
    		text_Name.setText(person.student.Name);
    		text_Birthday.setText(person.student.Birthday);
    		text_NativePlace.setText(person.student.Native_Place);
    		text_Change.setText(MyChange.CHANGE_LEVELS[person.mychange.Code]);
    		text_Reward.setText(Reward.REWARD_LEVELS[person.reward.Levels]);
    		text_Punishment.setText(Punishment.PUNISH_LEVELS[person.punishment.Levels]);
    		
    		comboBox_Sex.setValue(person.student.Sex);
    		comboBox_Class.setValue(person.student.myclass.Name);
        	comboBox_Department.setValue(person.student.department.Name);
    	}
    	else 
    	{
    		Alert alert_Not = new Alert(AlertType.ERROR);
    		alert_Not.setTitle("错误");
    		alert_Not.setHeaderText("查无此人");
    		alert_Not.setContentText("请检查学号输入是否正确或者通知管理员添加信息");
    		alert_Not.showAndWait();
    	}
    }
    
    @FXML  //显示更多信息
    void moreInfo(ActionEvent event) {
    
    	Alert alert = new Alert(AlertType.INFORMATION);
    	alert.setTitle("更多信息");
    	String Text="奖励情况\n"+person.reward.Description+"\n\n处罚情况\n"+person.punishment.Description+"\n\n学籍变更情况\n"+person.mychange.Description;
    	alert.setContentText(Text); 
    	alert.setHeaderText("更多信息");
    	alert.showAndWait();  	
    }

    @FXML  //更新学生信息
    void upData(ActionEvent event) {
    	System.out.println("更新了"+text_StudentID.getText());

    	Alert alert = new Alert(AlertType.CONFIRMATION);
    	alert.setTitle("确认");
    	alert.setHeaderText("确定要修改学号为\""+person.student.StudentID+"\"的信息?");
    	Optional<ButtonType> result = alert.showAndWait();
    	if (result.get() == ButtonType.OK){
    		
    		String sName=text_Name.getText().trim();
    		String sSex=comboBox_Sex.getValue().trim();
    		String sBirthday=text_Birthday.getText().trim();
    		String sPlace=text_NativePlace.getText().trim();
    		String sClass=comboBox_Class.getValue().trim();
    		String sDepartment=comboBox_Department.getValue().trim();
    		
    		boolean bName=text_Name.getText().isEmpty();
    		boolean bSex=comboBox_Sex.getValue().isEmpty();
    		boolean bBirthday=text_Birthday.getText().isEmpty();
    		boolean bPlace=text_NativePlace.getText().isEmpty();
    		boolean bClass=comboBox_Class.getValue().isEmpty();
    		boolean bDepartment=comboBox_Department.getValue().isEmpty();
    		if(bName || bSex || bBirthday || bClass || bPlace || bDepartment)
    		{
    			Alert alert_Null = new Alert(AlertType.WARNING);
    			alert_Null.setTitle("警告");
    			alert_Null.setHeaderText("请将信息填写完整");
    			alert_Null.showAndWait();		
    		}
    		else 
    		{
    			Student newStudent=new Student();
    			newStudent.Birthday=sBirthday;;
    			newStudent.department=Department.getDepartmentFromSQLWithName(sDepartment);
    			newStudent.myclass=Class.getClassFromSQLWithName(sClass);
    			newStudent.Name=sName;
    			newStudent.Native_Place=sPlace;
    			newStudent.Sex=sSex;
    			newStudent.StudentID=person.student.StudentID;
    			Student.updateInfoToSQL(newStudent);
        		selcetData(event);
    		}
    	}
    }

}

如果有需要私信我,无偿给你发代码。

  • 9
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值