12.2.2.9.1 EditComponent类
package component; import javabean.Student; import ui.MainFrame; import utils.StringUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class EditComponent extends JPanel { private JFrame jf; private JLabel nameLabel; private JLabel stuIdLabel; private JLabel majorLabel; private JLabel classNumLabel; private JLabel avgScoreLabel; private JTextField nameField; private JTextField stuIdField; private JTextField majorField; private JTextField classNumField; private JTextField avgScoreField; private JButton addButton; private JButton delButton; private JButton updateButton; private JButton queryButton; boolean isQuery; private String oldStuId; public EditComponent(JFrame jf){ this.jf = jf; //修改布局方式,目的是让表格占满整个JPanel this.setLayout(new BorderLayout()); this.setBackground(new Color(213, 232, 212)); /* * 组装姓名 */ Box nameBox = Box.createHorizontalBox(); nameLabel = new JLabel("姓 名:"); nameLabel.setFont(new Font("宋体",Font.BOLD,30)); nameField = new JTextField(18); nameField.setFont(new Font("微软雅黑",Font.LAYOUT_NO_LIMIT_CONTEXT,18)); nameBox.add(nameLabel); nameBox.add(Box.createHorizontalStrut(10)); nameBox.add(nameField); /* * 组装学号 */ Box stuIdBox = Box.createHorizontalBox(); stuIdLabel = new JLabel("学 号:"); stuIdLabel.setFont(new Font("宋体",Font.BOLD,30)); stuIdField = new JTextField(18); stuIdField.setFont(new Font("微软雅黑",Font.LAYOUT_NO_LIMIT_CONTEXT,18)); stuIdBox.add(stuIdLabel); stuIdBox.add(Box.createHorizontalStrut(10)); stuIdBox.add(stuIdField); /* * 组装专业 */ Box majorBox = Box.createHorizontalBox(); majorLabel = new JLabel("专 业:"); majorLabel.setFont(new Font("宋体",Font.BOLD,30)); majorField = new JTextField(18); majorField.setFont(new Font("微软雅黑",Font.LAYOUT_NO_LIMIT_CONTEXT,18)); majorBox.add(majorLabel); majorBox.add(Box.createHorizontalStrut(10)); majorBox.add(majorField); /* * 组装班级 */ Box classNumBox = Box.createHorizontalBox(); classNumLabel = new JLabel("班 级:"); classNumLabel.setFont(new Font("宋体",Font.BOLD,30)); classNumField = new JTextField(18); classNumField.setFont(new Font("微软雅黑",Font.LAYOUT_NO_LIMIT_CONTEXT,18)); classNumBox.add(classNumLabel); classNumBox.add(Box.createHorizontalStrut(10)); classNumBox.add(classNumField); /* * 组装平均成绩 */ Box avgScoreBox = Box.createHorizontalBox(); avgScoreLabel = new JLabel("平均成绩:"); avgScoreLabel.setFont(new Font("宋体",Font.BOLD,28)); avgScoreField = new JTextField(10); avgScoreField.setFont(new Font("微软雅黑",Font.LAYOUT_NO_LIMIT_CONTEXT,18)); avgScoreBox.add(avgScoreLabel); avgScoreBox.add(Box.createHorizontalStrut(7)); avgScoreBox.add(avgScoreField); /* 组装左侧 */ Box leftBox = Box.createVerticalBox(); leftBox.add(Box.createVerticalStrut(60)); leftBox.add(nameBox); leftBox.add(Box.createVerticalStrut(25)); leftBox.add(stuIdBox); leftBox.add(Box.createVerticalStrut(25)); leftBox.add(majorBox); leftBox.add(Box.createVerticalStrut(25)); leftBox.add(classNumBox); leftBox.add(Box.createVerticalStrut(25)); leftBox.add(avgScoreBox); /* 组装右侧 */ Box rightBox = Box.createVerticalBox(); addButton = new JButton("添加"); delButton = new JButton("删除"); updateButton = new JButton("修改"); queryButton = new JButton("查询"); //添加按钮增添监听事件 addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { isQuery = false; String name = nameField.getText().trim(); String stuId = stuIdField.getText().trim(); String major = majorField.getText().trim(); String classNum = classNumField.getText().trim(); String avgScore = avgScoreField.getText().trim(); //判断内容是否合理并不为空 if(!StringUtils.hasText(name)||!StringUtils.hasText(stuId)||!StringUtils.hasText(major)|| !StringUtils.hasText(classNum)||!StringUtils.hasText(avgScore)){ JOptionPane.showMessageDialog(jf,"您有空内容或不合理内容,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } Integer stuIdParse = null; Integer classNumParse = null; Double avgScoreParse = null; try { stuIdParse = Integer.parseInt(stuId); if(stuIdParse<20000000){ JOptionPane.showMessageDialog(jf,"添加失败,错误的学号信息","提醒",JOptionPane.WARNING_MESSAGE); return; } classNumParse = Integer.parseInt(classNum); if(classNumParse<1){ JOptionPane.showMessageDialog(jf,"添加失败,错误的班级信息","提醒",JOptionPane.WARNING_MESSAGE); return; } avgScoreParse = Double.parseDouble(avgScore); if(avgScoreParse<0||avgScoreParse>100){ JOptionPane.showMessageDialog(jf,"添加失败,成绩应在0~100之间","提醒",JOptionPane.WARNING_MESSAGE); return; } Student student = MainFrame.studentService.queryByStuId(stuIdParse); if(student!=null){ //说明该学号已经存在了 JOptionPane.showMessageDialog(jf,"添加失败,学号 "+stuIdParse+" 已存在","提醒",JOptionPane.WARNING_MESSAGE); return; } } catch (Exception ex) { JOptionPane.showMessageDialog(jf,"您有空内容或不合理内容,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } try { MainFrame.studentService.add(name,stuIdParse,major,classNumParse,avgScoreParse); JOptionPane.showMessageDialog(jf,"添加成功","提醒",JOptionPane.INFORMATION_MESSAGE); clearTextField(); } catch (Exception ex) { JOptionPane.showMessageDialog(jf,ex.getMessage(),"错误",JOptionPane.ERROR_MESSAGE); } } }); //修改按钮增添监听事件 updateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!isQuery){ JOptionPane.showMessageDialog(jf,"请先查询到该学号原信息再进行修改操作","提醒",JOptionPane.WARNING_MESSAGE); return; } if(!stuIdField.getText().equals(oldStuId)){ JOptionPane.showMessageDialog(jf,"学号不可修改或请先查询到该学号原信息再进行修改操作","提醒",JOptionPane.WARNING_MESSAGE); isQuery = false; return; } String name = nameField.getText().trim(); String stuId = stuIdField.getText().trim(); String major = majorField.getText().trim(); String classNum = classNumField.getText().trim(); String avgScore = avgScoreField.getText().trim(); //判断内容是否合理并不为空 if(!StringUtils.hasText(name)||!StringUtils.hasText(stuId)||!StringUtils.hasText(major)|| !StringUtils.hasText(classNum)||!StringUtils.hasText(avgScore)){ JOptionPane.showMessageDialog(jf,"您有空内容或不合理内容,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } Integer stuIdParse = null; Integer classNumParse = null; Double avgScoreParse = null; try { stuIdParse = Integer.parseInt(stuId); if(stuIdParse<20000000){ JOptionPane.showMessageDialog(jf,"修改失败,错误的学号信息","提醒",JOptionPane.WARNING_MESSAGE); return; } classNumParse = Integer.parseInt(classNum); if(classNumParse<1){ JOptionPane.showMessageDialog(jf,"修改失败,错误的班级信息","提醒",JOptionPane.WARNING_MESSAGE); return; } avgScoreParse = Double.parseDouble(avgScore); if(avgScoreParse<0||avgScoreParse>100){ JOptionPane.showMessageDialog(jf,"修改失败,成绩应在0~100之间","提醒",JOptionPane.WARNING_MESSAGE); return; } Student student = MainFrame.studentService.queryByStuId(stuIdParse); if(student==null){ //说明该学号不存在 JOptionPane.showMessageDialog(jf,"修改失败,学号 "+stuIdParse+" 不存在","提醒",JOptionPane.WARNING_MESSAGE); return; } } catch (Exception ex) { JOptionPane.showMessageDialog(jf,"您有空内容或不合理内容,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } try { MainFrame.studentService.updateByStuId(name,stuIdParse,major,classNumParse,avgScoreParse); JOptionPane.showMessageDialog(jf,"修改成功","提醒",JOptionPane.INFORMATION_MESSAGE); clearTextField(); isQuery = false; } catch (Exception ex) { JOptionPane.showMessageDialog(jf,ex.getMessage(),"错误",JOptionPane.ERROR_MESSAGE); } } }); //删除按钮增添监听事件 delButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String stuId = stuIdField.getText().trim(); if(!StringUtils.hasText(stuId)){ JOptionPane.showMessageDialog(jf,"空或不合理的学号,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } Integer stuIdParse = null; try { stuIdParse = Integer.parseInt(stuId); if(stuIdParse<20000000){ throw new RuntimeException(); } } catch (Exception ex) { JOptionPane.showMessageDialog(jf,"空或不合理的学号,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } try { Student student = MainFrame.studentService.queryByStuId(stuIdParse); if(student==null){ JOptionPane.showMessageDialog(jf,"该学号信息不存在","提醒",JOptionPane.WARNING_MESSAGE); return; } int option = JOptionPane.showConfirmDialog(jf, "您确定删除学号为 " + stuId + " 的数据信息吗", "确定栏", JOptionPane.YES_NO_OPTION); if(option==JOptionPane.YES_OPTION){ MainFrame.studentService.delByStuId(stuIdParse); JOptionPane.showMessageDialog(jf,"删除成功","提醒",JOptionPane.INFORMATION_MESSAGE); clearTextField(); isQuery = false; } } catch (Exception ex) { JOptionPane.showMessageDialog(jf,ex.getMessage(),"错误",JOptionPane.ERROR_MESSAGE); } } }); //查询按钮增添监听事件 queryButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String stuId = stuIdField.getText().trim(); if(!StringUtils.hasText(stuId)){ JOptionPane.showMessageDialog(jf,"空或不合理的学号,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } Integer stuIdParse = null; try { stuIdParse = Integer.parseInt(stuId); if(stuIdParse<20000000){ throw new RuntimeException(); } } catch (Exception ex) { JOptionPane.showMessageDialog(jf,"空或不合理的学号,请修改","提醒",JOptionPane.WARNING_MESSAGE); return; } try { Student student = MainFrame.studentService.queryByStuId(stuIdParse); if(student==null){ JOptionPane.showMessageDialog(jf,"该学号信息不存在","提醒",JOptionPane.WARNING_MESSAGE); return; } nameField.setText(student.getName()); classNumField.setText(student.getClassNum()+""); stuIdField.setText(student.getStuId()+""); majorField.setText(student.getMajor()); avgScoreField.setText(student.getAvgScore()+""); } catch (Exception ex) { JOptionPane.showMessageDialog(jf,ex.getMessage(),"错误",JOptionPane.ERROR_MESSAGE); return; } //表明已查询到 isQuery = true; oldStuId = stuIdField.getText(); } }); rightBox.add(Box.createVerticalStrut(72)); rightBox.add(addButton); rightBox.add(Box.createVerticalStrut(60)); rightBox.add(delButton); rightBox.add(Box.createVerticalStrut(60)); rightBox.add(updateButton); rightBox.add(Box.createVerticalStrut(60)); rightBox.add(queryButton); /* 组装全部 */ Box allBox = Box.createHorizontalBox(); allBox.add(leftBox); allBox.add(Box.createHorizontalStrut(100)); allBox.add(rightBox); Panel mainPanel = new Panel(); mainPanel.add(allBox); this.add(mainPanel); } /** * 清空文本域内容 */ public void clearTextField(){ nameField.setText(""); classNumField.setText(""); stuIdField.setText(""); majorField.setText(""); avgScoreField.setText(""); } }
12.2.2.9.2 ScoreComponent类
package component; import javabean.Student; import ui.MainFrame; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableModel; import java.awt.*; import java.util.*; import java.util.List; public class ScoreComponent extends JPanel { private JTable jTable; private Vector<String> titles = new Vector<>(Arrays.asList("学号", "姓名", "专业", "班级", "平均成绩")); private Vector<Vector> tableData; private TableModel tableModel; private JFrame jf; // 设置表格间隔色 MyDefaultTableCellRenderer ter = new MyDefaultTableCellRenderer(); public ScoreComponent(JFrame jf) { this.jf = jf; //修改布局方式,目的是让表格占满整个JPanel this.setLayout(new BorderLayout()); tableData = new Vector<>(); tableModel = new DefaultTableModel(tableData, this.titles); jTable = new JTable(tableModel) { @Override public boolean isCellEditable(int row, int column) { //设置为均不可直接修改 return false; } }; requestData(); //颜色渲染 for (int i = 0; i < this.titles.size(); i++) { jTable.getColumn(this.titles.get(i)).setCellRenderer(ter); } //设置只能选中一行 //jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); /* 美化表头 */ JTableHeader header = jTable.getTableHeader(); //表头的高 header.setPreferredSize(new Dimension(1, 50)); //表头的背景颜色 header.setBackground(new Color(229,239,255)); //设置表头字体 header.setFont(new Font("STLiti", Font.BOLD, 20)); //设置字体 jTable.setFont(new Font("STHeiti", Font.PLAIN, 20)); //设置行高 jTable.setRowHeight(30); //支持滚动条浏览表格 JScrollPane jScrollPane = new JScrollPane(jTable); jScrollPane.getVerticalScrollBar().setUI(new NewScrollBarUI()); this.add(jScrollPane); } public void requestData() { List<Student> students = null; try { students = MainFrame.studentService.queryByScoreDesc(); } catch (Exception e) { JOptionPane.showMessageDialog(jf,"网络连接超时,无法获取新数据,请稍后再试","提示",JOptionPane.ERROR_MESSAGE); return; } //清空tableData的数据 tableData.clear(); for (Student student : students) { Vector vector = new Vector(); vector.add(student.getStuId()); vector.add(student.getName()); vector.add(student.getMajor()); vector.add(student.getClassNum()); vector.add(student.getAvgScore()); tableData.add(vector); } jTable.updateUI(); } class MyDefaultTableCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS); if (row % 2 == 0) { setBackground(Color.pink); } else if (row % 2 == 1) { setBackground(Color.white); } return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); } } }
12.2.2.9.3 NewScrollBarUI类
package component; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JScrollBar; import javax.swing.plaf.basic.BasicScrollBarUI; /** * 自定义滚动条UI */ public class NewScrollBarUI extends BasicScrollBarUI { @Override protected void configureScrollBarColors() { // 把手 // thumbColor = Color.GRAY; // thumbHighlightColor = Color.BLUE; // thumbDarkShadowColor = Color.BLACK; // thumbLightShadowColor = Color.YELLOW; // 滑道 if (this.scrollbar.getOrientation() == JScrollBar.VERTICAL) { trackColor = Color.black; setThumbBounds(0, 0, 3, 10); } if (this.scrollbar.getOrientation() == JScrollBar.HORIZONTAL) { trackColor = Color.black; setThumbBounds(0, 0, 10, 3); } // trackHighlightColor = Color.GREEN; } /** * 设置滚动条的宽度 */ @Override public Dimension getPreferredSize(JComponent c) { // TODO Auto-generated method stub if (this.scrollbar.getOrientation() == JScrollBar.VERTICAL) { c.setPreferredSize(new Dimension(10, 0)); } if (this.scrollbar.getOrientation() == JScrollBar.HORIZONTAL) { c.setPreferredSize(new Dimension(0, 6)); } return super.getPreferredSize(c); } // 重绘滑块的滑动区域背景 public void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { Graphics2D g2 = (Graphics2D) g; GradientPaint gp = null; //判断滚动条是垂直的 还是水平的 if (this.scrollbar.getOrientation() == JScrollBar.VERTICAL) { //设置画笔 gp = new GradientPaint(0, 0, Color.decode("#ede95f"), trackBounds.width, 0, Color.decode("#ff0000")); } if (this.scrollbar.getOrientation() == JScrollBar.HORIZONTAL) { /*gp = new GradientPaint(0, 0, new Color(80, 80, 80), trackBounds.height, 0, new Color(80, 80, 80));*/ gp = new GradientPaint(0, 0, Color.decode("#007C8E"), trackBounds.width, 0, Color.decode("#007C8E")); } g2.setPaint(gp); //填充Track g2.fillRect(trackBounds.x, trackBounds.y, trackBounds.width, trackBounds.height); //绘制Track的边框 /* g2.setColor(new Color(175, 155, 95)); g2.drawRect(trackBounds.x, trackBounds.y, trackBounds.width - 1, trackBounds.height - 1); */ if(trackHighlight == BasicScrollBarUI.DECREASE_HIGHLIGHT) { this.paintDecreaseHighlight(g); } if(trackHighlight == BasicScrollBarUI.INCREASE_HIGHLIGHT) { this.paintIncreaseHighlight(g); } } @Override protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) { // 把绘制区的x,y点坐标定义为坐标系的原点 // 这句一定一定要加上啊,不然拖动就失效了 g.translate(thumbBounds.x, thumbBounds.y); // 设置把手颜色 g.setColor(Color.decode("#4507ff")); // 画一个圆角矩形 // 这里面前四个参数就不多讲了,坐标和宽高 // 后两个参数需要注意一下,是用来控制角落的圆角弧度 // g.drawRoundRect(0, 0, 5, thumbBounds.height - 1, 5, 5); // 消除锯齿 Graphics2D g2 = (Graphics2D) g; RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.addRenderingHints(rh); // 半透明 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f)); // 设置填充颜色,这里设置了渐变,由下往上 // g2.setPaint(new GradientPaint(c.getWidth() / 2, 1, Color.GRAY, // c.getWidth() / 2, c.getHeight(), Color.GRAY)); // 填充圆角矩形 if (this.scrollbar.getOrientation() == JScrollBar.VERTICAL) { g2.fillRoundRect(0, 0, 40, thumbBounds.height - 1, 5, 5); } if (this.scrollbar.getOrientation() == JScrollBar.HORIZONTAL) { g2.fillRoundRect(0, 0, thumbBounds.width - 1, 40, 5, 5); } } /** * 创建滚动条上方的按钮 */ @Override protected JButton createIncreaseButton(int orientation) { JButton button = new JButton(); button.setBorderPainted(false); button.setContentAreaFilled(false); button.setBorder(null); return button; } /** * 创建滚动条下方的按钮 */ @Override protected JButton createDecreaseButton(int orientation) { JButton button = new JButton(); button.setBorderPainted(false); button.setContentAreaFilled(false); button.setFocusable(false); button.setBorder(null); return button; } }
12.2.2.10 src下创建ui文件夹并在src下创建类
MainFrame:
package ui; import component.EditComponent; import component.ScoreComponent; import service.impl.StudentServiceImpl; import service.StudentService; import utils.ScreenUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * 主界面 */ public class MainFrame { public static StudentService studentService = new StudentServiceImpl(); JFrame jf = new JFrame("学生成绩管理系统"); /** * 定义窗口的宽度 */ final int WIDTH = 700; /** * 定义窗口的高度 */ final int HEIGHT = 500; /** * 创建工具条 */ JToolBar jToolBar; JButton showButton; JButton editButton; JPanel mainPanel; /** * 当前是成绩模块还是编辑模块 */ String module = "学生成绩"; /** * 默认是成绩模块 */ ScoreComponent scoreComponent; EditComponent editComponent; public void init(){ //设置关闭窗口为结束程序 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置窗口相关的属性 jf.setBounds((ScreenUtils.getScreenWidth() - WIDTH) / 2, (ScreenUtils.getScreenHeight() - HEIGHT) / 2, WIDTH, HEIGHT); //设置窗口大小不可变 jf.setResizable(false); /* * 组装工具条 */ jToolBar = new JToolBar(); showButton = new JButton("学生成绩"); editButton = new JButton("编辑"); //对 点击 学生成绩按钮 的处理 --> 刷新数据 showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals(module)){ //说明原本就是在学生成绩模块 //那么只需要重新获取数据 scoreComponent.requestData(); }else{ //修改 module module = "学生成绩"; //去除editComponent mainPanel.remove(editComponent); //加入scoreComponent mainPanel.add(scoreComponent); scoreComponent.requestData(); //刷新页面,重绘面板 mainPanel.repaint(); // //使重绘的面板确认生效 mainPanel.validate(); } } }); //对 点击 编辑模块 的处理 editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (!module.equals("编辑")) { //修改 module module = "编辑"; //移除面板中的组件 mainPanel.remove(scoreComponent); //添加要切换的面板 mainPanel.add(editComponent); //刷新页面,重绘面板 mainPanel.repaint(); //使重绘的面板确认生效 mainPanel.validate(); } } }); jToolBar.add(showButton); jToolBar.addSeparator(); jToolBar.add(editButton); //设置工具条背景颜色 jToolBar.setBackground(new Color(197,255,103)); //向窗口中添加工具条 jf.add(jToolBar, BorderLayout.NORTH); scoreComponent = new ScoreComponent(jf); editComponent = new EditComponent(jf); mainPanel = new JPanel(new BorderLayout()); //默认是成绩面板 mainPanel.add(scoreComponent); jf.add(mainPanel); jf.setVisible(true); } }
12.2.2.11 src下创建主启动类
StudentManageApplication类:
import ui.MainFrame; /** * 主启动类 */ public class StudentManageApplication { public static void main(String[] args) { new MainFrame().init(); } }
12.2.2.12 注意事项与细节说明
- 在运行主启动类StudentManageApplication需要确保开启了MySQL服务:
win+R
输入services.msc
查看: - 如何查看自己的MySQL版本:
mysqld --version