首先给大家推荐一个学习Swing的好博文点这里去学习Swing
话不多说,直接上代码。
数据库和类相关信息
首先在mysql数据库有下面的表格
数据库名:chenzi 表格:login,student
下面是创建的类的信息
ps:jdbc.properties是配置文件,存放数据库信息的
代码
Welcome
package Manager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Welcome extends JFrame {
//定义需要别的类调用的数据
static JTextField jte;
static JPasswordField jpa;
static Welcome frame = new Welcome();
public Welcome(){
//创建容器并放相关组件
Font font = new Font(null,Font.PLAIN,15);
JPanel jpTitle = new JPanel();
JLabel jlTitle = new JLabel("管理系统");
jlTitle.setFont(new Font(null,Font.PLAIN,30));
jpTitle.add(jlTitle);
JPanel jpName =new JPanel();
JLabel jlUser = new JLabel("用户名 ");
jlUser.setFont(font);
jpName.add(jlUser);
jte = new JTextField(10);
jpName.add(jte);
JPanel jpPassword = new JPanel();
JLabel jlPassword = new JLabel("密码 ");
jlPassword.setFont(font);
jpPassword.add(jlPassword);
jpa = new JPasswordField(10);
jpPassword.add(jpa);
JPanel jpButton = new JPanel();
JButton button0 = new JButton("登录");
button0.setFont(font);
jpButton.add(button0);
JButton button1 = new JButton("注册");
button1.setFont(font);
jpButton.add(button1);
//创建盒子放容器
Box vbox = Box.createVerticalBox();
vbox.add(jpTitle);
vbox.add(jpName);
vbox.add(jpPassword);
vbox.add(jpButton);
//把盒子放进frame容器
add(vbox);
//按钮事件调取登录或者注册方法
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Login.login();
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Register.register();
}
});
}
public static void main(String[] args) {
frame.setTitle("尘子先生的测试");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//创建关闭窗体方法供调用
public static void exit(){
frame.dispose();
}
}
Login
package Manager;
import javax.swing.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Login {
public static void login() {
Connection conn;
{
try {
//调取方法连接数据库
conn = Connect.getConnection();
Statement sta = conn.createStatement();
String name = Welcome.jte.getText();
//getPassword方法返回的并不是String类型,需要转换。
String password = String.valueOf(Welcome.jpa.getPassword());
//注意sql语句书写规范
String sql = "select password from Login where name ='"+name+"'";
ResultSet re = sta.executeQuery(sql);
if (name.equals("") || password.equals("")) {
JOptionPane.showMessageDialog(null, "用户名或密码不能为空!", "错误!", JOptionPane.ERROR_MESSAGE);
}
else{
//if进行判断,若用户名存在,re有数据,re.next()为ture;
if (re.next()) {
if (!password.equals(re.getString("password"))) {
JOptionPane.showMessageDialog(null, "用户名或密码不对!", "错误", JOptionPane.ERROR_MESSAGE);
} else {
//先关闭登录窗口,再通过方法创建新窗口
Welcome.exit();
Main.main();
}
}
else {
JOptionPane.showMessageDialog(null, "用户名或密码不对!", "错误", JOptionPane.ERROR_MESSAGE);
}
}
//注意要关闭连接释放资源
re.close();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Register
package Manager;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Register {
private static JTextField jTextField;
private static JPasswordField jPasswordField ;
public static void register(){
//创建新的窗口
JFrame newJFrame = new JFrame("注册");
newJFrame.setSize(300,300);
newJFrame.setLocationRelativeTo(Welcome.frame);
newJFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
newJFrame.setResizable(false);
//容器与组件
JPanel jptitle = new JPanel();
JLabel jltitle = new JLabel("欢迎您注册");
jptitle.add(jltitle);
JPanel jpname = new JPanel();
JLabel jlname = new JLabel("请输入用户名");
jpname.add(jlname);
jTextField = new JTextField(10);
//注意 String name = jTextField.getText();在这里写是无效的
jpname.add(jTextField);
JPanel jppassword = new JPanel();
JLabel jlpassword = new JLabel("请输入密码");
jppassword.add(jlpassword);
jPasswordField = new JPasswordField(10);
jppassword.add(jPasswordField);
JPanel jpbutton = new JPanel();
JButton button1 = new JButton("确认");
JButton button2 = new JButton("取消");
jpbutton.add(button1);
jpbutton.add(button2);
Box vbox = Box.createVerticalBox();
vbox.add(jptitle);
vbox.add(jpname);
vbox.add(jppassword);
vbox.add(jpbutton);
newJFrame.add(vbox);
newJFrame.setVisible(true);
//创建按钮事件
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
succeed();
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
newJFrame.dispose();
}
});
}
public static void succeed(){
String sql;
String name = jTextField.getText();
String password = String.valueOf(jPasswordField.getPassword());
Connection conn;
try {
//调取方法链接数据库
conn = Connect.getConnection();
Statement sta = conn.createStatement();
sql = "select * from Login where name ='"+ name +"'";
ResultSet re = sta.executeQuery(sql);
//if进行判断,若有返回数据,则数据库中已存在改用户,不能注册
if (re.next()) {
JOptionPane.showMessageDialog(null, "用户名已存在!", "错误", JOptionPane.ERROR_MESSAGE);
}
else {
if (name.equals("") || password.equals("")) {
JOptionPane.showMessageDialog(null, "用户名或密码不能为空!", "错误!", JOptionPane.ERROR_MESSAGE);
} else {
sql = "insert into Login(name,password) values('"+ name +"','"+ password +"')";
sta.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"注册成功!","恭喜",JOptionPane.PLAIN_MESSAGE);
}
}
//关闭连接释放资源
re.close();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Main
package Manager;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class Main {
static JPanel jPanelAdd = new JPanel();
static JPanel jPanelDelete = new JPanel();
static JPanel jPanelRevamp = new JPanel();
static JPanel jPanelInquire = new JPanel();
public static void main(){
//新建一个主页面
JFrame jFrame = new JFrame();
jFrame.setSize(800,600);
jFrame.setLocationRelativeTo(null);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//用JTabbedPane(选项卡面板)
JTabbedPane jTabbedPane = new JTabbedPane();
//用方法返回容器,添加到选项卡面板
//调取方法时要传入一个容器
jTabbedPane.addTab("增加", Add.add(jPanelAdd) );
jTabbedPane.addTab("删除", Delete.delete(jPanelDelete) );
jTabbedPane.addTab("修改", Revamp.revamp(jPanelRevamp) );
jTabbedPane.addTab("查询", Inquire.inquire(jPanelInquire) );
//用setTabComponentAt方法在选项卡上添加组件,组件用方法获取
jTabbedPane.setTabComponentAt(0,Tabbed("增加"));
jTabbedPane.setTabComponentAt(1,Tabbed("删除"));
jTabbedPane.setTabComponentAt(2,Tabbed("修改"));
jTabbedPane.setTabComponentAt(3,Tabbed("查询"));
//设置默认选项卡
jTabbedPane.setSelectedIndex(0);
jTabbedPane.getTabComponentAt(0).setBackground(Color.gray);
//添加选项卡选中状态改变的监听器
jTabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
//使用循环消除之前给选项卡容器给的背景颜色
for (int i = 0; i < 4; i++) {
jTabbedPane.getTabComponentAt(i).setBackground(null);
}
//用方法给当前选项卡容器加上背景颜色
jTabbedPane.getTabComponentAt(jTabbedPane.getSelectedIndex()).setBackground(Color.gray);
}
});
jFrame.setContentPane(jTabbedPane);
jFrame.setVisible(true);
}
public static JComponent Tabbed(String text){
JPanel jpTabbed = new JPanel(new FlowLayout());
//给选项卡容器设定固定值大小
//注意:给JPanel设定大小时,不能用setsize方法
jpTabbed.setPreferredSize(new Dimension(173,50));
JLabel label = new JLabel(text);
label.setFont(new Font(null,Font.BOLD,30));
jpTabbed.add(label);
return jpTabbed;
}
}
Add
package Manager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Add {
private static String id;
private static String name;
private static String sex;
private static String age;
private static String site;
private static JTextField jtId;
private static JTextField jtName;
private static JRadioButton radioButton0;
private static JRadioButton radioButton1;
private static JTextField jtAge;
private static JTextField jtSite;
public static JComponent add(JPanel jPaneAdd){
Font font = new Font(null,Font.PLAIN,20);
//使用网格布局
JPanel jPanel = new JPanel(new GridLayout(6,2,15,15));
//给容器设定固定大小
jPanel.setPreferredSize(new Dimension(300,300));
JLabel laId = new JLabel("学号");
laId.setFont(font);
jPanel.add(laId);
jtId = new JTextField(10);
id = jtId.getText();
jPanel.add(jtId);
JLabel laName = new JLabel("姓名");
laName.setFont(font);
jPanel.add(laName);
jtName = new JTextField(10);
name = jtName.getText();
jPanel.add(jtName);
JLabel laSex = new JLabel("性别");
laSex.setFont(font);
jPanel.add(laSex);
//设置面板装单选按钮
JPanel jPanelSex = new JPanel();
radioButton0 = new JRadioButton("男");
radioButton1 = new JRadioButton("女");
radioButton0.setFont(new Font(null,Font.PLAIN,20));
radioButton1.setFont(new Font(null,Font.PLAIN,20));
// 创建按钮组,把两个单选按钮添加到该组
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton0);
buttonGroup.add(radioButton1);
//设置默认选中第一个按钮
radioButton0.setSelected(true);
jPanelSex.add(radioButton0);
jPanelSex.add(radioButton1);
jPanel.add(jPanelSex);
JLabel laAge = new JLabel("年龄");
laAge.setFont(font);
jPanel.add(laAge);
jtAge = new JTextField(10);
age = jtAge.getText();
jPanel.add(jtAge);
JLabel laSite = new JLabel("地址");
laSite.setFont(font);
jPanel.add(laSite);
jtSite = new JTextField(10);
site = jtSite.getText();
jPanel.add(jtSite);
JButton button0 = new JButton("确认");
button0.setFont(font);
jPanel.add(button0);
JButton button1 = new JButton("清空");
button1.setFont(font);
jPanel.add(button1);
jPaneAdd.add(jPanel);
//创建按钮事件,调取方法
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
succeed();
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clear();
}
});
return jPaneAdd;
}
public static void succeed(){
//获取用户输入数据
id = jtId.getText();
name = jtName.getText();
age = jtAge.getText();
site = jtSite.getText();
//判断第一个按钮是否被选中
if (radioButton0.isSelected()){
sex = "男";
}
else {
sex = "女";
}
try {
//连接数据库
Connection conn = Connect.getConnection();
Statement sta = conn.createStatement();
String sql = "select * from Student where id ='"+id+"'";
ResultSet re = sta.executeQuery(sql);
//判断是否有未输入
if (id.equals("")||name.equals("")||age.equals("")||site.equals("")) {
JOptionPane.showMessageDialog(null,"您有还有未输入!","",JOptionPane.ERROR_MESSAGE);
}
else {
//判断re是否有数据,有数据说明学号已存在
if (re.next()){
JOptionPane.showMessageDialog(null,"您输入的学号已存在!","",JOptionPane.ERROR_MESSAGE);
}
else {
//向数据库插入数据,注意插入的时候是sta.executeUpdate()
sql = "insert into Student values('"+id+"','"+name+"','"+sex+"','"+age+"','"+site+"')";
sta.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"添加成功!","",JOptionPane.PLAIN_MESSAGE);
//调取方法清除输入的数据
clear();
}
}
//关闭连接,释放资源
re.close();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clear(){
//利用setText方法清空输入数据
jtId.setText("");
jtName.setText("");
radioButton0.setSelected(true);
jtAge.setText("");
jtSite.setText("");
}
}
Delete
package Manager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Statement;
public class Delete {
private static JTextField jTextField;
public static JComponent delete(JPanel jPaneDelete){
//创建各种容器
JPanel jPanelText = new JPanel(new GridLayout(1,2,50,50));
jPanelText.setPreferredSize(new Dimension(500,40));
JLabel label = new JLabel("请输入您要删除的学生的学号");
label.setFont(new Font(null,Font.PLAIN,17));
jTextField = new JTextField(10);
jTextField.setFont(new Font(null,Font.PLAIN,15));
jPanelText.add(label);
jPanelText.add(jTextField);
//这里用的是最笨的方法,希望大佬能帮忙简化一下
Box hbutton = Box.createHorizontalBox();
JButton button0 = new JButton("确认");
//利用setPreferredSize方法给按钮设置大小
button0.setPreferredSize(new Dimension(100,80));
JButton button1 = new JButton("清除");
button1.setPreferredSize(new Dimension(100,80));
//创建横向不可见固定宽度填充
Component hStrut =Box.createHorizontalStrut(60);
//创建横向不可见弹性填充
Component hGlue1 = Box.createHorizontalGlue();
Component hGlue2 = Box.createHorizontalGlue();
hbutton.add(hGlue1);
hbutton.add(button0);
hbutton.add(hStrut);
hbutton.add(button1);
hbutton.add(hGlue2);
Component vStrut1 = Box.createVerticalStrut(50);
Component vStrut2 = Box.createVerticalStrut(35);
Box vbox = Box.createVerticalBox();
vbox.add(vStrut1);
vbox.add(jPanelText);
vbox.add(vStrut2);
vbox.add(hbutton);
//装入最终返回的容器
jPaneDelete.add(vbox);
//按钮事件调取方法
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
succeed();
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clear();
}
});
return jPaneDelete;
}
public static void succeed(){
String id = jTextField.getText();
try {
//连接数据库
Connection conn = Connect.getConnection();
Statement sta = conn.createStatement();
String sql ="Delete from Student where id = '"+id+"'";
//用int型数据获取删除的返回值,删除几行就会返回几,若是没有删除成功则返回0
int re = sta.executeUpdate(sql);
//判断是否删除成功
if (re!=0){
JOptionPane.showMessageDialog(null,"删除成功","", JOptionPane.PLAIN_MESSAGE);
}
else {
if (id.equals("")){
JOptionPane.showMessageDialog(null,"学号不能为空!","", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null,"查无此人","", JOptionPane.ERROR_MESSAGE);
}
}
//关闭连接,释放资源
clear();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clear(){
jTextField.setText("");
}
}
Revamp
package Manager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Revamp {
private static String id;
private static String name;
private static String sex;
private static String age;
private static String site;
private static JTextField jtName;
private static JRadioButton radioButton0;
private static JRadioButton radioButton1;
private static JTextField jtAge;
private static JTextField jtSite;
private static JTextField jTextField;
public static JComponent revamp(JPanel jPanelRevamp){
//利用方法来获取页面
jPanelRevamp.add(firstPanel());
return jPanelRevamp;
}
public static JComponent firstPanel(){
//创建输入学号的页面
JPanel firstPanel = new JPanel();
JPanel jPanelText = new JPanel(new GridLayout(1,2,50,50));
jPanelText.setPreferredSize(new Dimension(500,40));
JLabel label = new JLabel("请输入您要修改的学生的学号");
label.setFont(new Font(null,Font.PLAIN,17));
jTextField = new JTextField(10);
jTextField.setFont(new Font(null,Font.PLAIN,15));
jPanelText.add(label);
jPanelText.add(jTextField);
Box hbutton = Box.createHorizontalBox();
JButton button0 = new JButton("确认");
button0.setPreferredSize(new Dimension(100,80));
JButton button1 = new JButton("清除");
button1.setPreferredSize(new Dimension(100,80));
Component hStrut =Box.createHorizontalStrut(60);
Component hGlue1 = Box.createHorizontalGlue();
Component hGlue2 = Box.createHorizontalGlue();
hbutton.add(hGlue1);
hbutton.add(button0);
hbutton.add(hStrut);
hbutton.add(button1);
hbutton.add(hGlue2);
Component vStrut1 = Box.createVerticalStrut(50);
Component vStrut2 = Box.createVerticalStrut(35);
Box vbox = Box.createVerticalBox();
vbox.add(vStrut1);
vbox.add(jPanelText);
vbox.add(vStrut2);
vbox.add(hbutton);
//加入最终返回容器
firstPanel.add(vbox);
//按钮事件调取方法
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//把要返回的容器当参数传到方法
succeedFirst(firstPanel);
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearFirst();
}
});
return firstPanel;
}
public static JComponent endPanel(){
//创建新的页面
JPanel endPanel = new JPanel();
Font font = new Font(null,Font.PLAIN,20);
JPanel jPanel = new JPanel(new GridLayout(6,2,15,15));
jPanel.setPreferredSize(new Dimension(300,300));
JLabel laName = new JLabel("姓名");
laName.setFont(font);
jPanel.add(laName);
jtName = new JTextField(10);
name = jtName.getText();
jPanel.add(jtName);
JLabel laSex = new JLabel("性别");
laSex.setFont(font);
jPanel.add(laSex);
JPanel jPanelSex = new JPanel();
radioButton0 = new JRadioButton("男");
radioButton1 = new JRadioButton("女");
radioButton0.setFont(new Font(null,Font.PLAIN,20));
radioButton1.setFont(new Font(null,Font.PLAIN,20));
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioButton0);
buttonGroup.add(radioButton1);
radioButton0.setSelected(true);
jPanelSex.add(radioButton0);
jPanelSex.add(radioButton1);
jPanel.add(jPanelSex);
JLabel laAge = new JLabel("年龄");
laAge.setFont(font);
jPanel.add(laAge);
jtAge = new JTextField(10);
age = jtAge.getText();
jPanel.add(jtAge);
JLabel laSite = new JLabel("地址");
laSite.setFont(font);
jPanel.add(laSite);
jtSite = new JTextField(10);
site = jtSite.getText();
jPanel.add(jtSite);
JButton button0 = new JButton("确认");
button0.setFont(font);
jPanel.add(button0);
JButton button1 = new JButton("清空");
button1.setFont(font);
jPanel.add(button1);
JPanel button2Panel = new JPanel(new GridLayout(1,1));
JButton button2 = new JButton("退出");
button2.setFont(font);
jPanel.add(button2);
button2Panel.add(button2);
Box vbox = Box.createVerticalBox();
vbox.add(jPanel);
vbox.add(button2Panel);
endPanel.add(vbox);
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
succeedEnd(endPanel);
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearEnd();
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//退出按钮,重新构建页面,把输入学号的页面加载进来
endPanel.removeAll();
endPanel.repaint();
endPanel.add(firstPanel());
endPanel.revalidate();
}
});
return endPanel;
}
public static void succeedFirst(JPanel jPanel){
id = jTextField.getText();
try {
//连接数据库
Connection conn = Connect.getConnection();
Statement sta = conn.createStatement();
String sql ="select * from Student where id = '"+id+"'";
ResultSet re = sta.executeQuery(sql);
//判断是否有返回数据
if (re.next()){
//删除容器上的全部组件
jPanel.removeAll();
//刷新容器
jPanel.repaint();
//重新加入组件(容器)
jPanel.add(endPanel());
//重构容器大小
jPanel.revalidate();
}
else {
if (id.equals("")){
JOptionPane.showMessageDialog(null,"学号不能为空!","", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null,"查无此人","", JOptionPane.ERROR_MESSAGE);
}
}
clearFirst();
re.close();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void succeedEnd(JPanel jPanel){
name = jtName.getText();
age = jtAge.getText();
site = jtSite.getText();
if (radioButton0.isSelected()){
sex = "男";
}
else {
sex = "女";
}
try {
Connection conn = Connect.getConnection();
Statement sta = conn.createStatement();
if (id.equals("")||name.equals("")||age.equals("")||site.equals("")){
JOptionPane.showMessageDialog(null,"您有还有未输入!","",JOptionPane.ERROR_MESSAGE);
}
else {
//修改成功
String sql = "update Student set name = '" + name + "',sex = '" + sex + "',age = '" + age + "',site = '" + site + "'where id = '" + id + "'";
sta.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "修改成功!", "", JOptionPane.PLAIN_MESSAGE);
//重构页面,把输入学号的页面加载进来
jPanel.removeAll();
jPanel.repaint();
jPanel.add(firstPanel());
jPanel.revalidate();
}
//关闭连接,释放资源
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void clearFirst(){
jTextField.setText("");
}
public static void clearEnd(){
// jtId.setText("");
jtName.setText("");
radioButton0.setSelected(true);
jtAge.setText("");
jtSite.setText("");
}
}
Inquire
package Manager;
import javax.swing.*;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Inquire {
private static String id;
private static String name;
private static String sex;
private static String age;
private static String site;
private static JTextField jTextField;
public static JComponent inquire(JPanel jPaneInquire){
//先创建两个按钮,用来切换查询方式
Box hbutton = Box.createHorizontalBox();
JButton button0 = new JButton("查询一个学生信息");
button0.setFont(new Font(null,Font.PLAIN,20));
button0.setPreferredSize(new Dimension(200,30));
JButton button1 = new JButton("查询全部学生信息");
button1.setFont(new Font(null,Font.PLAIN,20));
button1.setPreferredSize(new Dimension(200,30));
Component hStrut =Box.createHorizontalStrut(100);
Component hGlue1 = Box.createHorizontalGlue();
Component hGlue2 = Box.createHorizontalGlue();
hbutton.add(hGlue1);
hbutton.add(button0);
hbutton.add(hStrut);
hbutton.add(button1);
hbutton.add(hGlue2);
//创建容器放在按钮下面
JPanel contentPanel = new JPanel();
Box vbox =Box.createVerticalBox();
vbox.add(hbutton);
//利用方法设置查询一个学生为默认页面
onePanel(contentPanel);
vbox.add(contentPanel);
jPaneInquire.add(vbox);
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//查询一个学生按钮,利用方法返回容器
onePanel(contentPanel);
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//查询全部学生按钮,利用方法返回容器
allPanel(contentPanel);
}
});
return jPaneInquire;
}
private static void onePanel(JPanel onePanel){
//查询一个学生的页面
//先创建输入查询学号的页面
JPanel jPanelText = new JPanel(new GridLayout(1,2,50,50));
jPanelText.setPreferredSize(new Dimension(500,40));
JLabel label = new JLabel("请输入您要查询的学生的学号");
label.setFont(new Font(null,Font.PLAIN,17));
jTextField = new JTextField(10);
jTextField.setFont(new Font(null,Font.PLAIN,15));
jPanelText.add(label);
jPanelText.add(jTextField);
Box hbutton = Box.createHorizontalBox();
JButton button0 = new JButton("确认");
button0.setPreferredSize(new Dimension(100,80));
JButton button1 = new JButton("清除");
button1.setPreferredSize(new Dimension(100,80));
//参考删除学生的页面
Component hStrut =Box.createHorizontalStrut(60);
Component hGlue1 = Box.createHorizontalGlue();
Component hGlue2 = Box.createHorizontalGlue();
hbutton.add(hGlue1);
hbutton.add(button0);
hbutton.add(hStrut);
hbutton.add(button1);
hbutton.add(hGlue2);
//创建查询信息页面
JPanel informationPanel = new JPanel();
Component vStrut1 = Box.createVerticalStrut(50);
Component vStrut2 = Box.createVerticalStrut(35);
Component vStrut3 = Box.createVerticalStrut(30);
Box vbox = Box.createVerticalBox();
vbox.add(vStrut1);
vbox.add(jPanelText);
vbox.add(vStrut2);
vbox.add(hbutton);
vbox.add(vStrut3);
vbox.add(informationPanel);
onePanel.removeAll();
onePanel.repaint();
onePanel.add(vbox);
onePanel.revalidate();
//创建按钮事件用方法重构容器
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
oneSucceed(informationPanel);
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
oneClera(informationPanel);
}
});
}
public static void allPanel(JPanel allPanel){
try {
//链接数据库
Connection conn = Connect.getConnection();
Statement sta = conn.createStatement();
String sql = "select * from student";
ResultSet re = sta.executeQuery(sql);
int row = 0;
//获取数据库中表格的行数
while (re.next()){
row++;
}
//判断数据库中是否有数据
if(row==0){
JOptionPane.showMessageDialog(null,"对不起,数据库暂无任何信息","",JOptionPane.ERROR_MESSAGE);
}
//这里重新获取的一个数据,因为我用re.beforeFirst()方法就会报错,下面是报错信息
//Operation not allowed for a result set of type ResultSet.TYPE_FORWARD_ONLY.
//上网查说是因为一个re多次使用,所以重新获取一下
ResultSet res = sta.executeQuery(sql);
//创建一个动态二位数组,获取数据库信息,加入到JTable
String[] columnNames = {"学号","姓名","性别","年龄","地址"};
String[][] rowData = new String[row][];
//利用循环获取数据库数据并赋值
for (int i = 0; i < row; i++) {
//re.next()这个可以上网查一下,我的理解是指针指向下一行
res.next();
id = res.getString("id");
name = res.getString("name");
sex = res.getString("sex");
age = res.getString("age");
site = res.getString("site");
//给二维数组赋值
rowData[i] = new String[]{id,name,sex,age,site};
}
//创建表格
JTable table = new JTable(rowData,columnNames);
//设置表头字体
table.getTableHeader().setFont(new Font(null,Font.PLAIN,20));
//不可随意交换列
table.getTableHeader().setReorderingAllowed(false);
//不可修改表中数据
table.setEnabled(false);
//设置行高
table.setRowHeight(30);
table.setFont(new Font(null,Font.PLAIN,20));
// 先获取到某列
TableColumn tableColumn = table.getColumnModel().getColumn(4);
// 设置列的宽度、首选宽度、最小宽度、最大宽度
// tableColumn.setWidth(int width);
tableColumn.setPreferredWidth(150);
tableColumn.setMinWidth(100);
tableColumn.setMaxWidth(300);
//允许手动调整该列宽度
tableColumn.setResizable(true);
// table.setPreferredScrollableViewportSize(new Dimension(400, 300));
//由于此处是用JScrollPane容器,所以表头会自动加,如果是普通容器,表头和表体需要分开加。
JScrollPane jScrollPanel = new JScrollPane(table);
JPanel jPanel = new JPanel();
jPanel.add(jScrollPanel);
//重新构建容器,这是为了防止连续查询
allPanel.removeAll();
allPanel.repaint();
allPanel.add(jPanel);
allPanel.revalidate();
re.close();
res.close();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void oneSucceed(JPanel jPanel){
id = jTextField.getText();
String sql;
try {
//连接数据库
Connection conn = Connect.getConnection();
Statement sta = conn.createStatement();
sql = "select * from Student where id ='"+id+"'";
ResultSet re = sta.executeQuery(sql);
//判断输入是否为空
if (id.equals("")) {
JOptionPane.showMessageDialog(null,"学号不能为空!","",JOptionPane.ERROR_MESSAGE);
}
else {
//判断数据库中是否有数据
if (re.next()) {
//获取用户输入
name =re.getString("name");
sex = re.getString("sex");
age = re.getString("age");
site = re.getString("site");
//创建学生信息页面
JPanel informationPanel = new JPanel(new BorderLayout());
//创建数组存放信息
String[] columnNames = {"学号","姓名","性别","年龄","地址"};
String[][] rowData = {{id,name,sex,age,site}};
//创建表格
JTable table = new JTable(rowData, columnNames);
table.getTableHeader().setFont(new Font(null,Font.PLAIN,20));
//不可交换列
table.getTableHeader().setReorderingAllowed(false);
//不可修改表格信息
table.setEnabled(false);
//设置行高
table.setRowHeight(30);
table.setFont(new Font(null,Font.PLAIN,20));
// 先获取到某列
TableColumn tableColumn = table.getColumnModel().getColumn(4);
// 设置列的宽度、首选宽度、最小宽度、最大宽度
// tableColumn.setWidth(int width);
tableColumn.setPreferredWidth(150);
tableColumn.setMinWidth(100);
tableColumn.setMaxWidth(300);
//允许手动调整该列宽度
tableColumn.setResizable(true);
// 把 表头 添加到容器顶部(使用普通的中间容器添加表格时,表头 和 内容 需要分开添加)
informationPanel.add(table.getTableHeader(), BorderLayout.NORTH);
// 把 表格内容 添加到容器中心
informationPanel.add(table, BorderLayout.CENTER);
// informationPanel.setPreferredSize(new Dimension(600,100));
//重新构建容器,这是为了防止连续查询
jPanel.removeAll();
jPanel.repaint();
jPanel.add(informationPanel);
jPanel.revalidate();
} else {
JOptionPane.showMessageDialog(null, "查无此人!", "", JOptionPane.ERROR_MESSAGE);
}
}
re.close();
sta.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void oneClera(JPanel jPanel) {
//刷新页面
jTextField.setText("");
jPanel.removeAll();
jPanel.repaint();
}
}
Connect
package Manager;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/**
* 提供数据库连接操作的工具类
*/
public class Connect {
public static Connection getConnection() throws Exception {
//1. 加载配置文件
Properties pros = new Properties();
InputStream rs = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
pros.load(rs);
//2. 获取连接所需的四个基本信息
String driverClass = pros.getProperty("driverClass");
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
//3. 加载驱动
Class.forName(driverClass);
//4. 获取连接
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
}
部分效果图
总结
以上就是全部内容,写的不好希望能指正。