"Java"-Small project-Small student management system __java

Source: Internet
Author: User
Tags gettext stub

This project is based on the "Hanshunping-step-by-Step Java" instructional video completed, the project's interface as shown in the following diagram, the micro-student management system through the operation of the database, with basic additions and deletions to check the function. The knowledge points involved mainly include the layout of the interface, connect the database, and operate the database with SQL statements. Very suitable for getting started learning.


Before doing the project, we need to build a table in the database, including "school number, name, sex, age, place of origin, department", set the school number as the primary key, the code is as follows:

--Create TABLE

stu
(stuid varchar () primary key, Stuname nvarchar () not
null, Stusex nchar
(1) Check (stusex in (' Male ', ' female ')) Default ' man ',
stuage int Check (stuage>1),
stujg nvarchar
nvarchar ()
)


Next we create a new Java file--stumanager.java, it is responsible for building the interface, including a number of buttons and text boxes, but also to press the events of the various buttons to monitor the whole project is the central headquarters, the code is as follows:

* * Complete a mini version of the Student Management system MODEL2 * 1. Query task * 2. Add a student * * */package com.test2;

Import javax.swing.*;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.util.*;
Import java.awt.*;

Import java.awt.event.*;
	public class Stumanager extends JFrame implements actionlistener{//define some controls JPanel jp1,jp2;
	JLabel jl1;
	JButton jb1,jb2,jb3,jb4;
	JTable JT;
	JScrollPane JSP;
	JTextField JTF;
	
	Stumodel SM;
	
			
	
	
	The rowdata is used to hold the row data//columnnames for storing the column name Vector rowdata,columnnames;
	public static void Main (string[] args) {//TODO auto-generated method stub Stumanager test3=new Stumanager ();
		}//Constructor public Stumanager () {jp1=new JPanel ();
		Jtf=new JTextField (10);
		Jb1=new JButton ("query");
		Jb1.addactionlistener (this);
		
		Jl1=new JLabel ("Please enter first name");
		Add each control to the JP1 Jp1.add (JL1);
		Jp1.add (JTF);
		
		Jp1.add (JB1);
		Jp2=new JPanel ();
		Jb2=new JButton ("add");
		Jb2.addactionlistener (this); Jb3=new JBUTton ("modification");
		Jb3.addactionlistener (this);
		Jb4=new JButton ("delete");
		
		Jb4.addactionlistener (this);
		Add each button to the JP2 jp2.add (JB2);
		Jp2.add (JB3);
		
		Jp2.add (JB4);
		Create a data Model object Sm=new Stumodel ();
		String []paras={"1"};
		
		Sm.querystu ("select * from Stu where 1=?", paras);
		
		Initialization of JTable jt=new JTable (SM);
		
		Initialize JSP JScrollPane jsp=new JScrollPane (JT);
		Put the JSP into the JFrame This.add (JSP);
		This.add (JP1, "North");
		
		This.add (JP2, "South");
		
		This.setsize (400, 300);
		This.setdefaultcloseoperation (Jframe.exit_on_close);
		
		
	This.setvisible (TRUE); @Override public void actionperformed (ActionEvent e) {//TODO auto-generated stub//Determine which button is clicked if (e.gets
			Ource () ==jb1) {System.out.println ("User wants query");
			Because the data on the table is encapsulated into the stumodel, we can simply complete the query String name=this.jtf.gettext (). Trim ();
			Write an SQL statement String sql= "select * from Stu where stuname=?";
			String Paras[]={name};
			
			Build new data Model class and update sm=new Stumodel ();
Sm.querystu (SQL, paras);			Update jtable Jt.setmodel (SM);
			
			//When the user clicks = Adds else if (E.getsource () ==jb2) {Stuadddialog sa=new Stuadddialog (this, add student, true);
			Re-acquire new data model//build new Data Model class and update sm=new Stumodel ();
			String []paras2={"1"};
			Sm.querystu ("select * from Stu where 1=?", PARAS2);
		Update jtable Jt.setmodel (SM);
			else if (E.getsource () ==jb3) {//the user wishes to modify the student information int rownum=this.jt.getselectedrow ();
				if (rownum==-1) {//Prompt Joptionpane.showmessagedialog (this, "Please select one row");
			Return
			//Show Modify dialog box new Stuupddialog (This, "Modify student Information", true,sm,rownum);
			Build new data Model class and update sm=new Stumodel ();
			String []paras2={"1"};
			Sm.querystu ("select * from Stu where 1=?", PARAS2);
			
		Update jtable Jt.setmodel (SM); else if (E.getsource () ==jb4) {//Description the user wants to delete the record//1. Get the ID of the student//getselectedrow will return the line in the user's point if the user does not have a row, return a
			-1 int Rownum=this.jt.getselectedrow ();
				if (rownum==-1) {//Prompt Joptionpane.showmessagedialog (this, "Please select one row");
	Return		//Get Student number string stuid= (String) sm.getvalueat (rownum, 0);
			Create a SQL String sql= "Delete from Stu where stuid=?";
			String []paras={stuid};
			Stumodel temp=new Stumodel ();
			
			Temp.updstu (SQL, paras);
			Update Data Model Sm=new Stumodel ();
			String []paras2={"1"};
			Sm.querystu ("select * from Stu where 1=?", PARAS2);
		Update jtable Jt.setmodel (SM);
 }
		
	}

}

Then, we create a new Stuadddialog,java file, which is the function of when we click on a "Add" button, pop-up a dialog box, as shown in the picture:


The code is as follows:

Package com.test2;
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
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 Stuadddialog extends JDialog implements actionlistener{//define the Swing components I need JLabel jl1,jl2,jl3,jl4,jl5,jl6;
	JButton jb1,jb2;
	JTextField Jtf1,jtf2,jtf3,jtf4,jtf5,jtf6;
	
	JPanel jp1,jp2,jp3; Owner its parent window//title window name//modal specifies modal window or modeless window public stuadddialog (Frame owner,string title, Boolean modal) {Supe
		R (owner,title,modal);//Call the parent class construct method to achieve the modal dialog box effect jp1=new JPanel ();
		Jp2=new JPanel ();
		
		Jp3=new JPanel ();
		Jl1=new JLabel ("School Number");
		Jl2=new JLabel ("name");
		Jl3=new JLabel ("gender");
		Jl4=new JLabel ("Age");
		Jl5=new JLabel ("Native Place");
		
		Jl6=new JLabel ("fasten");
		Jtf1=new JTextField ();
		Jtf2=new JTextField ();
		Jtf3=new JTextField ();
		Jtf4=new JTextField (); Jtf5=new JTextField ();
		
		Jtf6=new JTextField ();
		Jb1=new JButton ("add");
		Register to monitor Jb1.addactionlistener (this);
		
		Jb2=new JButton ("cancellation");
		Set Layout jp1.setlayout (new GridLayout (6,1));
		
		Jp2.setlayout (New GridLayout (6,1));
		Add Component Jp1.add (JL1);
		Jp1.add (JL2);
		Jp1.add (JL3);
		Jp1.add (JL4);
		Jp1.add (JL5);
		
		Jp1.add (JL6);
		Jp2.add (JTF1);
		Jp2.add (JTF2);
		Jp2.add (JTF3);
		Jp2.add (JTF4);
		Jp2.add (JTF5);
		
		Jp2.add (JTF6);
		Jp3.add (JB1);
		
		Jp3.add (JB2);
		This.add (jp1,borderlayout.west);
		This.add (Jp2,borderlayout.center);
		
		
		This.add (Jp3,borderlayout.south);
		Show This.setsize (300,250);
	This.setvisible (TRUE);
		@Override public void actionperformed (ActionEvent e) {//TODO auto-generated Method stub if (E.getsource () ==jb1)
			{//wish to add Stumodel temp=new Stumodel ();
			String sql= "INSERT into Stu values (?,?,?,?,?,?)";
			String []paras={jtf1.gettext (), Jtf2.gettext (), Jtf3.gettext (), Jtf4.gettext (), Jtf5.gettext (), Jtf6.gettext ()}; if (!temp.updstu(SQL, paras))
				
			{//Prompt Joptionpane.showmessagedialog (this, "Add failed");
		//Close dialog box This.dispose ();
 }
		
		
	}
	
	
}

Next, we create a new Stuupddialog.java, which is responsible for updating the student's information, the code is as follows:

* * Revise Student information * * * * * * Package com.test2;
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
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 Stuupddialog extends JDialog implements actionlistener{//define the Swing components I need JLabel jl1,jl2,jl3,jl4,jl5,jl6;
	JButton jb1,jb2;
	JTextField Jtf1,jtf2,jtf3,jtf4,jtf5,jtf6;
	
	JPanel jp1,jp2,jp3; Owner its parent window//title window name//modal specifies modal window or modeless window public stuupddialog (Frame owner,string title, Boolean Modal,stumodel s
		M,int rownums) {super (Owner,title,modal);//Call the parent class construct method to achieve the modal dialog box effect jp1=new JPanel ();
		Jp2=new JPanel ();
		
		Jp3=new JPanel ();
		Jl1=new JLabel ("School Number");
		Jl2=new JLabel ("name");
		Jl3=new JLabel ("gender");
		Jl4=new JLabel ("Age");
		Jl5=new JLabel ("Native Place");
		
		Jl6=new JLabel ("fasten");
		Jtf1=new JTextField (); Initializes the data Jtf1.settext ((String) Sm.getValueAt (rownums, 0));
		Let JTF1 not modify jtf1.seteditable (false);
		Jtf2=new JTextField ();
		Jtf2.settext ((String) sm.getvalueat (rownums, 1));
		Jtf3=new JTextField ();
		Jtf3.settext ((String) sm.getvalueat (Rownums, 2));
		Jtf4=new JTextField ();
		Jtf4.settext ((String) sm.getvalueat (Rownums, 3). ToString ());
		Jtf5=new JTextField ();
		Jtf5.settext ((String) sm.getvalueat (Rownums, 4));
		Jtf6=new JTextField ();
		
		Jtf6.settext ((String) sm.getvalueat (Rownums, 5));
		Jb1=new JButton ("modification");
		Register to monitor Jb1.addactionlistener (this);
		
		Jb2=new JButton ("cancellation");
		Set Layout jp1.setlayout (new GridLayout (6,1));
		
		Jp2.setlayout (New GridLayout (6,1));
		Add Component Jp1.add (JL1);
		Jp1.add (JL2);
		Jp1.add (JL3);
		Jp1.add (JL4);
		Jp1.add (JL5);
		
		Jp1.add (JL6);
		Jp2.add (JTF1);
		Jp2.add (JTF2);
		Jp2.add (JTF3);
		Jp2.add (JTF4);
		Jp2.add (JTF5);
		
		Jp2.add (JTF6);
		Jp3.add (JB1);
		
		Jp3.add (JB2);
		This.add (jp1,borderlayout.west);
		This.add (Jp2,borderlayout.center);
		
This.add (Jp3,borderlayout.south);		
		Show This.setsize (300,250);
	This.setvisible (TRUE);
		@Override public void actionperformed (ActionEvent e) {//TODO auto-generated Method stub if (E.getsource () ==jb1) {//Response action after user clicks Add button//Make a SQL//Precompiled Statement Object String str= "Update stu set stuname=?,stusex=?," + "Stuage=?,stuj G=?,studept=?
			where stuid=? ";
			String []paras={jtf2.gettext (), Jtf3.gettext (), Jtf4.gettext (), Jtf5.gettext (), Jtf6.gettext (), Jtf1.gettext ()};
			Stumodel temp=new Stumodel ();
			Temp.updstu (STR, paras);
		This.dispose ();
 }
		
		
	}
	
	
}

We'll create a new Stumodel.java, which encapsulates the various operations on the student table into a model with the following code:

* * This is my one Stu table model * can encapsulate various operations of the student table into the model */package com.test2;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import Java.util.Vector;

Import javax.swing.table.*;
		
				
		The public class Stumodel extends abstracttablemodel{//rowdata is used to hold the row data//columnnames used to store the column name Vector rowdata,columnnames;
		Define what you need to manipulate the database PreparedStatement ps=null;
		Connection Ct=null;
		ResultSet Rs=null;
		String url= "JDBC:MICROSOFT:SQLSERVER://127.0.0.1:1433;DATABASENAME=ACM";
		String user= "SA";
		String passwd= "SA";
		
		String driver= "Com.microsoft.jdbc.sqlserver.SQLServerDriver";
			Add students (increase, delete, change) public boolean updstu (String sql,string []paras) {//Create SqlHelper (if program concurrency is not considered, you can make SqlHelper static)
			SqlHelper SqlHelper = new SqlHelper ();
		return Sqlhelper.updexecute (SQL, paras);
			
			}//The nature of the query is to initialize the public void Querystu (String sql,string []paras) {SqlHelper SqlHelper =null; Middle Columnnames=new VecTor ();
			Set column name Columnnames.add ("School Number");
			Columnnames.add ("name");
			Columnnames.add ("gender");
			Columnnames.add ("Age");
			Columnnames.add ("Native Place");
			
			Columnnames.add ("fasten");
			
			Rowdata=new Vector ();
				try{sqlHelper = new SqlHelper ();
				
				ResultSet rs=sqlhelper.queryexecute (SQL, paras);
					while (Rs.next ()) {vector hang=new vector ();
					Hang.add (rs.getstring (1));
					Hang.add (rs.getstring (2));
					Hang.add (Rs.getstring (3));
					Hang.add (Rs.getint (4));
					Hang.add (Rs.getstring (5));
					
					Hang.add (rs.getstring (6));
				Add to RowData rowdata.add (hang);
			}}catch (Exception e) {e.printstacktrace ();
			}finally{Sqlhelper.close ();
	The total number of rows public int GetRowCount () {//TODO auto-generated a stub return this.rowData.size ();
	The total number of columns public int getcolumncount () {return this.columnNames.size () is obtained; //Get a column of a row of data public Object getvalueat (int row, int column) {//TODO auto-generated MethoD Stub return ((Vector) this.rowData.get (Row)). get (column); @Override public String getcolumnname (int column) {//TODO auto-generated a stub return (String) This.colu
	Mnnames.get (column);
 }

}

Finally, we'll create a new file Sqlhelper.java, a class specifically designed to manipulate the database

* * This is a database operation of the Class (SqlHelper) * */package com.test2;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;

Import Java.sql.ResultSet;
	public class SqlHelper {//define what is required to manipulate the database PreparedStatement ps=null;
	Connection Ct=null;
	ResultSet Rs=null;
	String url= "JDBC:MICROSOFT:SQLSERVER://127.0.0.1:1433;DATABASENAME=ACM";
	String user= "SA";
	String passwd= "SA";
	
	String driver= "Com.microsoft.jdbc.sqlserver.SQLServerDriver";
			Closes the database resource public void Close () {//closes try{if (rs!=null) rs.close ();
			if (ps!=null) ps.close ();
			
			
		if (ct!=null) ct.close ();
		}catch (Exception e) {e.printstacktrace ();
			}//Write a method that does not need to be injected public ResultSet queryexcecute (String sql) {try{//1. Load drive Class.forName (driver);
			2. Get Connected Ct=drivermanager.getconnection (URL,USER,PASSWD);
			
			
			3. Create PS ps=ct.preparestatement (SQL);
		
	Rs=ps.executequery ();
	}catch (Exception e) {e.printstacktrace (); }finally{//Close resource} return RS }//Query database Operations public ResultSet Queryexecute (String sql,string []paras) {try{//1. Load Drive Class.forName (driver
				);
				2. Get Connected Ct=drivermanager.getconnection (URL,USER,PASSWD);
				3. Create PS ps=ct.preparestatement (SQL); to PS.
				Assignment for (int i=0;i<paras.length;i++) {ps.setstring (i+1, paras[i]);
			
		} rs=ps.executequery ();
		}catch (Exception e) {e.printstacktrace ();
	}finally{//Close Resource} return RS;
		
		///change the additions and deletions together public boolean updexecute (String sql,string []paras) {Boolean b=true;
			try{//1. Loading drive Class.forName (driver);
			2. Get Connected Ct=drivermanager.getconnection (URL,USER,PASSWD);
			3. Create PS ps=ct.preparestatement (SQL); to PS.
			Assignment for (int i=0;i<paras.length;i++) {ps.setstring (i+1, paras[i]);
			//4. Execute operation if (Ps.executeupdate ()!=1) {b=false;
			}}catch (Exception e) {b=false;
		E.printstacktrace ();
		}finally{This.close ();
	return b;
 }
	}

This project uses the MV design mode, that is, V (view) view and M (model) background to separate, the program frame diagram is as follows:






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.