实验五 图形化应用程序开发
<center>
<strong>姓名:</strong>
<u>XXX</u>
  
<strong>班级:</strong>
<u>XXXXX</u>
  
<strong>学号:</strong>
<u>XXXXXXXXXXXX</u></center>
一、实验目的
通过图形化界面设计相关类、接口等,实现用户图形化应用程序的开发;
进一步巩固JDBC连接数据库以及文件读写操作。
二、 实验目标:
(1)能够通过阅读Java API文档来灵活运用Java API中的一些常用类(例如String、StringBuffer、System、Runtime、Math、Random
等)来解决实际问题。
(2)能够灵活运用用Java语言的常用集合类(ArrayList、Map、Collections、Array
等)来解决实际问题。
三、实验内容:
- 利用GUI模拟用户登录,界面设计如图1:
所有的用户名密码存储在数据库中;
定义一个类使用JDBC连接数据库,读取用户名密码数据进行匹配以实现用户登录,若登录成功,提示用户登录成功,否则,提示用户登录失败;
- 设计一个关于文件操作的图形化应用程序,至少实现以下功能:
包含一个文本框以及添加按钮,在文本框中输入文字后,点击添加按钮可以在文件中写入文本框中的文字;
包含一个读取按钮,点击该按钮后,可以读取文件内容,并显示到文本框中。
四、实验过程分析
4.1 实验步骤
-
利用GUI模拟用户登录,界面设计如图1:
所有的用户名密码存储在数据库中;
定义一个类使用JDBC连接数据库,读取用户名密码数据进行匹配以实现用户登录,若登录成功,提示用户登录成功,否则,提示用户登录失败;图1 用户登录界面
实验代码
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{
// 注册 JDBC 驱动
String JDBC_DRVER = "com.mysql.cj.jdbc.Driver";
Class.forName(JDBC_DRVER);
// 打开链接
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("登录");
frame.setSize(426,327);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setResizable(false);
//窗体居中显示
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) {
/* 布局部分我们这边不多做介绍
* 这边设置布局为 null
*/
panel.setLayout(null);
// 创建 JLabel
JLabel userLabel = new JLabel("User:");
/* 这个方法定义了组件的位置。
* setBounds(x, y, width, height)
* x 和 y 指定左上角的新位置,由 width 和 height 指定新的大小。
*/
userLabel.setBounds(80,80,80,25);
panel.add(userLabel);
/*
* 创建文本域用于用户输入
*/
JTextField userText = new JTextField(20);
userText.setBounds(160,80,165,25);
panel.add(userText);
// 输入密码的文本域
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(80,120,80,25);
panel.add(passwordLabel);
/*
*这个类似用于输入的文本域
* 但是输入的信息会以点号代替,用于包含密码的安全性
*/
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);
// 创建登录按钮
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("登录成功,将在2s跳转");}
else {tipsJLabel.setText("登录失败,用户名或密码错误");}}});
panel.add(loginButton);
//创建清空按钮
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);}}
实验结果
- 设计一个关于文件操作的图形化应用程序,至少实现以下功能:
包含一个文本框以及添加按钮,在文本框中输入文字后,点击添加按钮可以在文件中写入文本框中的文字;
包含一个读取按钮,点击该按钮后,可以读取文件内容,并显示到文本框中。
实验代码
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("文 本");
private final JButton saveButton = new JButton("保存");
private final JButton openButton = new JButton("打开");
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("黑体",Font.PLAIN,15));
String contents = inputTextArea.getText();
File file = new File("../data.txt");
if (!file.exists()) {
try {
if (!file.createNewFile()) {
TipsLable.setText("文件创建失败");
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("文件写入成功");
TipsLable.setForeground(Color.BLUE);
} catch (IOException ex) {
ex.printStackTrace();
TipsLable.setText("文件写入出现问题");
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();}}}}
实验结果
4.2 错误分析
- 问题复现
出现Could not create connection to database server.
报错,检查自己的url语句并没有错误,数据库的用户名和密码也都正确。
- 问题分析
经排查是,MySQL8.0
版本需要更换驱动为com.mysql.cj.jdbc.Driver,
之前的com.mysql.jdbc.Driver
已经不能在MySQL 8.0
版本使用了.
- 解决方案
使用select version() from dual;
,查询获得我的MySQL
版本为8.0.27
.然后从Maven Repository: mysql » mysql-connector-java » 8.0.27 (mvnrepository.com)下载驱动,并将JDBC_DRVER
的驱动从com.mysql.jdbc.Driver
改为com.mysql.cj.jdbc.Driver
.
五、实验总结
通过本次实验学习并掌握了java GUI
的相关操作,并通过接入数据库以及用户登陆操作体验了图形化界面应用程序的开发。并在数据库连接的过程中解决了相关问题,加深了对于jadbc
使用的相关操作的熟练程度。这对于我们今后的程序开发设计很有帮助,通过本次实验也尝试了GUI与文件操作的搭配使用进行文件可视化读写操作。通过本次实验不仅学习了GUI相关知识,也进一步巩固JDBC连接数据库以及文件读写操作。