这是一个要通过GUI访问数据库的代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TesterUserAndUserDA extends JFrame implements ActionListener {
User firstUser;
JTextField mes1Text,mes2Text,mes3Text,mes4Text,mes5Text;
JTextArea out;
JButton addBtn,findBtn,updBtn,delBtn,closeBtn;
public TesterUserAndUserDA(){
super("数据访问");
Container c=this.getContentPane();
c.setLayout(new GridLayout(3,6));
JPanel first=new JPanel(new FlowLayout());
JPanel second=new JPanel(new FlowLayout());
JPanel third=new JPanel(new FlowLayout());
addBtn=new JButton("添加");
findBtn=new JButton("查找");
updBtn=new JButton("修改");
delBtn=new JButton("删除");
closeBtn=new JButton("退出");
JLabel mes1=new JLabel("UserID:");
mes1Text=new JTextField(10);
JLabel mes2=new JLabel("Name:");
mes1Text=new JTextField(10);
JLabel mes3=new JLabel("Password:");
mes1Text=new JTextField(10);
first.add(mes1);
first.add(mes1Text);
first.add(mes2);
first.add(mes2Text);
first.add(mes3);
first.add(mes3Text);
c.add(first);
second.add(addBtn);
second.add(findBtn);
second.add(updBtn);
second.add(delBtn);
second.add(closeBtn);
c.add(second);
JLabel output=new JLabel("显示:");
out=new JTextArea();
third.add(output);
third.add(out);
c.add(third);
addBtn.addActionListener(this);
findBtn.addActionListener(this);
updBtn.addActionListener(this);
delBtn.addActionListener(this);
closeBtn.addActionListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,1000);
this.setVisible(true);
}
public static void main(String []args){
TesterUserAndUserDA bUser=new TesterUserAndUserDA();
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==addBtn) {
String userID=mes1Text.getText();
String name=mes2Text.getText();
String password=mes3Text.getText();
firstUser=new User(userID,name,password);
User.initialize();
try{
firstUser.add();
System.out.println("加一个用户");
}
catch(DuplicateException ee){
System.out.println(ee);
}
}
if(e.getSource()==findBtn) {
//test find
try{
String userID=mes1Text.getText();
firstUser=User.find(userID);
System.out.println("查询"+firstUser.getDetails());
}
catch(NotFoundException ee){
System.out.println(ee);
}}
if(e.getSource()==updBtn) {
//test update
try{
String userID=mes1Text.getText();
String name=mes2Text.getText();
String password=mes3Text.getText();
firstUser.update();
firstUser=User.find(userID);
System.out.println("更新后"+firstUser.getDetails());
}
catch(NotFoundException ee){
System.out.println(ee);
}
}
if(e.getSource()==delBtn) {
//test delete
try{String userID=mes1Text.getText();
firstUser.delete();
System.out.println("要删除"+firstUser.getDetails());
firstUser=User.find(userID);
System.out.println("删除后查询"+firstUser.getDetails());
}