因为代码较多,如果有需要可以找我拿压缩包,我会将全部(包括图片)打包送你哦
//引包
import javax.swing.*;
import pane._7_UserPane;
import view._1_LoginFrame;
import view._2_MainFrame;
public class MainText {
public static void main(String[] args) {
new _1_LoginFrame();
}
}
package view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import dao.UserDao;
import vo.User;
import java.sql.*;//操作数据库
//窗体的默认布局是边界布局管理器
//面板的默认布局是流式布局管理器
public class _1_LoginFrame extends JFrame implements ActionListener{//将整个类作为监听器
//面板
JPanel jp1,jp2,jp3;
//标签
JLabel labimg,labusr,labpwd,labrole;
//文本框
JTextField jtf;
//密码框
JPasswordField jpf;
//按钮
JButton btnlog,btnclear;
//复选按钮
JRadioButton jrblog,jrbshouyin;
public _1_LoginFrame() {
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
//设置收银系统登录页面的上面的图片---------(图片添加到标签上进行插入)
labimg = new JLabel();
labimg.setIcon(new ImageIcon("src/images/top.jpg"));
labimg.setPreferredSize(new Dimension(536,148));//设置图片的大小
labusr = new JLabel("用户名");
labpwd = new JLabel("密码");
labrole = new JLabel("角色");
jtf = new JTextField(12);
jpf = new JPasswordField(12);
btnlog = new JButton("登录");
btnlog.addActionListener(this);
btnclear = new JButton("取消");
btnclear.addActionListener(this);
jrblog = new JRadioButton("管理员",true);//true表示按钮一出现就会被选中
jrbshouyin = new JRadioButton("收银员");
jp1.add(labimg);
add(jp1,"North");
//jp2的面板设置为空(面板设置为空的话,就可以自定义面板的布局,根据设定的位置进行设置布局)
jp2.setLayout(null);
labusr.setBounds(71, 17, 53, 27);//用户名
labpwd.setBounds(71, 56, 48, 23);//密码
jtf.setBounds(156, 20, 145, 22);//文本框
jpf.setBounds(156, 57, 145, 24);//密码框
labrole.setBounds(71, 85, 53, 38);//角色
jrblog.setBounds(155, 96, 79, 21);//管理员
jrbshouyin.setBounds(251, 96, 75, 17);//收银员
//将组件添加到jp2面板上
jp2.add(labusr);
jp2.add(labpwd);
jp2.add(jtf);
jp2.add(labpwd);
jp2.add(jpf);
jp2.add(labrole);
jp2.add(jrblog);
jp2.add(jrbshouyin);
//将jp2面板添加到窗体上,并设置为中心
add(jp2,"Center");
jp3.add(btnlog);
jp3.add(btnclear);
add(jp3,"South");
//设置不允许改变窗口的大小
this.setResizable(false);
this.setBounds(300, 200, 480, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//1.获取用户的输入
String id = jtf.getText();
String pwd = new String(jpf.getPassword());
if(e.getSource() == btnlog) {
/*
//2.连接数据库
Connection conn = DBUtil.open();
//3.查询数据库的信息
String sql = "select * from user where id = ? and pwd = ? ";
PreparedStatement psmt = conn.prepareStatement(sql);
psmt.setString(1, id);
psmt.setString(2, pwd);
ResultSet rs = psmt.executeQuery();
if(rs.next())
JOptionPane.showMessageDialog(null, "登录成功");
else
JOptionPane.showMessageDialog(null, "登录失败");
*/
//2.调用方法,查询数据
UserDao ud = new UserDao();
User u = ud.findById(id);
if(u!=null) {
if(pwd.equals(u.getPwd())) {
this.dispose();
new _2_MainFrame();
JOptionPane.showMessageDialog(null, "登录成功");
}else
JOptionPane.showMessageDialog(null, "密码错误");
}else
JOptionPane.showMessageDialog(null, "用户名错误");
}
if(e.getSource()==btnclear) {
jtf.setText("");
jpf.setText("");
jtf.requestFocusInWindow();
}
}
}
package view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//引包
import pane._0_MainPane;
import pane._2_CashierPane;
import pane._6_MemberPane;
import pane._7_UserPane;
import tools.ShowTime;
public class _2_MainFrame extends JFrame implements ActionListener{
//面板
JPanel jpnor,jpsou,jpcen,jpwest;//分别为上,下,中,左
//标签
JLabel labup,labcen,labwel,labtime,labadmin;
//按钮
JButton btn1, btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9;
//将创建的卡片对象写在构造方法的外面,这样下面超出方法的 actionPerformed方法就可以正常识别
CardLayout card = new CardLayout();
public _2_MainFrame() {
//创建面板
jpnor = new JPanel();
jpsou = new JPanel();
jpcen = new JPanel();
jpwest = new JPanel();
//创建标签
labup = new JLabel(new ImageIcon("src/images/banner.jpg"));
labcen = new JLabel();
labwel = new JLabel("欢迎光临超市收银系统");
labtime = new JLabel();
labadmin = new JLabel("管理员");
ShowTime st = new ShowTime();
labtime = st.getTimeLabel();
btn1 = new JButton(new ImageIcon("src/images/1.jpg"));
btn2 = new JButton(new ImageIcon("src/images/2.jpg"));
btn3 = new JButton(new ImageIcon("src/images/3.jpg"));
btn3.addActionListener(this);
btn4 = new JButton(new ImageIcon("src/images/4.jpg"));
btn5 = new JButton(new ImageIcon("src/images/5.jpg"));
btn6 = new JButton(new ImageIcon("src/images/6.jpg"));
btn6.addActionListener(this);
btn7 = new JButton(new ImageIcon("src/images/7.jpg"));
btn7.addActionListener(this);
btn8 = new JButton(new ImageIcon("src/images/8.jpg"));
btn9 = new JButton(new ImageIcon("src/images/9.jpg"));
jpnor.add(labup);
add(jpnor,"North");
//设置jpwest面板的布局是网格布局
jpwest.setLayout(new GridLayout(9,1));
jpwest.add(btn1);
jpwest.add(btn2);
jpwest.add(btn3);
jpwest.add(btn4);
jpwest.add(btn5);
jpwest.add(btn6);
jpwest.add(btn7);
jpwest.add(btn8);
jpwest.add(btn9);
add(jpwest,"West");
//设置jpcen的布局为卡片布局
// jpcen.setLayout(new CardLayout());
jpcen.setLayout(card);
_0_MainPane mp = new _0_MainPane();
jpcen.add("main",mp);
add(jpcen,"Center");
_6_MemberPane mmp = new _6_MemberPane();
jpcen.add(mmp,"member");
_2_CashierPane gp = new _2_CashierPane();
jpcen.add(gp,"goods");
_7_UserPane up = new _7_UserPane();
jpcen.add(up,"user");//user为卡片的名称
//设置jpsou的布局为网格布局,并添加组件
jpsou.setLayout(new GridLayout(1,3));
jpsou.add(labwel);
jpsou.add(labtime);
jpsou.add(labadmin);
add(jpsou,"South");
this.setResizable(false);//禁止改变窗口大小
this.setBounds(300, 200, 850, 650);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn3) {
card.show(jpcen,"goods");
}
if(e.getSource()==btn6) {
card.show(jpcen,"member");
}
if(e.getSource()==btn7) {
card.show(jpcen,"user");
}
}
}
package pane;
import javax.swing.*;
public class _0_MainPane extends JPanel{
public _0_MainPane(){
JLabel lab = new JLabel(new ImageIcon(("src/images/guanyu.jpg")));
add(lab);
}
}
package pane;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.DefaultTableModel;
import service.UserService;
import vo.User;
public class _7_UserPane extends JPanel implements ActionListener{//类实现监听
//创建标签 (输入,用户名,密码,姓名,角色)
JLabel labin,labid,labpwd,labxm,labrole;
//文本框 (输入,用户名,姓名)
JTextField jtfin,jtfid,jtfxm;
//密码框
JPasswordField jpf;
//组合框
JComboBox jcb;
//按钮 (查找,添加,删除,修改,清除)
JButton btnfind,btnadd,btndel,btnupdate,btnclear;
//面板
JPanel jpleft,jpright,jpnor,jpcen,jpdown,jpone,jptwo,jpthree,jpfour,jpfive,jpsix;
//组件
JTable table;
JScrollPane jsp;
DefaultTableModel dtm;
String[] rolelist = {"管理员","收银员"};
User users ;
public _7_UserPane(){
labin = new JLabel("请输入账号或姓名");//----------------------------标签
labid = new JLabel("请输入用户名");
labpwd = new JLabel("请输入密码");
labxm = new JLabel("请输入姓名");
labrole = new JLabel("请输入角色");
jtfin = new JTextField(12);//--------------------------------文本框
jtfid = new JTextField(12);
jtfxm = new JTextField(12);
jpf = new JPasswordField(12);//------------------------------密码框
// String[] rolelist = {"管理员","收银员"};
jcb = new JComboBox<String>(rolelist);//-------------------------------------组合框
//设置组件的大小
jcb.setPreferredSize(new Dimension(135,22));
btnfind = new JButton("查询");//----------------------------按钮
btnfind.addActionListener(this);
btnadd = new JButton("添加");
btnadd.addActionListener(this);
btndel = new JButton("删除");
btndel.addActionListener(this);
btnupdate = new JButton("修改");
btnupdate.addActionListener(this);
btnclear = new JButton("清空");
btnclear.addActionListener(this);
jpleft = new JPanel();//-------------------------------------面板
jpright = new JPanel();
jpnor = new JPanel();
jpcen = new JPanel();
jpone = new JPanel();
jptwo = new JPanel();
jpthree = new JPanel();
jpfour = new JPanel();
jpfive = new JPanel();
jpsix = new JPanel();
//创建表格组件
//1.创建表格模型,在表格中使用模型保存数据
dtm = new DefaultTableModel();
//使用默认表格模型的方法添加列标题
dtm.addColumn("账号");
dtm.addColumn("密码");
dtm.addColumn("姓名");
dtm.addColumn("角色");
//创建表格,并添加到滚动面板中
table = new JTable(dtm);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//获取选中的行
int row = table.getSelectedRow();
//获取选中行的各列值
String id = (String) table.getValueAt(row, 0);
String pwd = (String) table.getValueAt(row, 1);
String uname = (String) table.getValueAt(row, 2);
String role = (String) table.getValueAt(row, 3);
//将各列值复制给右侧的文本框
jtfid.setText(id);
jpf.setText(pwd);
jtfxm.setText(uname);
jcb.setSelectedItem(role);
users = new User(id,pwd,uname,role);
}
});
jsp = new JScrollPane(table);
// jpdown = new JPanel();
// jpdown.add(jsp);
jpcen.add(jsp);
TitledBorder tb1 = BorderFactory.createTitledBorder("用户信息");
TitledBorder tb2 = BorderFactory.createTitledBorder("资料维护");
//把组件添加到面板
jpnor.add(labin);
jpnor.add(jtfin);
jpnor.add(btnfind);
jpone.add(labid);
jpone.add(jtfid);
jptwo.add(labpwd);
jptwo.add(jpf);
jpthree.add(labxm);
jpthree.add(jtfxm);
jpfour.add(labrole);
jpfour.add(jcb);
jpfive.add(btnadd);
jpfive.add(btnupdate);
jpsix.add(btndel);
jpsix.add(btnclear);
//设置布局
jpleft.setLayout(new BorderLayout());
jpright.setLayout(new GridLayout(6,2));
this.setLayout(new BorderLayout());
//把子面板添加到主面板(左右面板)上
jpleft.add(jpnor,"North");
jpleft.add(jpcen,"Center");
jpright.add(jpone);
jpright.add(jptwo);
jpright.add(jpthree);
jpright.add(jpfour);
jpright.add(jpfive);
jpright.add(jpsix);
//把左右面板添加到主面板
this.add(jpleft,"Center");
this.add(jpright,"East");
//给左右面板加边框
jpleft.setBorder(tb1);
jpright.setBorder(tb2);
}
UserService us = new UserService();
@Override
public void actionPerformed(ActionEvent e) {
// 查找用户
if(e.getSource() == btnfind) {
/* Vector> vv = new Vector>();
String str = jtfin.getText().trim();
if(str.equals("")) {
vv = us.find();//查找所有的记录
}else {
vv = us.find(str);
}
//在显示表之前,把原来的表中的记录清空
int row = dtm.getRowCount();//原本存在记录的行数
for(int i = 0 ; i< row ; i++) {
//每次都删除第一行(因为删除了第一行,下面的行又跑到了第一行,所以每次都删除第一行)
dtm.removeRow(0);
}
for(int i=0 ; i v = vv.get(i);//查找第几行,数字从0开始,即(0为第一行)
dtm.addRow(v);
} */
showData();
}
//添加用户
if(e.getSource() == btnadd) {
String uid = jtfid.getText();
String pwd = new String(jpf.getPassword());
String uname = jtfxm.getText();
String role = (String) jcb.getSelectedItem();//将OBject强转为String
User u = new User(uid,pwd,uname,role);
boolean b =us.addUser(u);
if(b==true) {
JOptionPane.showMessageDialog(null, "添加成功");
showData();
}else
JOptionPane.showMessageDialog(null, "账号重复,添加失败");
}
//删除用户
if(e.getSource() == btndel) {
String uid = jtfid.getText();
boolean b = us.delUser(uid);
if(b==true) {
JOptionPane.showMessageDialog(null, "删除成功");
showData();
}else
JOptionPane.showMessageDialog(null, "账号不存在,删除失败");
}
/* //修改用户(先删除再添加的方法)
if(e.getSource() == btnupdate) {
String uid = jtfid.getText();
String pwd = new String(jpf.getPassword());
String uname = jtfxm.getText();
String role = (String) jcb.getSelectedItem();//将OBject强转为String
User u = new User(uid,pwd,uname,role);
int b = us.updateUser(uid, u);
if(b==1)
JOptionPane.showMessageDialog(null, "未查找到该账号,无法修改");
else if(b==3){
JOptionPane.showMessageDialog(null, "修改成功");
showData();
}
}
//修改用户(直接修改的方法)
if(e.getSource() == btnupdate) {
String uid = jtfid.getText();
String pwd = new String(jpf.getPassword());
String uname = jtfxm.getText();
String role = (String) jcb.getSelectedItem();//将OBject强转为String
User u = new User(uid,pwd,uname,role);
boolean b = us.updateUser(uid, u);
if(b==false)
JOptionPane.showMessageDialog(null, "未查找到该账号,无法修改");
else if(b==true) {
JOptionPane.showMessageDialog(null, "修改成功");
showData();
}
} */
//修改用户
if(e.getSource() == btnupdate) {
String uid = jtfid.getText();
String pwd = new String(jpf.getPassword());
String uname = jtfxm.getText();
String role = (String) jcb.getSelectedItem();//将OBject强转为String
User u = new User(uid,pwd,uname,role);
boolean b = us.updateUser(uid,users, u);
if(b==true) {
JOptionPane.showMessageDialog(null, "修改成功");
showData();
}else
JOptionPane.showMessageDialog(null, "已存在该账号,无法修改为相同的账号");
}
//清空文本框
if(e.getSource()==btnclear) {
jtfin.setText("");
jtfid.setText("");
jtfxm.setText("");
jpf.setText("");
}
//清空所有用户的信息
/* if(e.getSource()==btnclear) {
boolean b = us.clearUser();
if(b) {
JOptionPane.showMessageDialog(null, "清空成功");
showData();
}
else
JOptionPane.showMessageDialog(null, "内容为空,无法清除");
} */
}
public void showData() {
Vector<Vector<String>> vv = new Vector<Vector<String>>();
String str = jtfin.getText().trim();//trim()方法是用来删除前后多余的空格的
if(str.equals("")) {
vv = us.find();//查找所有的记录
}else {
vv = us.find(str);
}
//在显示表之前,把原来的表中的记录清空
int row = dtm.getRowCount();//原本存在记录的行数
for(int i = 0 ; i< row ; i++) {
//每次都删除第一行(因为删除了第一行,下面的行又跑到了第一行,所以每次都删除第一行)
dtm.removeRow(0);
}
for(int i=0 ; i <vv.size() ;i++) {
Vector<String> v = vv.get(i);//查找第几行,数字从0开始,即(0为第一行)
dtm.addRow(v);
}
}
}
package pane;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import service.MemberService;
import tools.DatePicker;
import vo.Member;
public class _6_MemberPane extends JPanel implements ActionListener{
//标签 (查询 ,卡号 ,姓名 ,电话 ,生日 ,积分 ,余额, 兑换 ,充值)
JLabel labfind,labcard,labname,labphone,labbirth,labjifen,labmoney,labchange,labaddmoney;
//文本框 (查询 ,卡号 ,姓名 ,电话 ,生日 ,积分 ,余额 ,充值)
JTextField jtffind,jtfcard,jtfname,jtfphone,jtfbirth,jtfjifen,jtfmoney,jtfaddmoney;
//按钮 (查询,添加会员,删除会员,修改会员,清空数据,兑换,充值)
JButton btnfind,btnadd,btndelete,btnupdate,btnclear,btnchange,btnaddmoney;
//组合框
JComboBox jcbchange;
//面板 (上下2大面板 + 上面板的两个面板 + 下面板的两个面板 + 下面板的中面板的中面板与右面板)
JPanel jpup,jpdown,jpupnor,jpupcen,jpdowncen,jpdownsou,jpdowncencen,jpdownceneast;
//再设置六个面板,每一个面板上添加一个标签和与之对应的文本框
JPanel one,two,three,four,five,six;
//组件
JTable table;
JScrollPane jsp;
DefaultTableModel dtm;
String [] gift = {"保温杯","自动牙刷","帽子","一斤鸡蛋","袜子五双","蓝牙耳机","电动车"};
int [] giftChange = {50,20,15,25,15,50,800};
Member mber ;
public _6_MemberPane() {
// TODO Auto-generated constructor stub
labfind = new JLabel("会员卡号 / 姓名 / 电话");// ----------------------------标签
labcard = new JLabel("卡号 :");
labname = new JLabel("姓名 :");
labphone = new JLabel("电话 :");
labbirth = new JLabel("生日 :");
labjifen = new JLabel("积分数:");
labmoney = new JLabel("余额:");
labchange = new JLabel("兑换:");
labaddmoney = new JLabel("充值:");
jtffind = new JTextField(12);// --------------------------------文本框
jtfcard = new JTextField(10);
jtfname = new JTextField(10);
jtfphone = new JTextField(10);
jtfbirth = new JTextField();
jtfjifen = new JTextField(10);
jtfmoney = new JTextField(10);
jtfaddmoney = new JTextField(9);
//添加日期选择框
DatePicker datePicker = new DatePicker();
jtfbirth = datePicker;// 生日文本框
jtfbirth.setColumns(10);
btnfind = new JButton("查询");// ----------------------------按钮
btnfind.addActionListener(this);
btnadd = new JButton("添加会员");
btnadd.addActionListener(this);
btndelete = new JButton("删除会员");
btndelete.addActionListener(this);
btnupdate = new JButton("修改信息");
btnupdate.addActionListener(this);
btnclear = new JButton("清空数据");
btnclear.addActionListener(this);
btnchange = new JButton("兑换");
btnchange.addActionListener(this);
btnaddmoney = new JButton("充值");
btnaddmoney.addActionListener(this);
jcbchange = new JComboBox<String>(gift);// -------------------------------------组合框
jpup = new JPanel();// -------------------------------------面板
jpdown = new JPanel();
jpupnor = new JPanel();
jpupcen = new JPanel();
jpdowncen = new JPanel();
jpdownsou = new JPanel();
jpdowncencen = new JPanel();
jpdownceneast = new JPanel();
one = new JPanel();
two = new JPanel();
three = new JPanel();
four = new JPanel();
five = new JPanel();
six = new JPanel();
//创建表格组件
//1.创建表格模型,在表格中使用模型保存数据
dtm = new DefaultTableModel();
//使用默认表格模型的方法添加列标题
dtm.addColumn("卡号");
dtm.addColumn("姓名");
dtm.addColumn("电话");
dtm.addColumn("生日");
dtm.addColumn("积分");
dtm.addColumn("余额");
//创建表格,并添加到滚动面板中
table = new JTable(dtm);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
//获取选中的行
int row = table.getSelectedRow();
//获取选中行的各列值
String card = (String) table.getValueAt(row, 0);
String name = (String) table.getValueAt(row, 1);
String phone = (String) table.getValueAt(row, 2);
String birth = (String) table.getValueAt(row, 3);
String jifen = (String) table.getValueAt(row, 4);
String money = (String) table.getValueAt(row, 5);
//将各列值复制给右侧的文本框
jtfcard.setText(card);
jtfname.setText(name);
jtfphone.setText(phone);
jtfbirth.setText(birth);
jtfjifen.setText(jifen);
jtfmoney.setText(money);
mber = new Member(card,name,phone,birth,jifen,money);
}
});
jsp = new JScrollPane(table);
//设置布局
this.setLayout(new GridLayout(2,1));
jpup.setLayout(new BorderLayout());
jpdown.setLayout(new BorderLayout());
jpdowncen.setLayout(new BorderLayout());
jpdowncencen.setLayout(new GridLayout(3,2));
jpdownceneast.setLayout(new GridLayout(2,2));
//把组件添加到面板上
jpupnor.add(labfind);
jpupnor.add(jtffind);
jpupnor.add(btnfind);
jpupcen.add(jsp);// ---------对应代码的129行
one.add(labcard);
one.add(jtfcard);
two.add(labname);
two.add(jtfname);
three.add(labphone);
three.add(jtfphone);
four.add(labbirth);
four.add(jtfbirth);
five.add(labjifen);
five.add(jtfjifen);
six.add(labmoney);
six.add(jtfmoney);
jpdowncencen.add(one);
jpdowncencen.add(two);
jpdowncencen.add(three);
jpdowncencen.add(four);
jpdowncencen.add(five);
jpdowncencen.add(six);
jpdownceneast.add(btnadd);
jpdownceneast.add(btndelete);
jpdownceneast.add(btnupdate);
jpdownceneast.add(btnclear);
jpdownsou.add(labchange);
jpdownsou.add(jcbchange);
jpdownsou.add(btnchange);
jpdownsou.add(labaddmoney);
jpdownsou.add(jtfaddmoney);
jpdownsou.add(btnaddmoney);
//把子面板添加到主面板上
jpup.add(jpupnor,"North");
jpup.add(jpupcen,"Center");
this.add(jpup);
jpdowncen.add(jpdowncencen,"Center");
jpdowncen.add(jpdownceneast,"East");
jpdown.add(jpdowncen,"Center");
jpdown.add(jpdownsou,"South");
this.add(jpdown);
//设置位置大小
jpupcen.setLayout(null);
jsp.setBounds(10, 10, 700, 300);
//设置边框
TitledBorder tb1 = BorderFactory.createTitledBorder("会员查询");
TitledBorder tb2 = BorderFactory.createTitledBorder("会员资料维护");
TitledBorder tb3 = BorderFactory.createTitledBorder("兑换——充值");
//给三大面板加边框
jpup.setBorder(tb1);
jpdowncen.setBorder(tb2);
jpdownsou.setBorder(tb3);
}
MemberService ms = new MemberService();
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//查找会员
if(e.getSource() == btnfind) {
showData();
}
//添加会员
if(e.getSource() == btnadd) {
String card = jtfcard.getText();
String name = jtfname.getText();
String phone = jtfphone.getText();
String birth = jtfbirth.getText();
String jifen = jtfjifen.getText();
String money = jtfmoney.getText();
Member m = new Member(card,name,phone,birth,jifen,money);
boolean b = ms.addMember(m);
if(b==true) {
JOptionPane.showMessageDialog(null, "恭喜您成功成为了我们的会员");
showData();
}else
JOptionPane.showMessageDialog(null, "会员账号冲突,无法添加");
}
//删除会员
if(e.getSource() == btndelete) {
String card = jtfcard.getText();
boolean b = ms.delMember(card);
if(b==true) {
JOptionPane.showMessageDialog(null, "删除成功");
showData();
}else
JOptionPane.showMessageDialog(null, "账号不存在,删除失败");
}
//修改用户
if(e.getSource() == btnupdate) {
String card = jtfcard.getText();
String name = jtfname.getText();
String phone = jtfphone.getText();
String birth = jtfbirth.getText();
String jifen = jtfjifen.getText();
String money = jtfmoney.getText();
Member m = new Member(card,name,phone,birth,jifen,money);
boolean b = ms.updateMember(card, mber, m);
if(b==true) {
JOptionPane.showMessageDialog(null, "会员信息修改成功");
showData();
}else
JOptionPane.showMessageDialog(null, "已存在该会员账号,无法修改为相同的会员账号");
}
//清空文本框
if(e.getSource()==btnclear) {
jtfcard.setText("");
jtfname.setText("");
jtfphone.setText("");
jtfbirth.setText("");
jtfjifen.setText("");
jtfmoney.setText("");
jtfaddmoney.setText("");
}
//商品兑换
/*
规定:在积分足够的情况下才能够进行商品的兑换,下面是商品兑换所需要的积分的数量(每消费10元获得一个积分)
保温杯——————————————50
自动牙刷————————————20
帽子———————————————15
一斤鸡蛋————————————25
袜子五双————————————15
蓝牙耳机————————————50
电动车——————————————800
*/
if(e.getSource()==btnchange) {
String str = (String)jcbchange.getSelectedItem();//将Object强转为String
int n = 0;
for(;n<gift.length;n++) {
if(gift[n].equals(str))
break;//此时n存储的就是所兑换商品在数组中的下标
}
n = giftChange[n];//记录兑换该商品所需要的积分数
String card = jtfcard.getText();
String name = jtfname.getText();
String phone = jtfphone.getText();
String birth = jtfbirth.getText();
String jifen = jtfjifen.getText();
String money = jtfmoney.getText();
Member m = new Member(card,name,phone,birth,jifen,money);
boolean b = ms.changeMember(card, m, n);
if(b==true) {
JOptionPane.showMessageDialog(null, "恭喜您成功兑换了:"+str);
showData();
}else
JOptionPane.showMessageDialog(null, "会员账号不存在或积分不足");
}
//会员卡充值
if(e.getSource() == btnaddmoney) {
String addmoney = jtfaddmoney.getText();
String card = jtfcard.getText();
String money = jtfmoney.getText();
boolean b = ms.addMoneyMember(card, addmoney, money);
if(b==true) {
JOptionPane.showMessageDialog(null, "恭喜您充值成功,祝您消费愉快");
showData();
}else
JOptionPane.showMessageDialog(null, "会员账号不存,无法进行充值");
}
}
public void showData() {
Vector<Vector<String>> vv = new Vector<Vector<String>>();
String str = jtffind.getText().trim();//trim()方法是用来删除前后多余的空格的
if(str.equals("")) {
vv = ms.find();//查找所有记录
}else {
vv = ms.find(str);//查找单个
}
//在显示表之前,把原来的表中的记录清空
int row = dtm.getRowCount();//原本存在记录的行数
for(int i = 0 ; i< row ; i++) {
//每次都删除第一行(因为删除了第一行,下面的行又跑到了第一行,所以每次都删除第一行)
dtm.removeRow(0);
}
for(int i=0 ; i <vv.size() ;i++) {
Vector<String> v = vv.get(i);//查找第几行,数字从0开始,即(0为第一行)
dtm.addRow(v);
}
}
}
package dao;
import java.sql.*;
import java.util.*;
import vo.User;
import tools.DBUtil;
//Connection JDBC连接管理器
//Statement JDBC SQL执行器
//ResultSet sql执行的结果集
public class UserDao {
//查询一个用户的方法
public User findById(String id) {
Connection conn = DBUtil.getConn();
String sql = "select * from user where id = ?";
//预编译sql语句的 然后传入参数的时候bai ? 就会替换成你所需要的参数。
PreparedStatement psmt = null;
//sql执行的结果集
ResultSet rs = null ;
User u = null;
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1 , id);
rs = psmt.executeQuery();
if(rs.next()) {
String uid = rs.getString("id");
String password = rs.getString("pwd");
String username = rs.getString("xm");
String role = rs.getString("role");
u = new User(uid,password,username,role);
}
}catch(SQLException e) {
e.printStackTrace();
}
return u;
}
//查找所有用户(一条记录返回的是一个对象,多个记录就返回的是一个集合)(查询表中的所有记录)
//Vector集合可以改变数组的长度(每一个Vector相当于一个一维数组)
public Vector<Vector<String>> findAll() {
//连接数据库
Connection conn = DBUtil.getConn();
//操作SQL语句
Statement smt = null;
ResultSet rs = null;
Vector<Vector<String>> vv = new Vector<Vector<String>>();
try {
smt = conn.createStatement();
String sql = "select * from user";
rs = smt.executeQuery(sql);
//判断有无记录
while(rs.next()) {
String uid = rs.getString("id");
String username = rs.getString("pwd");
String pwd = rs.getString("xm");
String role = rs.getString("role");
Vector<String> v = new Vector<String>();
v.add(uid);
v.add(username);
v.add(pwd);
v.add(role);
vv.add(v);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
return vv;
}
//查找部分用户(一条、两条、多条.......)
public Vector<Vector<String>> find(String str) {
//连接数据库
Connection conn = DBUtil.getConn();
//操作SQL语句
PreparedStatement psmt = null;
ResultSet rs = null;
Vector<Vector<String>> vv = new Vector<Vector<String>>();
try {
String sql = "select * from user where id = ? or xm=? ";
// String sql = "select * from user where id like ? or xm like ? ";//模糊查询
psmt = conn.prepareStatement(sql);
psmt.setString(1, str);
// psmt.setString(1, "%"+str+"%");//模糊查询
psmt.setString(2, str);
// psmt.setString(2, "%"+str+"%");//模糊查询
rs = psmt.executeQuery();
//判断有无记录
while(rs.next()) {
String uid = rs.getString("id");
String username = rs.getString("pwd");
String pwd = rs.getString("xm");
String role = rs.getString("role");
Vector<String> v = new Vector<String>();
v.add(uid);
v.add(username);
v.add(pwd);
v.add(role);
vv.add(v);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
return vv;
}
//添加用户
public boolean addUser(User u) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "insert into user values(?,?,?,?)";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, u.getId());
psmt.setString(2, u.getPwd());
psmt.setString(3, u.getXm());
psmt.setString(4, u.getRole());
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//删除用户
public boolean delUser(String id) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "delete from user where id = ? ";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1,id);
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
/* //修改用户(先删除再添加的方法)
public int updateUser(String id, User u) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
//实验证明:使用先删除再添加的方法进行修改数据的话是不能通过姓名进行修改的
//因为当姓名有重复的时候,会删除所有姓名的,而却只添加了一个人的信息,所以不能称之为修改
// String sql = "delete from user where xm = ?";
//实验证明:使用先删除再添加的方法进行修改数据的话是不能通过姓名与学号进行或的关系进行修改的
// String sql = "delete from user where id = ? or xm = ?";
//因为当姓名和学号存在时,多个人存在,那么删除的会过多而只添加一个人的信息
//这种修改只适用于查找id,对id的其他内容进行修改,不能对其id进行修改
String sql = "delete from user where id = ?";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, id);
int i = psmt.executeUpdate();
if(i<=0)
return 2;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sql = "insert into user values(?,?,?,?)";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, u.getId());
psmt.setString(2, u.getPwd());
psmt.setString(3, u.getXm());
psmt.setString(4, u.getRole());
int i = psmt.executeUpdate();
if(i<=0)
return 2;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 3;
}
//修改用户(直接修改的方法)
public boolean updateUser(String id, User u) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "update user set pwd=?,xm=?,role=? where id=? ";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, u.getPwd());
psmt.setString(2, u.getXm());
psmt.setString(3, u.getRole());
psmt.setString(4,id);
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
} */
//修改用户
public boolean updateUser(String id,User user,User u) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
if(user.getId() == u.getId()) {
String sql = "update user set pwd=?,xm=?,role=? where id=? ";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, u.getPwd());
psmt.setString(2, u.getXm());
psmt.setString(3, u.getRole());
psmt.setString(4,id);
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}else{
String sql = "delete from user where id = ?";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, user.getId());
int i = psmt.executeUpdate();
if(i<=0)
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sql = "insert into user values(?,?,?,?)";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, u.getId());
psmt.setString(2, u.getPwd());
psmt.setString(3, u.getXm());
psmt.setString(4, u.getRole());
int i = psmt.executeUpdate();
if(i>=0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
//清空用户
public boolean clearUser() {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "delete from user";
try {
psmt = conn.prepareStatement(sql);
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
package dao;
import java.sql.*;
import java.util.*;
import tools.DBUtil;
import vo.Member;
//Connection JDBC连接管理器
//Statement JDBC SQL执行器
//ResultSet sql执行的结果集
public class MemberDao {
//查询一个用户的方法
public Member findByCard(String card) {
Connection conn = DBUtil.getConn();
String sql = "select * from member where card = ?";
//预编译sql语句的 然后传入参数的时候bai ? 就会替换成你所需要的参数。
PreparedStatement psmt = null;
//sql执行的结果集
ResultSet rs = null ;
Member m = null;
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1 , card);
rs = psmt.executeQuery();
if(rs.next()) {
String cards = rs.getString("card");
String name = rs.getString("name");
String phone = rs.getString("phone");
String birth = rs.getString("birth");
String jifen = rs.getString("jifen");
String money = rs.getString("money");
m = new Member(cards,name,phone,birth,jifen,money);
}
}catch(SQLException e) {
e.printStackTrace();
}
return m;
}
//查找所有用户(一条记录返回的是一个对象,多个记录就返回的是一个集合)(查询表中的所有记录)
//Vector集合可以改变数组的长度(每一个Vector相当于一个一维数组)
public Vector<Vector<String>> findAll() {
//连接数据库
Connection conn = DBUtil.getConn();
//操作SQL语句
Statement smt = null;
ResultSet rs = null;
Vector<Vector<String>> vv = new Vector<Vector<String>>();
try {
smt = conn.createStatement();
String sql = "select * from member";
rs = smt.executeQuery(sql);
while(rs.next()) {
String cards = rs.getString("card");
String name = rs.getString("name");
String phone = rs.getString("phone");
String birth = rs.getString("birth");
String jifen = rs.getString("jifen");
String money = rs.getString("money");
Vector<String> v = new Vector<String>();
v.add(cards);
v.add(name);
v.add(phone);
v.add(birth);
v.add(jifen);
v.add(money);
vv.add(v);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vv;
}
//查找部分会员(一条、两条、多条.......)
public Vector<Vector<String>> find(String str) {
//连接数据库
Connection conn = DBUtil.getConn();
//操作SQL语句
PreparedStatement psmt = null;
ResultSet rs = null;
Vector<Vector<String>> vv = new Vector<Vector<String>>();
String sql = "select * from member where card like ? or name like ? or phone like ? ";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, "%"+str+"%");
psmt.setString(2, "%"+str+"%");
psmt.setString(3, "%"+str+"%");
rs = psmt.executeQuery();
while(rs.next()) {
String card = rs.getString("card");
String name = rs.getString("name");
String phone = rs.getString("phone");
String birth = rs.getString("birth");
String jifen = rs.getString("jifen");
String money = rs.getString("money");
Vector<String> v = new Vector<String>();
v.add(card);
v.add(name);
v.add(phone);
v.add(birth);
v.add(jifen);
v.add(money);
vv.add(v);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vv;
}
//添加会员
public boolean addMember(Member m) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "insert into member values(?,?,?,?,?,?)";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, m.getCard());
psmt.setString(2, m.getName());
psmt.setString(3, m.getPhone());
psmt.setString(4, m.getBirth());
psmt.setString(5, m.getJifen());
psmt.setString(6, m.getMoney());
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//删除会员
public boolean delMember(String card) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "delete from member where card = ? ";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, card);
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//修改会员
public boolean updateMember(String card,Member mber ,Member m) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
if(mber.getCard() == m.getCard()) {
String sql = "update member set name=?,phone=?,birth=?,jifen=?,money=? where card=? ";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, m.getName());
psmt.setString(2, m.getPhone());
psmt.setString(3, m.getBirth());
psmt.setString(4, m.getJifen());
psmt.setString(5, m.getMoney());
psmt.setString(6, m.getCard());
int i = psmt.executeUpdate();
if(i>0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}else {
String sql ="delete from member where card = ?";
try {
psmt = conn.prepareStatement(sql);
psmt.setString(1, mber.getCard());
int i = psmt.executeUpdate();
if(i<=0)
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sql = "insert into member values(?,?,?,?,?,?)";
try {
psmt = conn.prepareStatement(sql);
psmt = conn.prepareStatement(sql);
psmt.setString(1, m.getCard());
psmt.setString(2, m.getName());
psmt.setString(3, m.getPhone());
psmt.setString(4, m.getBirth());
psmt.setString(5, m.getJifen());
psmt.setString(6, m.getMoney());
int i = psmt.executeUpdate();
if(i>=0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
//商品兑换
public boolean changeMember(String card, Member m, int n1) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "update member set jifen=? where card =?";
try {
psmt = conn.prepareStatement(sql);
int n2 = Integer.parseInt(m.getJifen());//获取现有的积分总数
int n = n2-n1;//兑换商品有应剩余的积分总数
if(n>=0) {
String str = n+"";//数字转换为字符串
psmt.setString(1, str);
psmt.setString(2, card);
int i = psmt.executeUpdate();
if(i>=0)
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
//会员卡充值
public boolean addMoneyMember(String card ,String addmoney,String money) {
Connection conn = DBUtil.getConn();
PreparedStatement psmt = null;
String sql = "update member set money=? where card =?";
try {
psmt = conn.prepareStatement(sql);
int qian = Integer.parseInt(addmoney) + Integer.parseInt(money);
money = qian+"";
psmt.setString(1, money);
psmt.setString(2, card);
int i = psmt.executeUpdate();
if(i>=0)
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
package service;
//和页面操作打交道
import java.util.*;
import dao.UserDao;
import vo.User;
public class UserService {
UserDao ud = new UserDao();
//查找所有用户(查找部分用户的话在下面的方法中加入参数)
public Vector<Vector<String>> find(){
Vector<Vector<String>> vv = ud.findAll();
return vv;
}
//查找部分用户
public Vector<Vector<String>> find(String str){
Vector<Vector<String>> vv = ud.find(str);
return vv;
}
//添加用户
public boolean addUser(User u) {
User ul = ud.findById(u.getId());
if(ul!=null)
return false;
else {
boolean b = ud.addUser(u);
return b;
}
}
//删除用户
public boolean delUser(String id) {
User ul = ud.findById(id);
if(ul!=null)
return ud.delUser(id);
else {
return false;
}
}
/* //修改用户(先删除再添加的方法)
public int updateUser(String id, User u) {
User ul = ud.findById(id);
if(ul!=null)
return ud.updateUser(id, u);
else
return 1;
}
//修改用户(直接修改的方法)
public boolean updateUser(String id,User u) {
User ul = ud.findById(id);
if(ul!=null)
return ud.updateUser(id, u);
else
return false;
} */
//修改用户
public boolean updateUser(String id, User user,User u) {
User ul = ud.findById(id);
if(user.getId().equals(u.getId()) || ul==null) {
return ud.updateUser(id, user, u);
}else
return false;
}
//清空用户
public boolean clearUser() {
return ud.clearUser();
}
}
package service;
//和页面操作打交道
import java.util.*;
import dao.MemberDao;
import vo.Member;
public class MemberService {
MemberDao md =new MemberDao();
//查找所有用户(查找部分用户的话在下面的方法中加入参数)
public Vector<Vector<String>> find(){
Vector<Vector<String>> vv = md.findAll();
return vv;
}
//查找部分用户
public Vector<Vector<String>> find(String str){
Vector<Vector<String>> vv = md.find(str);
return vv;
}
//添加用户
public boolean addMember(Member m) {
Member mb = md.findByCard(m.getCard());
if(mb!=null)
return false;
else
return md.addMember(m);
}
//删除用户
public boolean delMember(String card) {
Member mb = md.findByCard(card);
if(mb!=null)
return md.delMember(card);
else
return false;
}
//修改用户
public boolean updateMember(String card,Member mber,Member m) {
Member mb = md.findByCard(card);
if(mber.getCard().equals(m.getCard()) || mb==null)
return md.updateMember(card, mber, m);
else
return false;
}
//兑换商品
public boolean changeMember(String card,Member m,int n) {
Member mb = md.findByCard(card);
if(mb!=null)
return md.changeMember(card, m, n);
else
return false;
}
//会员卡充值
public boolean addMoneyMember(String card,String addmoney,String money) {
Member mb = md.findByCard(card);
if(mb!=null)
return md.addMoneyMember(card,addmoney,money);
return false;
}
}
package vo;
public class User {
private String id;
private String pwd;
private String xm;
private String role;
public User() {
super();
}
public User(String id, String pwd, String xm, String role) {
super();
this.id = id;
this.pwd = pwd;
this.xm = xm;
this.role = role;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getXm() {
return xm;
}
public void setXm(String xm) {
this.xm = xm;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "USer [id=" + id + ", pwd=" + pwd + ", xm=" + xm + ", role=" + role + "]";
}
}
package vo;
public class Member {
private String card;
private String name;
private String phone;
private String birth;
private String jifen;
private String money;
public Member() {
super();
}
public Member(String card, String name, String phone, String birth, String jifen, String money) {
super();
this.card = card;
this.name = name;
this.phone = phone;
this.birth = birth;
this.jifen = jifen;
this.money = money;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public String getJifen() {
return jifen;
}
public void setJifen(String jifen) {
this.jifen = jifen;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
@Override
public String toString() {
return "Member [card=" + card + ", name=" + name + ", phone=" + phone + ", birth=" + birth + ", jifen="
+ jifen + ", money=" + money + "]";
}
}
package tools;
import java.awt.event.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class ShowTime {
JLabel labtime = new JLabel();//显示时间的标签
public JLabel getTimeLabel() {
int delay = 1000;//1000的单位是毫秒
SimpleDateFormat sdf = new SimpleDateFormat("当前时间: yyyy年MM月dd日HH:mm:ss");
Timer time = new Timer(delay,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
labtime.setText(sdf.format(new Date()));
}
});
time.start();
return labtime;
}
}
package tools;
//数据库的一个工具类
import java.sql.*;
public class DBUtil {//创建一个连接对象
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("加载成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("加载失败");
e.printStackTrace();
}
String url = "jdbc:mysql://localhost:3306/market";//?useSSL=false
String username = "root";
String pwd = "root12345";
try {
conn = DriverManager.getConnection(url,username,pwd);
System.out.println("连接成功");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接失败");
e.printStackTrace();
}//3个参数分别表示连接数据库的URL、登录数据库的用户名和密码
return conn;
}
public static void close(PreparedStatement psmt,Connection conn) {
if(psmt!=null)
try {
psmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package tools;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.LayoutManager2;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.plaf.basic.BasicArrowButton;
import javax.swing.plaf.basic.BasicButtonUI;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
/**
* @author CCC520 2010 Jun
* @version 1.0 for 1.6
*/
public class DatePicker extends JTextField implements MouseListener,MouseMotionListener{
//年月栏颜色
public static Color YEAR_AND_MONTH_COLOR = new Color(30,60,115);
//年月字体颜色
public static Color YEAR_AND_MONTH_FONT_COLOR = new Color(255,255,255);
//星期栏渐变色
public static Color WEEK_COLOR1 = new Color(215,231,247);
public static Color WEEK_COLOR2 = new Color(199,216,232);
//白色的透明渐变,增加玻璃效果
public static Color GLASS_COLOR1 = new Color(244,244,244,100);
public static Color GLASS_COLOR2 = new Color(224,224,204,50);
//星期栏字体色
public static Color WEEK_FONT_COLOR = new Color(78,84,118);
//日历中间边框色
public static Color DAY_BORDER_COLOR = new Color(170,187,118);
//天数背景色
public static Color DAY_COLOR = new Color(0,0,0);
//选择渐变背景色
public static Color CHOICE_COLOR1 = new Color(244,244,244);
public static Color CHOICE_COLOR2 = new Color(209,225,251);
//日历缩略图颜色
public static Color WEEK_COLOR = Color.ORANGE;
private Calendar cc = null;
public static Dimension pop_Size = new Dimension(280,250);
private CalendarPanel cp = null;
private PickerLabel[][] pl = null;
private int choiceYear;
private int choiceMonth;
private int choiceDay;
private int thisYear;
private int thisMonth;
private int today;
private BufferedImage img;
private Insets insets;
private boolean pressed;
private HashMap hm;
//动画
ActionListener ac;
public DatePicker(String title){
super(title);
init();
}
public DatePicker(int i) {
super(i);
init();
}
public DatePicker() {
init();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(pressed)
g.drawImage(img, this.getWidth()-20+1,(this.getHeight()-16)/2+1, this);
else
g.drawImage(img, this.getWidth()-20,(this.getHeight()-16)/2, this);
}
public Insets getMargin() {
insets = super.getMargin();
if (insets == null) {
return new Insets(0, 0, 0, 20);
}
return new Insets(insets.top, insets.left + 20, insets.bottom, insets.right + 20);
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
if((e.getX()-this.getWidth()+20>=0)){
this.setCursor(new Cursor(Cursor.HAND_CURSOR));
}else
this.setCursor(new Cursor(Cursor.TEXT_CURSOR));
}
public String getText() {
// TODO Auto-generated method stub
if(super.getText() != null && super.getText().trim().length() > 0){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s = super.getText();
try{
df.parse(s);
}catch(Exception e){
s = df.format(new Date());
}
return s;
}else if(super.getText() == null || super.getText().trim().length() <= 0){
return "";
}
return super.getText();
}
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if((e.getX()-this.getWidth()+20>=0)){
pressed = true;
repaint();
}
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
if((e.getX()-this.getWidth()+20>=0)){
pressed = false;
repaint();
if(cp == null)
cp = new CalendarPanel(this);
cp.show(this, 0,this.getHeight());
}
}
public void init(){
this.setColumns(7);
hm = getHashMap();
pressed = false;
this.addMouseMotionListener(this);
this.addMouseListener(this);
img = new BufferedImage(16,16,BufferedImage.TYPE_4BYTE_ABGR);
Graphics g = img.getGraphics();
g.setColor(WEEK_COLOR);
g.drawRect(0, 0, 15,15);
g.fillRect(0, 0, 15, 3);
for(int i = 1 ; i < 5; i++){
g.drawLine(3*i, 0, 3*i, 15);
g.drawLine(0, 3*i, 15, 3*i);
}
g.fillRect(9, 9, 3, 3);
//reset();
//初始化文本框显示为当前日期
cc = Calendar.getInstance();
choiceYear = thisYear = cc.get(Calendar.YEAR);
choiceMonth = thisMonth = cc.get(Calendar.MONTH);
choiceDay = today = cc.get(Calendar.DAY_OF_MONTH);
resetToday();
this.setFont(new Font("", Font.PLAIN, 14));
}
public void resetToday(){
String mon = (thisMonth+1)+"";
if(thisMonth < 11)mon = "0"+(thisMonth+1);
String d = today+"";
if(today < 10)d = "0"+today;
this.setText(thisYear+"-"+mon+"-"+d);
}
public void reset(){
this.setText("");
}
private HashMap getHashMap() {
// TODO Auto-generated method stub
if(hm == null){
hm = new HashMap();
hm.put("一月", new Integer(0));
hm.put("二月", new Integer(1));
hm.put("三月", new Integer(2));
hm.put("四月", new Integer(3));
hm.put("五月", new Integer(4));
hm.put("六月", new Integer(5));
hm.put("七月", new Integer(6));
hm.put("八月", new Integer(7));
hm.put("九月", new Integer(8));
hm.put("十月", new Integer(9));
hm.put("十一月", new Integer(10));
hm.put("十二月", new Integer(11));
}
return hm;
}
class PickerToolBar extends JToolBar{
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
GradientPaint gp = new GradientPaint(0,0,DatePicker.WEEK_COLOR1,0,this.getHeight(),DatePicker.WEEK_COLOR2);
g2.setPaint(gp);
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
class LabelGroup{
private PickerLabel[] plGroup;
private PickerLabel choiceLabel;
public PickerLabel getChoiceLabel() {
return choiceLabel;
}
public void setChoiceLabel(PickerLabel choiceLabel) {
if(this.choiceLabel != null){
this.choiceLabel.choice = false;
this.choiceLabel.updateUI();
}
this.choiceLabel = choiceLabel;
this.choiceLabel.choice = true;
this.choiceLabel.updateUI();
}
public PickerLabel[] getPlGroup() {
return plGroup;
}
public LabelGroup(PickerLabel[] pl){
this.plGroup = pl;
for(int i = 0 ; i < plGroup.length ; i++){
final PickerLabel pl1 = plGroup[i];
pl1.addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e) {
pl1.setBackground(DatePicker.WEEK_COLOR1);
pl1.updateUI();
}
public void mouseExited(MouseEvent e) {
if(pl1 != choiceLabel)
pl1.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
pl1.updateUI();
}
public void mousePressed(MouseEvent e) {
if(choiceLabel != null){
choiceLabel.choice = false;
choiceLabel.updateUI();
}
pl1.choice = true;
choiceLabel = pl1;
pl1.updateUI();
}
});
}
}
}
class PickerLabel extends JLabel{
public boolean choice = false;
public PickerLabel(String string){
super(string);
init();
}
public PickerLabel() {
init();
}
private void init(){
this.setOpaque(true);
this.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
this.setHorizontalAlignment(SwingConstants.CENTER);
this.setForeground(DatePicker.DAY_COLOR);
this.setFont(new Font("",Font.PLAIN,14));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(choice){
this.setBackground(DatePicker.WEEK_COLOR1);
Graphics2D g2 = (Graphics2D)g.create();
GradientPaint gp = new GradientPaint(0,0,DatePicker.GLASS_COLOR1,0,this.getHeight(),DatePicker.GLASS_COLOR2);
g2.setPaint(gp);
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
g2.dispose();
g.drawRect(0, 0, this.getWidth()-1, this.getHeight()-1);
}else
this.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
}
}
class PickerTable extends JTable implements MouseListener,MouseMotionListener{
private PickerLabel choiceLabel = null;
private PickerLabel hoverLabel = null;
public PickerTable(){
this.setRowSelectionAllowed(false);
this.setRowHeight((int)(DatePicker.pop_Size.getHeight()-70)/6);
DefaultTableModel dtm = new DefaultTableModel(pl,new String[7]){
public boolean isCellEditable(int row, int column) {
// TODO Auto-generated method stub
return false;
}
};
this.setModel(dtm);
this.addMouseListener(this);
this.addMouseMotionListener(this);
this.setCellSelectionEnabled(false);
}
public TableCellRenderer getCellRenderer(int row, int column) {
// TODO Auto-generated method stub
return new TableCellRenderer(){
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
// TODO Auto-generated method stub
PickerLabel pl = (PickerLabel)value;
if(hasFocus && pl.getText().trim().length() > 0){
pl.setBackground(DatePicker.WEEK_COLOR1);
}
return pl;
}
};
}
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
PickerLabel jl = (PickerLabel)this.getValueAt(this.rowAtPoint(e.getPoint()), this.columnAtPoint(e.getPoint()));
if(jl.getText().trim().length() > 0){
if(choiceLabel != null){
choiceLabel.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
choiceLabel.choice = false;
}
choiceLabel = jl;
choiceLabel.choice = true;
}
}
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
if(hoverLabel != null)hoverLabel.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
hoverLabel = (PickerLabel)this.getValueAt(this.rowAtPoint(e.getPoint()), this.columnAtPoint(e.getPoint()));
if(!hoverLabel.getText().trim().equals(""))hoverLabel.setBackground(DatePicker.WEEK_COLOR1);
this.updateUI();
}
}
public static void main(String args[]){
JFrame jf = new JFrame();
jf.getContentPane().setLayout(new FlowLayout());
final DatePicker jcb = new DatePicker();
final JTextArea jta = new JTextArea();
KeyListener ma = new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getSource() == jcb && e.getKeyCode() == KeyEvent.VK_ENTER){
jta.requestFocus();
}
}
};
jcb.addKeyListener(ma);
jf.getContentPane().add(jcb);
jf.getContentPane().add(jta);
jf.setSize(320, 240);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
class CalendarPanel extends JPopupMenu{
private JLayeredPane jlp = null;
private JPanel jp_yearAndMonth = null;
private JPanel jp_weekAndDay = null;
//下拉选择年月的面板
private JPanel jp_yearChoice = null;
//显示主日期的面板
private JPanel jp_main = null;
private JButton jb_left = null;
private JButton jb_right = null;
Object[] item_year = new Object[100];
Object[] item_month = new Object[12];
private JTable jt = null;
private static final int ANIMATION_FRAMES=15;
//当前动画帧
private int frameIndex;
private Timer timer = null;
//存放返回日期的
private JTextField jtf = null;
//返回的日期字符串
public String date = null;
private JButton jb_today = null;
private JButton jb_Ok = null;
private JButton jb_Canel = null;
private JLabel jl_MonthYearC1 = null;
private LabelGroup monthGroup = null;
private LabelGroup yearGroup = null;
private PickerLabel[] pl_Year = null;
private PickerLabel[] pl_Month = null;
JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
//移入还是移除
private boolean move_Out = false;
private JLabel[] jl_week = new JLabel[]{new JLabel("日"),new JLabel("一"),new JLabel("二"),new JLabel("三"),
new JLabel("四"),new JLabel("五"),new JLabel("六"),};
class PickerPopAciton implements ActionListener{
int y = jp_yearChoice.getY();
public void actionPerformed(ActionEvent e) {
int add_Y = jp_yearChoice.getHeight()*frameIndex/ANIMATION_FRAMES;
//一直都是拉出去时会有问题
//经测试估计是因为下面的组件不停updateUI导致界面停顿
//此处如果用g = create()的话就会上拉的时候没有效果
//但是如果使用g本身的话就会出现一块虚影。。。
//最好的解决办法就是做动画时移出所有组件的位置到0,-y,然后做完后将位置移动回来即可
//1.6直接用setLocation
//cp.getGraphics().drawImage(dayImage, 1,1,cp.getWidth(),cp.getHeight(),null);
//cp.getGraphics().drawImage(yearImage,0,(move_Out?y-add_Y:y+add_Y),cp.getWidth(),cp.getHeight(),null);
jp_yearChoice.setLocation(0, (move_Out?y-add_Y:y+add_Y));
if(frameIndex == ANIMATION_FRAMES){
//最后一帧,动画停止
timer.stop();
/*//如果是移入,就最后把组件放到指定位置
if(!move_Out){
jp_yearChoice.setLocation(0, 0);
}else{
jp_main.setLocation(0, 0);
}*/
updateUI();
frameIndex = 0;
y = jp_yearChoice.getY();
}else{
frameIndex++;
}
}
}
public CalendarPanel(final JTextField jtf){
pl = new PickerLabel[6][7];
for(int i = 0 ; i < pl.length ; i++){
for(int j = 0 ; j < pl[i].length ; j++){
pl[i][j] = new PickerLabel();
}
}
this.jtf = jtf;
jt = new PickerTable();
jt.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getClickCount() == 1 && e.getButton() == MouseEvent.BUTTON1){
PickerLabel pl = (PickerLabel)jt.getValueAt(jt.rowAtPoint(e.getPoint()), jt.columnAtPoint(e.getPoint()));
if(pl != null && pl.getText().trim().length() > 0){
CalendarPanel.this.setVisible(false);
String month = (choiceMonth < 9)?("0"+(choiceMonth+1)):(""+(choiceMonth+1));
choiceDay = Integer.parseInt(pl.getText());
String day = (choiceDay < 10)?("0"+choiceDay):(""+choiceDay);
jtf.setText(choiceYear+"-"+month+"-"+day);
}
}
}
});
this.setLayout(new BorderLayout());
//设置上部选择框
this.jp_yearAndMonth = getYearAndMonthPanel();
//设置中部选择框
this.jp_weekAndDay = getWeekAndDayPanel();
this.jp_yearChoice = getYearMonthChoicePanel();
jlp = new JLayeredPane();
jp_main = new JPanel();
jp_main.setLocation(0, 0);
jp_main.setSize(DatePicker.pop_Size);
jp_main.setLayout(new BorderLayout());
jp_main.add(this.jp_yearAndMonth,BorderLayout.NORTH);
jp_main.add(this.jp_weekAndDay,BorderLayout.CENTER);
jlp.add(jp_main,JLayeredPane.DEFAULT_LAYER);
jlp.add(this.jp_yearChoice,JLayeredPane.POPUP_LAYER);
this.add(jlp);
//设置大小
this.setPreferredSize(DatePicker.pop_Size);
timer = new Timer(15,new PickerPopAciton());
//设置当前日期控件显示的值
this.flushDay(choiceYear,choiceMonth);
}
public Insets getInsets() {
// TODO Auto-generated method stub
return new Insets(1,1,1,1);
}
private JPanel getYearMonthChoicePanel() {
if(this.jp_yearChoice == null){
jp_yearChoice = new JPanel();
this.jp_yearChoice.setLocation(0, -(int)DatePicker.pop_Size.getHeight());
this.jp_yearChoice.setSize(DatePicker.pop_Size);
jsp.setDividerSize(1);
jsp.setEnabled(false);
jsp.setBorder(new LineBorder(DatePicker.WEEK_COLOR1));
jsp.setDividerLocation((int)DatePicker.pop_Size.getWidth()/2);
jsp.setLeftComponent(getMonthChoicePanel());
jsp.setRightComponent(getYearChoicePanel());
PickerToolBar jp_Ope = new PickerToolBar();
jp_Ope.setFloatable(false);
jp_Ope.setLayout(new FlowLayout());
jb_Ok = new JButton("确定");
jb_Canel = new JButton("取消");
jb_Ok.setFont(new Font("",Font.PLAIN,12));
jb_Canel.setFont(new Font("",Font.PLAIN,12));
jb_Ok.setUI(new BasicButtonUI());
jb_Canel.setUI(new BasicButtonUI());
jp_Ope.add(jb_Ok);
jp_Ope.add(jb_Canel);
jp_Ope.setOpaque(false);
this.jp_yearChoice.setLayout(new BorderLayout());
this.jp_yearChoice.add(jsp,BorderLayout.CENTER);
this.jp_yearChoice.add(jp_Ope,BorderLayout.SOUTH);
this.jp_yearChoice.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
ac = new MoveOutListener();
//aaaaaaaa
jb_Ok.addActionListener(ac);
jb_Ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
changeMonthYearChoice();
}
});
jb_Canel.addActionListener(ac);
}
return this.jp_yearChoice;
}
public void changeMonthYearChoice(){
choiceYear = Integer.parseInt(yearGroup.getChoiceLabel().getText());
choiceMonth = ((Integer)hm.get(monthGroup.getChoiceLabel().getText())).intValue();
flushDay(choiceYear,choiceMonth);
if(choiceMonth < 9)
jl_MonthYearC1.setText("0"+(choiceMonth+1)+"月 "+choiceYear+"年");
else
jl_MonthYearC1.setText((choiceMonth+1)+"月 "+choiceYear+"年");
}
private JPanel getYearChoicePanel() {
// TODO Auto-generated method stub
JPanel jp = new JPanel();
jp.setLayout(new TableLayout2(6,2,8,8));
PickerLabel thisYearLabel = new PickerLabel(""+thisYear);
pl_Year = new PickerLabel[]{
new PickerLabel(""+(thisYear-4)),new PickerLabel(""+(thisYear+1)),
new PickerLabel(""+(thisYear-3)),new PickerLabel(""+(thisYear+2)),new PickerLabel(""+(thisYear-2)),new PickerLabel(""+(thisYear+3)),
new PickerLabel(""+(thisYear-1)),new PickerLabel(""+(thisYear+4)),thisYearLabel,new PickerLabel(""+(thisYear+5))
};
yearGroup = new LabelGroup(pl_Year);
for(int i = 0 ; i < pl_Year.length ; i++){
if(pl_Year[i].getText().equals(choiceYear+""))
yearGroup.setChoiceLabel(pl_Year[i]);
pl_Year[i].addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() >= 2){
changeMonthYearChoice();
ac.actionPerformed(null);
}
}
});
}
StyleArrowButton leftYear = new StyleArrowButton(BasicArrowButton.WEST,new Color(215,231,247), new Color(100,120,200),
new Color(233,222,233).brighter(), new Color(233,244,233).brighter(),Color.BLUE);
StyleArrowButton rightYear = new StyleArrowButton(BasicArrowButton.EAST,new Color(215,231,247), new Color(100,120,200),
new Color(233,222,233).brighter(), new Color(233,244,233).brighter(),Color.BLUE);
leftYear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i = 0 ; i < pl_Year.length ; i++){
pl_Year[i].setText(""+(Integer.parseInt(pl_Year[i].getText())-10));
if(pl_Year[i].getText().equals(choiceYear+""))
yearGroup.setChoiceLabel(pl_Year[i]);
else
pl_Year[i].choice = false;
}
}
});
rightYear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
for(int i = 0 ; i < pl_Year.length ; i++){
pl_Year[i].setText(""+(Integer.parseInt(pl_Year[i].getText())+10));
if(pl_Year[i].getText().equals(choiceYear+""))
yearGroup.setChoiceLabel(pl_Year[i]);
else
pl_Year[i].choice = false;
}
}
});
jp.add(leftYear);
jp.add(rightYear);
for(int i = 0 ; i < pl_Year.length ; i++){
pl_Year[i].setForeground(DatePicker.WEEK_FONT_COLOR);
jp.add(pl_Year[i]);
}
jp.setBackground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
return jp;
}
private JPanel getMonthChoicePanel() {
// TODO Auto-generated method stub
JPanel jp = new JPanel();
jp.setLayout(new TableLayout2(6,2,8,8));
pl_Month = new PickerLabel[]{
new PickerLabel("一月"),new PickerLabel("二月"),new PickerLabel("三月"),new PickerLabel("四月"),
new PickerLabel("五月"),new PickerLabel("六月"),new PickerLabel("七月"),new PickerLabel("八月"),
new PickerLabel("九月"),new PickerLabel("十月"),new PickerLabel("十一月"),new PickerLabel("十二月")
};
monthGroup = new LabelGroup(pl_Month);
monthGroup.setChoiceLabel(pl_Month[choiceMonth]);
for(int i = 0 ; i < pl_Month.length ; i++){
pl_Month[i].setOpaque(true);
pl_Month[i].setForeground(DatePicker.WEEK_FONT_COLOR);
pl_Month[i].addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getClickCount() >= 2){
//aaaaa
changeMonthYearChoice();
ac.actionPerformed(null);
}
}
});
jp.add(pl_Month[i]);
}
jp.setBackground(Color.WHITE);
return jp;
}
class MoveOutListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
move_Out = true;
timer.start();
}
}
private JToolBar getButtonToolBar() {
// TODO Auto-generated method stub
JToolBar jtb = new PickerToolBar();
jtb.setLayout(new FlowLayout(FlowLayout.CENTER,0,0));
jtb.add(getJb_today());
jtb.setFloatable(false);
return jtb;
}
private JButton getJb_today() {
// TODO Auto-generated method stub
if(this.jb_today == null){
jb_today = new PickerButton("今天");
jb_today.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String mon = (thisMonth < 10)?("0"+(thisMonth+1)):(""+(thisMonth+1));
String day = (today < 10)?("0"+today):(""+today);
jtf.setText(thisYear+"-"+mon+"-"+day);
jl_MonthYearC1.setText(mon+"月 "+thisYear+"年");
choiceYear = thisYear;
choiceMonth = thisMonth;
choiceDay = today;
flushDay(thisYear,thisMonth);
cp.setVisible(false);
monthGroup.setChoiceLabel(monthGroup.getPlGroup()[thisMonth]);
int m = 1;
int n = 1;
for(int i = 0 ; i < pl_Year.length ; i++){
pl_Year[i].setText(
""+(((i+1)%2)==0?(thisYear+m++):(thisYear-5+n++))
);
if(pl_Year[i].getText().equals(choiceYear+""))
yearGroup.setChoiceLabel(pl_Year[i]);
}
}
});
}
return jb_today;
}
private JPanel getWeekAndDayPanel() {
// TODO Auto-generated method stub
if(this.jp_weekAndDay == null){
this.jp_weekAndDay = new JPanel();
this.jp_weekAndDay.setLayout(new BorderLayout());
this.jp_weekAndDay.add(getJToolBar(),BorderLayout.NORTH);
this.jp_weekAndDay.add(jt,BorderLayout.CENTER);
this.jp_weekAndDay.add(getButtonToolBar(),BorderLayout.SOUTH);
this.jp_weekAndDay.setBackground(Color.white);
}
return this.jp_weekAndDay;
}
private JPanel getYearAndMonthPanel() {
// TODO Auto-generated method stub
if(this.jp_yearAndMonth == null){
this.jp_yearAndMonth = new JPanel();
this.jp_yearAndMonth.setBackground(DatePicker.YEAR_AND_MONTH_COLOR);
final StyleArrowButton bab = new StyleArrowButton(BasicArrowButton.SOUTH,new Color(215,231,247), new Color(100,120,200),
new Color(233,222,233).brighter(), new Color(233,244,233).brighter(),Color.BLUE);
if(choiceMonth < 9)
jl_MonthYearC1 = new JLabel("0"+(choiceMonth+1)+"月 "+choiceYear+"年");
else
jl_MonthYearC1 = new JLabel((choiceMonth+1)+"月 "+choiceYear+"年");
jl_MonthYearC1.setForeground(DatePicker.YEAR_AND_MONTH_FONT_COLOR);
jl_MonthYearC1.setFont(new Font("",Font.PLAIN,16));
jb_left = new StyleArrowButton(BasicArrowButton.WEST,new Color(215,231,247), new Color(100,120,200),
new Color(233,222,233).brighter(), new Color(233,244,233).brighter(),Color.BLUE);
jb_right = new StyleArrowButton(BasicArrowButton.EAST,new Color(215,231,247), new Color(100,120,200),
new Color(233,222,233).brighter(), new Color(233,244,233).brighter(),Color.BLUE);
jp_yearAndMonth.setPreferredSize(new Dimension((int)DatePicker.pop_Size.getWidth(),20));
jb_left.setBounds((int)(this.jp_yearAndMonth.getPreferredSize().getWidth()*0.02),2,15,15);
jb_right.setBounds((int)(this.jp_yearAndMonth.getPreferredSize().getWidth()*0.92),2,15,15);
int width = (int)(this.jp_yearAndMonth.getPreferredSize().getWidth()-jl_MonthYearC1.getPreferredSize().getWidth()-bab.getPreferredSize().getWidth())/2;
jl_MonthYearC1.setBounds(width, 0,(int)jl_MonthYearC1.getPreferredSize().getWidth(),(int)jl_MonthYearC1.getPreferredSize().getHeight());
bab.setBounds((int)(width+jl_MonthYearC1.getPreferredSize().getWidth()),3,(int)bab.getPreferredSize().getWidth(),(int)bab.getPreferredSize().getHeight());
jp_yearAndMonth.setLayout(null);
jp_yearAndMonth.add(jb_left);
jp_yearAndMonth.add(jb_right);
jp_yearAndMonth.add(jl_MonthYearC1);
jp_yearAndMonth.add(bab);
jl_MonthYearC1.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == jl_MonthYearC1){
move_Out = false;
timer.start();
}
}
});
bab.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == bab){
move_Out = false;
timer.start();
}
}
});
jb_left.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(choiceMonth == 0){
choiceMonth = 11;
choiceYear = choiceYear-1;
}else{
choiceMonth = choiceMonth-1;
}
flushDay(choiceYear,choiceMonth);
if(choiceMonth < 9)
jl_MonthYearC1.setText("0"+(choiceMonth+1)+"月 "+choiceYear+"年");
else
jl_MonthYearC1.setText((choiceMonth+1)+"月 "+choiceYear+"年");
}
});
jb_right.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(choiceMonth == 11){
choiceMonth = 0;
choiceYear = choiceYear+1;
}else{
choiceMonth = choiceMonth+1;
}
flushDay(choiceYear,choiceMonth);
if(choiceMonth < 9)
jl_MonthYearC1.setText("0"+(choiceMonth+1)+"月 "+choiceYear+"年");
else
jl_MonthYearC1.setText((choiceMonth+1)+"月 "+choiceYear+"年");
}
});
}
return this.jp_yearAndMonth;
}
private JToolBar getJToolBar() {
// TODO Auto-generated method stub
JToolBar jtb = new PickerToolBar();
jtb.setLayout(new GridLayout(1,7));
//把星期加进去
for(int i = 0; i < jl_week.length; i++){
jl_week[i].setForeground(DatePicker.WEEK_FONT_COLOR);
jl_week[i].setFont(new Font("", Font.PLAIN, 15));
jl_week[i].setOpaque(false);
jl_week[i].setHorizontalAlignment(JLabel.CENTER);
jtb.add(jl_week[i]);
}
jtb.setFloatable(false);
return jtb;
}
public void flushDay(int year , int month){
//cc.set(field, value),最关键的方法,通过设置为某年,某月,来取得日子信息
//例如:取得1990年5月 注意:月份是当前物理月份+1,但是set()方法里面还是get()的那个值
cc.set(Calendar.YEAR, year);
cc.set(Calendar.MONTH, month);
cc.set(Calendar.DAY_OF_MONTH, 1);
int maxDayNo = cc.getActualMaximum(Calendar.DAY_OF_MONTH);
int dayNo = 2-cc.get(Calendar.DAY_OF_WEEK);
//把日加进去
for(int i = 0 ; i < jt.getRowCount(); i++){
for(int j = 0 ; j < jt.getColumnCount(); j++){
if(dayNo >= 1 && dayNo <= maxDayNo){
((PickerLabel)jt.getModel().getValueAt(i, j)).setText(""+dayNo);
if(dayNo == today && year == thisYear && month == thisMonth){
((PickerLabel)jt.getModel().getValueAt(i, j)).setBackground(Color.ORANGE);
}
}else{
((PickerLabel)jt.getModel().getValueAt(i, j)).setText("");
}
dayNo++;
}
}
this.updateUI();
}
}
}
class StyleArrowButton extends JButton implements SwingConstants
{
protected int direction;
//边框渐变色
private Color borderColor1;
//边框渐变色
private Color borderColor2;
//填充渐变色
private Color fillColor1;
//填充渐变色
private Color fillColor2;
//三角色平常色
private Color triangleColor;
public StyleArrowButton(int direction, Color BorderColor1, Color BorderColor2,
Color fillColor1, Color fillColor2,Color triangleColor) {
super();
this.setRolloverEnabled(false);
this.setOpaque(false);
this.setFocusPainted(false);
setRequestFocusEnabled(false);
setDirection(direction);
this.borderColor1 = BorderColor1;
this.borderColor2 = BorderColor2;
this.fillColor1 = fillColor1;
this.fillColor2 = fillColor2;
this.triangleColor = triangleColor;
}
public StyleArrowButton(int direction) {
this(direction, UIManager.getColor("control"), UIManager.getColor("controlShadow"),
UIManager.getColor("controlDkShadow"), UIManager.getColor("controlLtHighlight"),
Color.BLACK);
}
public int getDirection() {
return direction;
}
public void setDirection(int dir) {
direction = dir;
}
public void paint(Graphics g) {
Color origColor;
boolean isPressed, isEnabled;
int w, h, size;
w = getSize().width;
h = getSize().height;
origColor = g.getColor();
isPressed = getModel().isPressed();
isEnabled = isEnabled();
//fill RoundRect
GradientPaint fillGP = new GradientPaint(0, 0, this.fillColor1, 0, h, this.fillColor2);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(fillGP);
g2.fillRoundRect(1, 1, w-2, h-2,3,3);
//Draw the proper Border
//pressPaint
GradientPaint borderGP1 = new GradientPaint(0, 0, this.borderColor1, w, h, this.borderColor2);
g2.setPaint(borderGP1);
g2.drawRoundRect(0, 0, w-1, h-1,3,3);
if (isPressed) {
GradientPaint borderGP2 = new GradientPaint(0, 0, this.borderColor2, w, h, this.borderColor1);
g2.setPaint(borderGP2);
g2.drawRoundRect(0, 0, w-1, h-1,3,3);
}
//If there's no room to draw arrow, bail
if(h < 5 || w < 5) {
g.setColor(origColor);
return;
}
/*if (isPressed) {
g.translate(1, 1);
}*/
// Draw the arrow
size = Math.min((h - 4) / 3, (w - 4) / 3);
size = Math.max(size, 2);
paintTriangle(g, (w - size) / 2, (h - size) / 2,
size, direction, isEnabled);
// Reset the Graphics back to it's original settings
// if (isPressed) {
// g.translate(-1, -1);
// }
g.setColor(origColor);
}
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
public Dimension getMinimumSize() {
return new Dimension(5, 5);
}
public Dimension getMaximumSize() {
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
public boolean isFocusTraversable() {
return false;
}
public void paintTriangle(Graphics g, int x, int y, int size,
int direction, boolean isEnabled) {
Color oldColor = g.getColor();
int mid, i, j;
j = 0;
size = Math.max(size, 2);
mid = (size / 2) - 1;
g.translate(x, y);
if(isEnabled)
g.setColor((Color)UIManager.getColor("controlDkShadow"));
else
g.setColor(triangleColor);
switch(direction) {
case NORTH:
for(i = 0; i < size; i++) {
g.drawLine(mid-i, i, mid+i, i);
}
if(!isEnabled) {
g.setColor(triangleColor);
g.drawLine(mid-i+2, i, mid+i, i);
}
break;
case SOUTH:
if(!isEnabled) {
g.translate(1, 1);
g.setColor(triangleColor);
for(i = size-1; i >= 0; i--) {
g.drawLine(mid-i, j, mid+i, j);
j++;
}
g.translate(-1, -1);
g.setColor(triangleColor);
}
j = 0;
for(i = size-1; i >= 0; i--) {
g.drawLine(mid-i, j, mid+i, j);
j++;
}
break;
case WEST:
for(i = 0; i < size; i++) {
g.drawLine(i, mid-i, i, mid+i);
}
if(!isEnabled) {
g.setColor(triangleColor);
g.drawLine(i, mid-i+2, i, mid+i);
}
break;
case EAST:
if(!isEnabled) {
g.translate(1, 1);
g.setColor(triangleColor);
for(i = size-1; i >= 0; i--) {
g.drawLine(j, mid-i, j, mid+i);
j++;
}
g.translate(-1, -1);
g.setColor(triangleColor);
}
j = 0;
for(i = size-1; i >= 0; i--) {
g.drawLine(j, mid-i, j, mid+i);
j++;
}
break;
}
g.translate(-x, -y);
g.setColor(oldColor);
}
}
class PickerButton extends JButton{
//透明度
private float transparence = .3f;
private int pressed = 0;
public PickerButton(){
setFont(new Font(null,Font.PLAIN,12));
setBorderPainted(false);
setForeground(Color.BLACK);
setFocusPainted(false);
setContentAreaFilled(false);
addMouseListener(new MouseAdapter(){
public void mouseEntered(MouseEvent e){
transparence = 1f;
pressed = 1;
}
public void mouseExited(MouseEvent e){
transparence = .3f;
pressed = 0;
}
public void mousePressed(MouseEvent e){
pressed = 2;
}
public void mouseReleased(MouseEvent e){
transparence = .3f;
pressed = 0;
}
});
}
public PickerButton(String string) {
// TODO Auto-generated constructor stub
this();
setText(string);
}
public PickerButton(String title, JPopupMenu jpm){
this();
setText(title);
}
public Dimension getPreferredSize(){
return new Dimension(100,24);
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g.create();
int h = getHeight();
int w = getWidth();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
GradientPaint p1;
GradientPaint p2;
if(getModel().isPressed()){
p1 = new GradientPaint(0,0,new Color(0,0,0),0,h-1,new Color(100,100,100));
p2 = new GradientPaint(0,1,new Color(0,0,0,50),0,h-3,new Color(255,255,255,50));
}else{
//边框从0,0点到最下面是从灰到黑的渐变
p1 = new GradientPaint(0, 0, new Color(100, 100, 100), 0, h - 1,new Color(0, 0, 0));
//边框从0,1点到最下面是从白到黑的渐变
p2 = new GradientPaint(0, 1, new Color(255, 255, 255, 50), 0,h - 3, new Color(0, 0, 0, 50));
}
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,transparence));
//这个决定背景的形状和颜色
RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0,0,w-1,h-1,10,10);
Shape clip = g2d.getClip();
g2d.clip(r2d);
GradientPaint gp = null;
//这个决定背景颜色的渐变
if(pressed == 0)
gp = new GradientPaint(0f,0f,new Color(247,246,245),0f,h,new Color(222,222,221),true);
if(pressed == 1)
gp = new GradientPaint(0f,0f,new Color(197,219,245,110),0f,h,new Color(197,219,245,110),true);
if(pressed == 2)
gp = new GradientPaint(0f,0f,new Color(148,195,245,40),0f,h,new Color(148,195,245,40),true);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setClip(clip);
g2d.setPaint(p1);
//这个后面的两个参数要和r2d的两个参数对应上,即弧度要一样
g2d.drawRoundRect(0, 0, w-1, h-1, 10, 10);
g2d.setPaint(p2);
g2d.drawRoundRect(1, 1, w - 3, h - 3, 9, 9);
g2d.dispose();
super.paintComponent(g);
}
}
class TableLayout2 implements LayoutManager2 {
public static final Integer LEFT = new Integer(-1);
public static final Integer CENTER = new Integer(0);
public static final Integer RIGHT = new Integer(1);
int cellWidth = 0;
int cellHeight = 0;
//水平间距
public int hgap = 5;
//垂直间距
public int vagp = 5;
public int align = 0;
private Hashtable ht;
private int rows;
private int columns;
public TableLayout2(int rows,int columns){
ht = new Hashtable();
this.rows = rows;
this.columns = columns;
}
public TableLayout2(int rows,int columns, int hgap, int vagp){
this(rows,columns);
this.hgap = hgap;
this.vagp = vagp;
}
public TableLayout2(int rows, int columns, int align){
this(rows,columns);
this.align = align;
}
public TableLayout2(int rows, int columns, int hgap, int vagp, int align){
this(rows,columns,hgap,vagp);
this.align = align;
}
public void addLayoutComponent(Component comp, Object constraints) {
//没设置每个单元格的对其格式就全局对齐方式
if(constraints == null){
synchronized(comp.getTreeLock()){
ht.put(comp, new Integer(align));
}
}
else if(constraints != null && !(constraints instanceof Integer)){
throw new IllegalArgumentException("align must be Integer");
}
else{
synchronized(comp.getTreeLock()){
ht.put(comp, constraints);
}
}
}
public float getLayoutAlignmentX(Container target) {
// TODO Auto-generated method stub
return 0;
}
public float getLayoutAlignmentY(Container target) {
// TODO Auto-generated method stub
return 0;
}
public void invalidateLayout(Container target) {
// TODO Auto-generated method stub
}
public Dimension maximumLayoutSize(Container target) {
// TODO Auto-generated method stub
return new Dimension(Integer.MAX_VALUE,Integer.MAX_VALUE);
}
public void addLayoutComponent(String name, Component comp) {
// TODO Auto-generated method stub
}
//所有布局类中最重要的一个类,布局管理器会先执行这个,然后执行大小
public void layoutContainer(Container parent) {
// TODO Auto-generated method stub
int x = hgap;
int y = vagp;
int count = 0;
int width = 0;
int height = 0;
Component[] comps = parent.getComponents();
//如果有设置大小就强制内容大小,如果没有就自适应大小
if(parent.getPreferredSize().getWidth() > 0 && parent.getPreferredSize().getHeight() > 0){
Insets inset = parent.getInsets();
cellWidth = (int)(parent.getWidth()-inset.left-inset.right-vagp*(columns+1))/columns;
cellHeight = (int)(parent.getHeight()-inset.top-inset.bottom-hgap*(rows+1))/rows;
}else{
for (int i = 0 ; i < comps.length ; i++) {
Dimension d = comps[i].getPreferredSize();
if (cellWidth < d.width) {
cellWidth = d.width;
}
if (cellHeight < d.height) {
cellHeight = d.height;
}
}
}
//布局每个单元格
for(int i = 1 ; i <= rows ; i++){
for(int j = 1; j <= columns ; j++){
//获取对齐方式,根据对齐方式 设置组件位置
int align = ((Integer)ht.get(comps[count])).intValue();
//设置了preferredSize之后 如果组件大小大于 单元格大小,那组件大小会强制为单元格大小
width = comps[count].getPreferredSize().width;
height = comps[count].getPreferredSize().height;
if(width > cellWidth){
width = cellWidth;
}
if(height > cellHeight){
height = cellHeight;
}
//左
int offSetX = 0;
int offSetY = (cellHeight-height)/2;
//中
if(align == 0){
offSetX = (cellWidth-width)/2;
//右
}else if(align == 1){
offSetX = cellWidth-width;
}
comps[count].setBounds(x+offSetX, y+offSetY, width, height);
count++;
x += cellWidth+hgap;
}
x = hgap;
y += cellHeight+vagp;
}
}
public Dimension minimumLayoutSize(Container parent) {
// TODO Auto-generated method stub
return new Dimension(50,50);
}
//很显然在1.4就算设置了也是会进来的,顺序layoutContainer----preferredLayoutSize
public Dimension preferredLayoutSize(Container parent) {
// TODO Auto-generated method stub
synchronized(parent.getTreeLock()){
Insets insets = parent.getInsets();
return new Dimension(insets.left + insets.right + cellWidth*columns + (columns+1)*hgap,
insets.top + insets.bottom + cellHeight*rows + (rows+1)*vagp);
}
}
public void removeLayoutComponent(Component comp) {
// TODO Auto-generated method stub
synchronized(comp.getTreeLock()){
ht.remove(comp);
}
}
}
create market;
Use market;
create table user(
id varchar(6),
pwd varchar(10),
xm varchar(20),
role varchar(10));
insert into user values('20001','123','王晓','管理员');
insert into user values('20002','222','李海','收银员');
insert into user values('20003','666','王妃','管理员');
Create table member(
card varchar(20),
name varchar(10),
phone varchar(20),
birth varchar(20),
jifen varchar(8),
money varchar(10));