实验五 java gui

实验五 java gui,第1张

实验五 java gui
实验五 图形化应用程序开发
姓名: XXX    班级: XXXXX    学号: XXXXXXXXXXXX
一、实验目的

通过图形化界面设计相关类、接口等,实现用户图形化应用程序的开发;

进一步巩固JDBC连接数据库以及文件读写 *** 作。

二、 实验目标:

(1)能够通过阅读Java API文档来灵活运用Java API中的一些常用类(例如String、StringBuffer、System、Runtime、Math、Random等)来解决实际问题。

(2)能够灵活运用用Java语言的常用集合类(ArrayList、Map、Collections、Array等)来解决实际问题。

三、实验内容:
    利用GUI模拟用户登录,界面设计如图1:
    所有的用户名密码存储在数据库中;
    定义一个类使用JDBC连接数据库,读取用户名密码数据进行匹配以实现用户登录,若登录成功,提示用户登录成功,否则,提示用户登录失败;
图1 用户登录界面
    设计一个关于文件 *** 作的图形化应用程序,至少实现以下功能:
    包含一个文本框以及添加按钮,在文本框中输入文字后,点击添加按钮可以在文件中写入文本框中的文字;
    包含一个读取按钮,点击该按钮后,可以读取文件内容,并显示到文本框中。
四、实验过程分析 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) {

        
        panel.setLayout(null);
        // 创建 JLabel
        JLabel userLabel = new JLabel("User:");
        
        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);}}

实验结果

图 1 登录失败
图2 登录成功

设计一个关于文件 *** 作的图形化应用程序,至少实现以下功能:
包含一个文本框以及添加按钮,在文本框中输入文字后,点击添加按钮可以在文件中写入文本框中的文字;
包含一个读取按钮,点击该按钮后,可以读取文件内容,并显示到文本框中。

实验代码

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 保存文件并打开文件
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连接数据库以及文件读写 *** 作。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5716155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存