Experiment 5 graphical application development
<center> <strong>full name:</strong> <u>XXX</u>    <strong>Class:</strong> <u>XXXXX</u>    <strong>Student number:</strong> <u>XXXXXXXXXXXX</u></center>
1, Experimental purpose
The development of user graphical application program is realized by designing relevant classes and interfaces through graphical interface;
Further consolidate JDBC connection to the database and file reading and writing operations.
2, Experimental objectives:
(1) Be able to flexibly use some common classes in Java API (such as String, StringBuffer, System, Runtime, Math, Random, etc.) to solve practical problems by reading Java API documents.
(2) Be able to flexibly use the common collection classes of Java language (ArrayList, Map, Collections, Array, etc.) to solve practical problems.
3, Experiment content:
- Use GUI to simulate user login. The interface design is shown in Figure 1:
All user names and passwords are stored in the database;
Define a class that uses JDBC to connect to the database and reads the user name and password data for matching to realize user login. If the login is successful, the user will be prompted that the login is successful; otherwise, the user will be prompted that the login fails;
- Design a graphical application program for file operation to realize at least the following functions:
It includes a text box and an add button. After entering text in the text box, click the Add button to write the text in the text box in the file;
It contains a read button. After clicking this button, the file content can be read and displayed in the text box.
4, Experimental process analysis
4.1 experimental steps
-
Use GUI to simulate user login. The interface design is shown in Figure 1:
Figure 1 user login interface
All user names and passwords are stored in the database;
Define a class that uses JDBC to connect to the database and reads the user name and password data for matching to realize user login. If the login is successful, the user will be prompted that the login is successful; otherwise, the user will be prompted that the login fails;
Experimental code
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.SQLException; import java.sql.Statement; class sqlTest{ public sqlTest(String User,String PASS){ pass=PASS; user=User; } public boolean Connect(){ Connection conn = null; Statement stmt = null; try{ // Register JDBC Driver String JDBC_DRVER = "com.mysql.cj.jdbc.Driver"; Class.forName(JDBC_DRVER); // Open link String DB_URL = "jdbc:mysql://localhost:3306/mysql?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; conn = DriverManager.getConnection(DB_URL,user,pass); System.out.println(conn.toString()); conn.close(); return true;} catch (SQLException e) { e.printStackTrace(); return false;} catch (ClassNotFoundException e) { e.printStackTrace(); return false;}} private String pass; private String user;} public class GUI { public static void main(String[] args) { JFrame frame =new JFrame("Sign in"); frame.setSize(426,327); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.setResizable(false); //Center form Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.width > displaySize.width) frameSize.width = displaySize.width; frame.setLocation((displaySize.width - frameSize.width) / 2, (displaySize.height - frameSize.height) / 2); JPanel panel=new JPanel(); frame.add(panel); placeComponents(panel); frame.setVisible(true);} private static void placeComponents(JPanel panel) { /* We won't introduce more about the layout * Set the layout here to null */ panel.setLayout(null); // Create JLabel JLabel userLabel = new JLabel("User:"); /* This method defines the location of the component. * setBounds(x, y, width, height) * x And y specify the new position of the upper left corner, and width and height specify the new size. */ userLabel.setBounds(80,80,80,25); panel.add(userLabel); /* * Create a text field for user input */ JTextField userText = new JTextField(20); userText.setBounds(160,80,165,25); panel.add(userText); // Enter the text field for the password JLabel passwordLabel = new JLabel("Password:"); passwordLabel.setBounds(80,120,80,25); panel.add(passwordLabel); /* *This is similar to the text field used for input * However, the information entered will be replaced by a point number to include the security of the password */ JPasswordField passwordText = new JPasswordField(20); passwordText.setBounds(160,120,165,25); panel.add(passwordText); JLabel tipsJLabel = new JLabel(""); tipsJLabel.setBounds(80,200,246,25); panel.add(tipsJLabel); // Create login button JButton loginButton = new JButton("login"); loginButton.setBounds(80, 170, 80, 25); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String username =userText.getText(); String password = passwordText.getText(); sqlTest sql=new sqlTest(username,password); if (sql.Connect()){ tipsJLabel.setText("Login successful, will be in 2 s Jump");} else {tipsJLabel.setText("Login failed, wrong user name or password");}}}); panel.add(loginButton); //Create empty button JButton cleanButton = new JButton("clean"); cleanButton.setBounds(245,170,80,25); cleanButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e){ userText.setText(""); passwordText.setText("");}}); panel.add(cleanButton);}}
experimental result
Figure 1 login failure Figure 2 login success- Design a graphical application program for file operation to realize at least the following functions:
It includes a text box and an add button. After entering text in the text box, click the Add button to write the text in the text box in the file;
It contains a read button. After clicking this button, the file content can be read and displayed in the text box.
Experimental code
import lombok.SneakyThrows; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.nio.charset.StandardCharsets; class FileSaveOpen extends JFrame { private final JFrame thisFrame = this; private final JPanel rootPanel = new JPanel(); private final JLabel titleLabel = new JLabel("Text"); private final JButton saveButton = new JButton("preservation"); private final JButton openButton = new JButton("open"); private final JTextArea inputTextArea = new JTextArea(); private final JTextArea outputTextArea = new JTextArea(); private final JLabel TipsLable = new JLabel(); public static void main(String[] args) throws InterruptedException { new FileSaveOpen("");} FileSaveOpen(String name) { super(name); this.setBounds(new Rectangle(600, 300, 400, 300)); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setVisible(true); this.dataInitialize(); this.componentInitial(); this.setParameter(); this.dealLogic();} private void dataInitialize() { } private void componentInitial() { this.setComponent(); this.setComponentsLayout(); this.setComponentsPreferredSize(); this.setComponentsHorizontalAlignment();} private void setComponent() { rootPanel.add(titleLabel); rootPanel.add(saveButton); rootPanel.add(openButton); rootPanel.add(inputTextArea); rootPanel.add(TipsLable); rootPanel.add(outputTextArea);} private void setComponentsLayout() { this.setContentPane(rootPanel); rootPanel.setLayout(null); titleLabel.setBounds(new Rectangle(30, 0, 30, 25)); saveButton.setBounds(new Rectangle(240, 0, 60, 25)); openButton.setBounds(new Rectangle(320, 0, 60, 25)); inputTextArea.setBounds(new Rectangle(5, 30, 375, 50)); TipsLable.setBounds(new Rectangle(100,85,375,25)); outputTextArea.setBounds(new Rectangle(5,120,375,150));} private void setComponentsPreferredSize() { titleLabel.setPreferredSize(new Dimension(100, 100));} private void setComponentsHorizontalAlignment() { titleLabel.setHorizontalAlignment(SwingConstants.CENTER); saveButton.setHorizontalAlignment(SwingConstants.CENTER); openButton.setHorizontalAlignment(SwingConstants.CENTER);} private void setParameter() {} private void dealLogic() { saveButton.addActionListener(new saveButtonActionListener()); openButton.addActionListener(new openButtonActionListener());} class saveButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { TipsLable.setFont(new Font("Blackbody",Font.PLAIN,15)); String contents = inputTextArea.getText(); File file = new File("../data.txt"); if (!file.exists()) { try { if (!file.createNewFile()) { TipsLable.setText("File creation failed"); TipsLable.setForeground(Color.red); return; } } catch (IOException ex) { ex.printStackTrace();}} FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(file); fileOutputStream.write(contents.getBytes(StandardCharsets.UTF_8)); fileOutputStream.flush(); fileOutputStream.close(); TipsLable.setText("File written successfully"); TipsLable.setForeground(Color.BLUE); } catch (IOException ex) { ex.printStackTrace(); TipsLable.setText("There was a problem writing the file"); TipsLable.setForeground(Color.red);}}} class openButtonActionListener implements ActionListener { @SneakyThrows @Override public void actionPerformed(ActionEvent e) { int length = 10000000; byte[] buffer = new byte[length]; File file = new File("../data.txt"); try { InputStream inputStream = new FileInputStream(file); int n = inputStream.read(buffer, 0, length); inputStream.close(); String str = new String(buffer, 0, n, StandardCharsets.UTF_8); outputTextArea.setText(str); } catch (FileNotFoundException c) { c.printStackTrace();}}}}
experimental result
Figure 4 saving and opening a file4.2 error analysis
- Problem recurrence
Could not create connection to database server appears Report an error, check that your url statement is correct, and the user name and password of the database are correct.
- problem analysis
After investigation, mysql8 Version 0 needs to replace the driver with com mysql. cj. jdbc. Driver, previous com mysql. jdbc. Driver is no longer available in MySQL version 8.0
- Solution
Use select version() from dual;, Query to get my MySQL version of 8.0.27 Then from Maven Repository: mysql » mysql-connector-java » 8.0.27 (mvnrepository.com) Download the driver and connect JDBC_DRVER driver from com mysql. jdbc. Change driver to com mysql. cj. jdbc. Driver.
5, Experimental summary
through this experiment, I learned and mastered the relevant operations of java GUI, and experienced the development of graphical interface application through accessing database and user login. In the process of database connection, the related problems are solved, and the proficiency of the related operations used by jadbc is deepened. This is very helpful for our future program development and design. Through this experiment, we also try to use the combination of GUI and file operation for file visual reading and writing operation. Through this experiment, we not only learned GUI related knowledge, but also further consolidated JDBC connection database and file reading and writing operation.