1小时学会通过Java Swing Design设计java图形化(3)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 1小时学会通过Java Swing Design设计java图形化

5、JDBC

需要数据库jar包

mysql-connector-java-5.1.7bin.jar

下载链接:https://download.csdn.net/download/feng8403000/85610502

MySQL

DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`  (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `createDate` datetime(0) NOT NULL,
  `userName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `sex` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `introduce` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (1, '2022-06-11 12:55:02', '王语嫣', '女', '琅嬛福地,神仙姐姐。');
INSERT INTO `users` VALUES (2, '2022-06-11 12:56:05', '小龙女', '女', '冰山美人');
SET FOREIGN_KEY_CHECKS = 1;

JDCB_Demo

package com.item.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * 数据库工厂
 * @author Administrator
 *
 */
public class FactoryDB {
  /**
   * 驱动位置
   */
  private static final String driver ="com.mysql.jdbc.Driver";
  /**
   * 数据库链接路径·必背
   */
  private static final String url ="jdbc:mysql://127.0.0.1:3306/mytest?characterEncoding=utf-8";
  /**
   * 数据库账号
   */
  private static final String user ="root";
  /**
   * 数据库密码
   */
  private static final String pwd ="12345678";
  /**
   * 静态块引入数据库驱动·解决包位置问题
   */
  static {
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * 数据库链接
   * @return
   */
  public static Connection getConn() {
    Connection conn = null;
    try {
      conn = DriverManager.getConnection(url,user,pwd);
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return conn;
  }
  /**
   * 关闭数据库连接
   * @param conn
   * @param pr
   * @param re
   */
  public static void close(Connection conn,PreparedStatement pr, ResultSet re) {
    try {
      if (re!=null) {
        re.close();
      } 
      if(pr!=null){
        pr.close();
      }
      if(conn!=null){
        conn.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

封装模型:

package com.item.model;
import java.util.Date;
public class Users {
  @Override
  public String toString() {
    return "Users [id=" + id + ", creaetDate=" + creaetDate + ", userName=" + userName + ", sex=" + sex
        + ", introduce=" + introduce + "]";
  }
  private int id;
  private Date creaetDate;
  private String userName;
  private String sex;
  private String introduce;
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public Date getCreaetDate() {
    return creaetDate;
  }
  public void setCreaetDate(Date creaetDate) {
    this.creaetDate = creaetDate;
  }
  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public String getSex() {
    return sex;
  }
  public void setSex(String sex) {
    this.sex = sex;
  }
  public String getIntroduce() {
    return introduce;
  }
  public void setIntroduce(String introduce) {
    this.introduce = introduce;
  }
}

UI层添加数据:

JTable需要绑定一下俩数据:

//添加标题
Vector vTitle  = new Vector();
//添加数据
Vector vdate = new Vector();
//绑定到控件
table.setModel(new DefaultTableModel(vdate,vTitle));
package com.item.ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.item.dao.UsersDAO;
import com.item.model.Users;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class utest extends JFrame {
  /**
   * 序列
   */
  private static final long serialVersionUID = 1L;
  private JPanel contentPane;
  private JTextField userName;
  private JTable table;
  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
          utest frame = new utest();
          frame.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
  /**
   * Create the frame.
   */
  public utest() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 667, 598);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
    JPanel panel = new JPanel();
    contentPane.add(panel, BorderLayout.NORTH);
    //添加按钮
    JButton btnNewButton = new JButton("\u6DFB\u52A0");
    btnNewButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        AddUsers users = new AddUsers();
        users.setVisible(true);
      }
    });
    panel.add(btnNewButton);
    userName = new JTextField();
    panel.add(userName);
    userName.setColumns(20);
    //查询按钮
    JButton btnNewButton_2 = new JButton("\u67E5\u8BE2");
    btnNewButton_2.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        bind(userName.getText());
      }
    });
    panel.add(btnNewButton_2);
    JPanel panel_1 = new JPanel();
    contentPane.add(panel_1, BorderLayout.SOUTH);
    //删除
    JButton btnNewButton_1 = new JButton("\u9009\u4E2D\u884C\u70B9\u8FD9\u91CC\u5220\u9664");
    btnNewButton_1.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        int i = table.getSelectedRow();
        if (i==-1) {
          JOptionPane.showMessageDialog(null,"请选择删除的行");
          return ;
        }
        String id  = table.getValueAt(i, 0).toString();
        boolean isf = UsersDAO.DeleteById(Integer.parseInt(id));
        if (isf) {
          JOptionPane.showMessageDialog(null, "删除成功!!!");
        } else {
          JOptionPane.showMessageDialog(null, "删除失败!!!");
        }
        bind(null);
      }
    });
    panel_1.add(btnNewButton_1);
    //刷新按钮
    JButton btnNewButton_3 = new JButton("\u6570\u636E\u5237\u65B0");
    btnNewButton_3.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        bind(null);
      }
    });
    panel_1.add(btnNewButton_3);
    JScrollPane scrollPane = new JScrollPane();
    contentPane.add(scrollPane, BorderLayout.CENTER);
    table = new JTable();
    scrollPane.setViewportView(table);
    bind(null);
  }
  //加载数据
  public void bind(String userName) {
    //添加标题
    Vector<String> vTitle  = new Vector<String>();
    vTitle.add("编号");
    vTitle.add("创建时间");
    vTitle.add("用户名");
    vTitle.add("性别");
    vTitle.add("简介");
    //添加数据
    Vector vdate = new Vector<Users>();
    ArrayList<Users> list = UsersDAO.GetInfo(userName);
    for (Users u : list) {
      Vector v = new Vector();
      v.add(u.getId());
      v.add(u.getCreaetDate());
      v.add(u.getUserName());
      v.add(u.getSex());
      v.add(u.getIntroduce());
      vdate.add(v);
    }
    table.setModel(new DefaultTableModel(vdate,vTitle));
  }
}

