catalog
Tip: this semester, Java class is going to do a project of employee management system. When we first heard about this topic, we just finished some process oriented content, and had little understanding of graphical programming. Later, we learned about various swing controls, layout use, database operation and events in various self-study. It's a good work for beginners.
Environment: NetBeans 11.2, Mysql 8.0.17
1. Function introduction and display (multi figure warning)
Function introduction of the system:
1. Data management: modify and add information (salary can only be modified by administrator)
2. Information display: display the public information of all users.
3. Employee management: add and delete users.
4: Exit the system: exit the program normally.
Login interface:
The difference of the main interface is that only administrators can manage employees
Main interface (administrator)
Main interface (ordinary user)
Information modification
Password change
Information display
Employee management
2. Code design
1 database
My database is Mysql 8.0.17
JDBC driver type 4: native protocol driver (local protocol driver), which provides corresponding driver jar package when using different databases
Its specific driving process:
Application → JDBC Driver → Database Engine → Database
When using the driver jar package, notice that for mysql version 8.0 and above, the jar package and connection statement used are different.
mysql 8.0 and above mysql-connector-java-8.0.16.jar
mysql 8.0 and below mysql-connector-java-5.1.39-bin.jar
mysql database structure
Database connection class
package human.resoruce.dbconnection; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.swing.JOptionPane; //Database connection public class DbConnect { static final String DB_URL = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC"; static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; // Mysql version lower than 8.0 // static final String DB_URL = "jdbc:mysql://localhost:3306/mydb"; // static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String user = "root"; //Modify the password according to the local mysql account static final String password = "root"; public Connection conn = null; public PreparedStatement pst = null; public DbConnect(String sql) { try { //Register JDBC Driver Class.forName(JDBC_DRIVER); //Open link conn = DriverManager.getConnection(DB_URL,user,password); pst = conn.prepareStatement(sql); } catch(SQLException e){ JOptionPane.showMessageDialog(null, "Connection is not Opened ! " + e.getMessage()); } catch (ClassNotFoundException ex) { JOptionPane.showMessageDialog(null, "Class not found ! " + ex.getMessage()); } } public void close() { try { this.conn.close(); this.pst.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String[] args) { } }
2 login interface and verification
The login interface uses non graphical programming, which involves adding background pictures. After consulting the data, JLayerdPane is used to control the priority relationship between the levels. The layer containing background pictures is set at the bottom, and other controls are added to the corresponding panel and then added to the bottom. It should be noted that the password box uses passwordtext, and you can use new string when getting it( passwordText.getPassword ())
The following code ensures that the window is centered
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((dim.width - this.getWidth()) / 2, (dim.height - this.getHeight()) / 2);
This line of code indicates that the program will be closed when the upper right corner fork is clicked
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
The main reason why the window size can't be changed is that when the window size is adjusted manually, the size and relative position of other controls have not changed, so the immutable size is simply set.
this.setResizable(false);
Login interface full code
package human.resource.login; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; //Login Frame public class Login extends JFrame { private JLayeredPane pane=new JLayeredPane();//Bottom level panel private JPanel backPanel=new JPanel();//Background picture private JPanel headPanel=new JPanel();//title private JPanel panel1 =new JPanel();//accounts private JPanel panel2 =new JPanel();//password private JPanel panel3 =new JPanel();//Button private JLabel back;//Background picture private JLabel headLight=new JLabel("Human Resource Management");//title private JLabel userLabel =new JLabel("username:"); private JLabel passwordLabel = new JLabel("password:"); private JTextField userText = new JTextField(); private JPasswordField passwordText = new JPasswordField(); private JButton but1 = new JButton("Login"); ImageIcon image; @SuppressWarnings("unchecked") public Login() { image=new ImageIcon(getClass().getResource("/Photos/1.jpg")); headLight.setOpaque(false); userLabel.setOpaque(false); userText.setOpaque(false); passwordLabel.setOpaque(false); passwordText.setOpaque(false); backPanel.setOpaque(false); headPanel.setOpaque(false); panel1.setOpaque(false); panel2.setOpaque(false); panel3.setOpaque(false); //background photo back=new JLabel(image); backPanel.setBounds(0, 0, image.getIconWidth(), image.getIconHeight()); backPanel = (JPanel)this.getContentPane(); backPanel.add(back); //title headLight.setFont(new Font("Blackbody",Font.BOLD,35)); headPanel.setLayout(new GridLayout(1,1)); headPanel.setBounds(10,40,500,200); headPanel.add(headLight); //user userLabel.setFont(new Font("Blackbody",Font.BOLD,40)); userText.setFont(new Font("Blackbody",Font.BOLD,40)); panel1.setLayout(new GridLayout(2,1)); panel1.setBounds(130, 240, 220, 70); panel1.add(userLabel); panel1.add(userText); //password passwordLabel.setFont(new Font("Blackbody",Font.BOLD,40)); passwordText.setFont(new java.awt.Font("Yu Gothic Medium", 0, 30)); panel2.setLayout(new GridLayout(2,1)); panel2.setBounds(130, 330, 220, 70); panel2.add(passwordLabel); panel2.add(passwordText); //buttion but1.setSize(300,60); but1.setFont(new Font("Blackbody",Font.BOLD,20)); panel3.setLayout(new GridLayout(1,2)); panel3.setBounds(50, 500, 400, 50); panel3.add(but1); pane.add(backPanel,JLayeredPane.DEFAULT_LAYER); pane.add(headPanel, JLayeredPane.MODAL_LAYER); pane.add(panel1,JLayeredPane.MODAL_LAYER); pane.add(panel2,JLayeredPane.POPUP_LAYER); pane.add(panel3,JLayeredPane.DRAG_LAYER); //Login event but1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new Userverify(userText.getText(),new String(passwordText.getPassword())); userText.setText(""); passwordText.setText(""); } }); this.setSize(image.getIconWidth(),image.getIconHeight()); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((dim.width - this.getWidth()) / 2, (dim.height - this.getHeight()) / 2); this.setTitle("Human Resource Management"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); this.setLayeredPane(pane); this.setResizable(false); this.setVisible(true); } public static void main(String[] args) {Login login = new Login();} }
Login authentication
Idea: transfer the input account password from the login interface, compare it with the account password extracted from the database, call the main interface according to the authority and transfer the authority data. The account password error will pop up.
//acount verify public class Userverify { String sql = null; DbConnect db = null; ResultSet ret = null; public Userverify(String user,String pass) { //select spicific accout sql = "select username,password,authority from person where username="+'"'+user+'"'; db = new DbConnect(sql); try { //ret will recieve query answers ret = db.pst.executeQuery(); while (ret.next()) { String u = ret.getString(1); //username in db String p = ret.getString(2); //password in db int authority=ret.getInt(3); if(u.equals(user)&&p.equals(pass)&&authority==2) { MainFrame mainFrame = new MainFrame(u,1); //administration } else if(u.equals(user)&&p.equals(pass)&&authority==1){ MainFrame mainFrame = new MainFrame(u,0); //normal user } else { JOptionPane.showMessageDialog(null,"Account or password is wrong !!!","error",JOptionPane.ERROR_MESSAGE); } } ret.close(); db.close(); } catch (SQLException e) { e.printStackTrace(); } catch(Exception e1){ e1.printStackTrace(); } } public static void main(String[] args) {} }
3 main interface
Here is the main interface programming with the graphical interface of netbeans, a menu bar, several options. After opening the interface, use the account name to query the database and display the current account information.
Because User Manage is a menu rather than a button, the ButtonMouseClicked event is set. When the mouse is clicked, a new window will be opened. If it is an ordinary user, it will be initialized to setEnabled(false), but the new window can still be opened by clicking, so the permission needs to be judged again in the event.
Use this representation here to automatically hide and release the form. However, if you continue to run the application, you can log in again from the login interface. Similarly, other secondary interfaces should be set in this way
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
public class MainFrame extends javax.swing.JFrame { String user; int right; //right=1 admin right =0 normal public MainFrame(String user,int right) { this.user=user; this.right=right; initComponents(); showInfo(user); //normal users could only check and change their own info if(right==0){ userManageButton.setEnabled(false); } Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((dim.width - this.getWidth()) / 2, (dim.height - this.getHeight()) / 2); this.setTitle("HRM"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); this.setResizable(false); this.setVisible(true); } @SuppressWarnings("unchecked") private void initComponents(){}//Slightly auto generated private void passChangeButtionActionPerformed(java.awt.event.ActionEvent evt) { new PassChange(user,right); this.dispose(); } private void changeInfoButtonActionPerformed(java.awt.event.ActionEvent evt) { new InfoChange(user,right); this.dispose(); } private void userManageButtonMouseClicked(java.awt.event.MouseEvent evt) { if(right==1)new UserManage(); } private void exitButtonMouseClicked(java.awt.event.MouseEvent evt) { System.exit(0); } private void infoSearchButtonMouseClicked(java.awt.event.MouseEvent evt) { InfoShow1 infoShow = new InfoShow1(user); } private void showInfo(String u){}//slightly
4 change of information
There are two difficulties in information modification. One is to obtain string data from the text box and convert it to the corresponding format data. The other is to write sql statements. The other is to write two statements.
It should be noted that salaries can only be changed by administrators.
Text box information extraction
Note that when extracting numbers, if the data is empty, an error will be reported in the direct conversion and saving. You can judge whether there is any data first, and then proceed Double.parseDouble(), or Integer.parseInt() format conversion.
After the information is extracted, judge whether there is empty text, give a warning, and confirm that all data is not empty. Then a confirmation box will pop up for database operation.
private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) { //data gather phone=phoneText.getText(); position=positText.getText(); skill=skillText.getText(); city=cityText.getText(); name=nameText.getText(); experience=experienceText.getText(); String u=salaryText.getText(); if(!u.isEmpty()){ double i=Double.parseDouble(u); this.salary=i; } u=yearText.getText(); if(!u.isEmpty()){ int i=Integer.parseInt(u); this.year=i; } if(phone.isEmpty()||position.isEmpty()||skill.isEmpty()||city.isEmpty()||skill.isEmpty()||name.isEmpty()||experience.isEmpty()){ JOptionPane.showMessageDialog(this,"One of the information is empty,please check again","Wrong",JOptionPane.WARNING_MESSAGE); new InfoChange(username,authority); this.dispose(); } else{ int n = JOptionPane.showConfirmDialog(null, "Comfirm?", "Comfirm Frame", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { dbOperation db=new dbOperation(); db.change(); new MainFrame(username,authority); this.dispose(); } } }
Database operations
When writing database language, you should note that if it is string data, you need to add a '' on both sides of the variable, and the number is not required.
private class dbOperation{ String sql = null; DbConnect db = null; ResultSet ret = null; //update info in mysql void change(){ try { sql="update person set name ='"+name+"',phone ='"+phone+"',position ='"+position+"',salary ="+salary+",skill ='"+skill+"',city ='"+city+"',workyear ="+year+",experience ='"+experience+"'"; db=new DbConnect(sql); db.pst.executeUpdate(sql); db.close(); } catch (SQLException e) { e.printStackTrace(); } } void show(){} //Display of current user information }
5 information display
JScrollPane is used for information display to hold data tables, and DefaultTableModel is used for table generation, such as model=new DefaultTableModel(data, t). Where, data is a two-dimensional vector, data is stored, and t is the header.
public class InfoShow1 extends JFrame{ String username; JTable table; DefaultTableModel model; public InfoShow1(String user) { this.username=user; this.setSize(800,550); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation((dim.width - this.getWidth()) / 2, (dim.height - this.getHeight()) / 2); this.setTitle("Info Show"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); this.setResizable(false); table=new JTable(); table.setBounds(10,100,900,400); model=new DefaultTableModel(); this.showInfo(); table.setModel(model); JScrollPane sp=new JScrollPane(table); sp.setBounds(50,100,900,400); this.add(sp); this.setVisible(true); } public void showInfo() { String sql=null; DbConnect db=null; ResultSet ret=null; sql="select name,salary,skill,workyear,experience from person"; //query db=new DbConnect(sql); try { ret=db.pst.executeQuery(); ResultSetMetaData rsmd=ret.getMetaData(); int count =rsmd.getColumnCount(); Vector t=new Vector(); for(int i=1;i<=count;i++) { //table head t.add(rsmd.getColumnName(i)); } Vector data=new Vector();//Two dimensional vector while(ret.next()) { Vector v1=new Vector(); for(int i=0;i<count;i++) { v1.add(ret.getString(i+1)); } data.add(v1); //v1 represents a row of data } model=new DefaultTableModel(data, t); //Generate table ret.close(); db.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void main(String user) { InfoShow1 infoShow1 = new InfoShow1(user); } }