效果

image.png

添加:如果有单选按钮得分组

image.png

为了方便操作,别忘改一个控件的名称:

image.png

image.png

双击添加按钮:

image.png

image.png


添加编码:

1.
package com.item.ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.item.dao.UsersDAO;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddUsers extends JFrame {
  private JPanel contentPane;
  private JTextField userName;
  private final ButtonGroup buttonGroup = new ButtonGroup();
  public utest utest;
  /**
   * Launch the application.
   */
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        try {
          AddUsers frame = new AddUsers();
          frame.setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
  /**
   * Create the frame.
   */
  public AddUsers() {
    setBounds(100, 100, 589, 457);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    JLabel lblNewLabel = new JLabel("\u7528\u6237\u540D");
    lblNewLabel.setBounds(100, 88, 76, 29);
    contentPane.add(lblNewLabel);
    JLabel lblNewLabel_1 = new JLabel("\u7B80\u4ECB");
    lblNewLabel_1.setBounds(100, 209, 54, 15);
    contentPane.add(lblNewLabel_1);
    JRadioButton sex1 = new JRadioButton("\u7537");
    buttonGroup.add(sex1);
    sex1.setSelected(true);
    sex1.setBounds(200, 141, 121, 23);
    contentPane.add(sex1);
    JLabel lblNewLabel_2 = new JLabel("\u6027\u522B");
    lblNewLabel_2.setBounds(100, 145, 54, 15);
    contentPane.add(lblNewLabel_2);
    JRadioButton sex2 = new JRadioButton("\u5973");
    buttonGroup.add(sex2);
    sex2.setBounds(357, 141, 121, 23);
    contentPane.add(sex2);
    userName = new JTextField();
    userName.setBounds(160, 92, 278, 21);
    contentPane.add(userName);
    userName.setColumns(10);
    JTextArea introduce = new JTextArea();
    introduce.setBounds(164, 204, 291, 117);
    contentPane.add(introduce);
    JButton btnNewButton = new JButton("\u6DFB\u52A0");
    btnNewButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String name = userName.getText();
        boolean isf = sex1.isSelected();
        String sex=isf?"男":"女";
        String intro = introduce.getText();
        boolean addInfo = UsersDAO.AddInfo(name, sex, intro);
        JOptionPane.showMessageDialog(null, addInfo?"添加成功!!!":"添加失败!!!");
      }
    });
    btnNewButton.setBounds(231, 357, 93, 23);
    contentPane.add(btnNewButton);
  }
}
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1天前
|
存储 设计模式 前端开发
[笔记] 疯狂JAVA讲义(第3版)第12章 Swing编程
[笔记] 疯狂JAVA讲义(第3版)第12章 Swing编程
|
1天前
|
Java Windows
基于java Swing编写扫雷游戏设计实现(已调试)
基于java Swing编写扫雷游戏设计实现(已调试)
4 1
|
8天前
|
Java
JAVA Swing自定义JScorllPanel
JAVA Swing自定义JScorllPanel
9 1
|
8天前
|
Java
Java Swing模拟水波纹扩散效果动画
Java Swing模拟水波纹扩散效果动画
17 6
|
9天前
|
Java
Java Swing 层次面板(JLayeredPanel) Demo
Java Swing 层次面板(JLayeredPanel) Demo
8 0
|
9天前
|
缓存 Java
Java Swing 2D系统属性参数详解
Java Swing 2D系统属性参数详解
12 0
|
9天前
|
Java
【Gloomyfish】Java Swing 实现实际大小到全屏切换
【Gloomyfish】Java Swing 实现实际大小到全屏切换
10 1
|
17天前
|
设计模式 Java 开发者
Java一分钟之-Swing组件:JTable, JTree, JTextArea
本文介绍了Java Swing的三个关键组件:`JTable`、`JTree`和`JTextArea`,用于数据展示和用户输入。`JTable`展示二维数据,如表格;`JTree`展示层次结构数据,如文件系统;`JTextArea`则用于多行文本输入和显示。每个组件都提供了示例代码,并列出常见问题及避免方法,如数据源未设置、滚动面板缺失等。理解并掌握这些组件,能帮助开发者创建高效用户界面。
30 0
|
17天前
|
设计模式 Java 容器
Java一分钟之-Swing基础:JFrame, JPanel, JButton
Java Swing教程介绍了构建桌面应用的关键组件:JFrame(顶级容器,显示主窗口)、JPanel(组合其他组件的容器)和JButton(交互元素)。文中通过示例代码展示了这些组件的使用,并列出常见问题及解决方法,如确保设置JFrame的可见性和关闭操作,正确添加组件至JPanel,以及为JButton添加事件监听器。理解这些基础将有助于开发功能完善的GUI应用。
10 0
|
19天前
|
设计模式 安全 Java
【设计模式】JAVA Design Patterns——Curiously Recurring Template Pattern(奇异递归模板模式)
该文介绍了一种C++的编程技巧——奇异递归模板模式(CRTP),旨在让派生组件能继承基本组件的特定功能。通过示例展示了如何创建一个`Fighter`接口和`MmaFighter`类,其中`MmaFighter`及其子类如`MmaBantamweightFighter`和`MmaHeavyweightFighter`强制类型安全,确保相同重量级的拳手之间才能进行比赛。这种设计避免了不同重量级拳手间的错误匹配,编译时会报错。CRTP适用于处理类型冲突、参数化类方法和限制方法只对相同类型实例生效的情况。
【设计模式】JAVA Design Patterns——Curiously Recurring Template Pattern(奇异递归模板模式)