主类示例
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
public class Main extends JFrame implements ActionListener,
ListCellRenderer<String> {
/**
*
*/
private static final long serialVersionUID = 1L;
static Main m;
Connection con = null;
Statement stmt = null;
Vector<String> studNumbers;
DefaultListModel<String> listmodel;
JList<String> numberlist;
DefaultTableModel tablemodel;
JTable table;
JLabel studnums;
JLabel surnames;
JLabel initialss;
JButton conbtn;
JButton disc;
JButton exp;
String selected; // currently selected student number.
String filename;
String CurYear = "";
JScrollPane scrollpane;
Document doc;
Element studyrecord;
Element yearofstudy;
ResultSet resultset;
public static void main(String[] args) {
// TODO Auto-generated method stub
m = new Main();
m.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public Main() {
BuildUI();
setBounds(100, 100, 685, 600);
pack();
setVisible(true);
}
private void BuildUI() {
setTitle("Study Records");
setLayout(new BorderLayout());
setBackground(Color.gray);
JPanel top = new JPanel();
top.setBackground(Color.DARK_GRAY);
top.setOpaque(true);
conbtn = new JButton("Connect");
conbtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
connect();
Vector<String> tempV = new Vector<String>();
tempV = populateList();
for (int x = 0; x <= tempV.size() - 1; x++) {
listmodel.addElement(tempV.get(x));
}
conbtn.setEnabled(false);
disc.setEnabled(true);
}
});
disc = new JButton("Disconnect");
disc.setEnabled(false);
disc.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
disconnectDB();
disc.setEnabled(false);
conbtn.setEnabled(true);
table.setModel(new DefaultTableModel());
surnames.setText("");
studnums.setText("");
initialss.setText("");
numberlist.setModel(new DefaultListModel<String>());
}
});
exp = new JButton("Export");
exp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
savetoXML();
}
});
top.setLayout(new FlowLayout());
top.add(conbtn);
top.add(disc);
top.add(exp);
add("North", top);
JPanel left = new JPanel();
left.setPreferredSize(new Dimension(200, 0));
left.setLayout(new BorderLayout());
JLabel SN = new JLabel("Student Numbers");
left.add("North", SN);
// List
listmodel = new DefaultListModel<String>();
numberlist = new JList<String>(listmodel);
JScrollPane scroll = new JScrollPane(numberlist);
// Cell Rendering
numberlist.setCellRenderer(this);
numberlist.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if (e.getValueIsAdjusting()) {
selected = numberlist.getSelectedValue();
studnums.setText(selected);
ResultSet result = getStudent(selected);
try {
while (result.next()) {
surnames.setText(result.getString("Surname"));
initialss.setText(result.getString("Initials"));
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
tablemodel = (DefaultTableModel) table.getModel();
tablemodel.getDataVector().removeAllElements();
tablemodel.fireTableDataChanged();
populateTable(selected);
table.setModel(tablemodel);
}
});
left.add("Center", scroll);
add("West", left);
JPanel center = new JPanel();
center.setLayout(new BorderLayout());
JPanel right = new JPanel();
right.setLayout(new GridLayout(3, 2));
JLabel studnum = new JLabel("Student Number:");
JLabel surname = new JLabel("Surname:");
JLabel initials = new JLabel("Initials:");
studnums = new JLabel("");
surnames = new JLabel("");
initialss = new JLabel("");
right.add(studnum);
right.add(studnums);
right.add(surname);
right.add(surnames);
right.add(initials);
right.add(initialss);
center.add("North", right);
add(center);
// table
tablemodel = new DefaultTableModel();
tablemodel.addColumn(new String("Year"));
tablemodel.addColumn(new String("ModuleCode"));
tablemodel.addColumn(new String("ModuleName"));
tablemodel.addColumn(new String("Mark"));
table = new JTable(tablemodel);
scrollpane = new JScrollPane(table);
center.add("Center", scrollpane);
// XML
try {
doc = createDoc();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
studyrecord = doc.createElement("StudyRecord");
// yearofstudy = doc.createElement("YearofStudy");
}
public String getfilename() {
// filename =
// "C:\\Users\\user\\Desktop\\WRAP301\\WRAP pracs\\Prac 11.MyStudyRecords.mdb";
JFileChooser dlgOpen = new JFileChooser();
if (dlgOpen.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
filename = dlgOpen.getSelectedFile().getAbsolutePath();
System.out.println(filename);
return filename;
}
return null;
}
public String savefilename() {
JFileChooser dlgOpen = new JFileChooser();
if (dlgOpen.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
filename = dlgOpen.getSelectedFile().getAbsolutePath();
System.out.println(filename);
return filename;
}
return null;
}
public void connect() {
System.out.println("Establishing connection to database...");
System.out.println(" Loading ODBC driver for MS Access database...");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (Exception e) {
System.out.println(" Unable to load ODBC driver...");
return;
}
System.out
.println(" Use ODBC driver to connect to MS Access database (students.mdb)...");
try {
System.out.println(" Locate database to open...");
String file = m.getfilename();
System.out.println(file);
String myDB = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="
+ file;
System.out.println(" Connection string = " + myDB);
// create connection to DB
con = DriverManager.getConnection(myDB, "", "");
// create statement object for manipulating DB
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
} catch (Exception e) {
System.out
.println(" Unable to connect to DB..." + e.getMessage());
}
System.out.println();
}
public void disconnectDB() {
System.out.println("Disconnecting from database...");
try {
// Important to close connection (same as with files)
con.close();
} catch (Exception ex) {
System.out.println(" Unable to disconnect from database");
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public Vector<String> populateList() {
Vector<String> list = new Vector<String>();
try {
String sql = "SELECT * FROM students";
System.out.println(" Performing query, sql = " + sql);
ResultSet result = stmt.executeQuery(sql);
System.out.println();
while (result.next()) {
String studNo = result.getString("StudentNo");
list.add(studNo);
}
return list;
} catch (Exception e) {
return null;
}
}
public ResultSet getStudent(String student) {
try {
String sql = "SELECT students.StudentNo, students.Surname, students.Initials, takes.Year, takes.Mark, modules.ModuleCode, modules.ModuleName FROM students INNER JOIN (modules INNER JOIN takes ON modules.[ModuleCode] = takes.[ModuleCode]) ON students.[StudentNo] = takes.[StudentNumber] WHERE (((students.StudentNo)="
+ student + "))";
System.out.println(" Performing query, sql = " + sql);
ResultSet result = stmt.executeQuery(sql);
System.out.println(result.toString());
return result;
} catch (Exception e) {
e.getMessage();
return null;
}
}
public void populateTable(String studNum) {
ResultSet tempset = getStudent(selected);
try {
while (tempset.next()) {
Vector<String> tempV = new Vector<String>();
tempV.addElement(tempset.getString("Year"));
tempV.addElement(tempset.getString("ModuleCode"));
tempV.addElement(tempset.getString("ModuleName"));
tempV.addElement(tempset.getString("Mark"));
tablemodel.addRow(tempV);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void savetoXML() {
Element report = doc.createElement("Report");
Element student = createStudent(doc);
ResultSet studentsetR = getStudent(selected);
Element studyrecord = null;
String year = "";
// int x=1;
try {
while (studentsetR.next()) {
// System.out.println(studentsetR.getArray(x).toString());
CurYear = studentsetR.getString("Year");
year = CurYear;
Element yearofstudy = doc.createElement("Yearofstudy");
studyrecord = createStudyrecord(yearofstudy, studentsetR,
CurYear);
// x++;
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
report.appendChild(student);
report.appendChild(studyrecord);
doc.appendChild(report);
try {
saveDoc(doc, savefilename());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Document createDoc() throws Exception {
// create DocumentBuilder to parse XML document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// create empty document
Document doc = builder.newDocument();
return doc;
}
public Element createStudent(Document doc) {
Element student = doc.createElement("student");
Element studnum = doc.createElement("studnum");
Element surname = doc.createElement("surname");
Element initials = doc.createElement("initials");
ResultSet studentresult = getStudent(selected);
try {
while (studentresult.next()) {
studnum.appendChild(doc.createTextNode((studentresult
.getString("StudentNo"))));
surname.appendChild(doc.createTextNode(studentresult
.getString("Surname")));
initials.appendChild(doc.createTextNode(studentresult
.getString("Initials")));
break;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
student.appendChild(studnum);
student.appendChild(surname);
student.appendChild(initials);
return student;
}
public Element createStudyrecord(Element yearofstudy, ResultSet studentSet,
String Year) {
// Element yearofstudy = doc.createElement("YearOfStudy");
Element module = doc.createElement("module");
try {
Year = studentSet.getString("Year");
yearofstudy.setAttribute("year", CurYear);
yearofstudy.appendChild(module);
module.setAttribute("code", studentSet.getString("ModuleCode"));
module.setAttribute("mark", studentSet.getString("Mark"));
module.setAttribute("name", studentSet.getString("ModuleName"));
studyrecord.appendChild(yearofstudy);
return studyrecord;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void saveDoc(Document doc, String filename) throws Exception {
// obtain serializer
DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature(
"LS", "3.0");
LSSerializer ser = implLS.createLSSerializer();
ser.getDomConfig().setParameter("format-pretty-print", true);
// create file to save too
FileOutputStream fout = new FileOutputStream(filename);
// set encoding options
LSOutput lsOutput = implLS.createLSOutput();
lsOutput.setEncoding("UTF-8");
// tell to save xml output to file
lsOutput.setByteStream(fout);
// FINALLY write output
ser.write(doc, lsOutput);
// close file
fout.close();
// display output on screen to see (note UTF-16 at top)
// System.out.println(ser.writeToString(doc));
}
public Component getListCellRendererComponent(JList<? extends String> list,
String value, int index, boolean isSelected, boolean cellHasFocus) {
Border blackline = BorderFactory.createLineBorder(Color.black);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
ResultSet set = getStudent(value);
JLabel studnum_label = new JLabel("Stud number:");
JLabel surname_label = new JLabel("Surname:");
JLabel initials_label = new JLabel("Initials:");
JLabel yos_label = new JLabel("Year of study:");
System.out.println("value:" + value);
JLabel studnum = new JLabel(value);
JLabel surname = new JLabel("");
JLabel initials = new JLabel("");
JLabel yearofStudy = new JLabel("");
try {
while (set.next()) {
surname = new JLabel(set.getString("Surname"));
System.out.println("here");
initials = new JLabel(set.getString("Initials"));
// set.last();
yearofStudy = new JLabel(set.getString("Year"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JPanel center = new JPanel(new GridLayout(4, 2));
center.add(studnum_label);
System.out.println("studnum value before adding: " + studnum.getText());
center.add(studnum);
center.add(surname_label);
System.out.println("surname value before adding: " + surname);
center.add(surname);
center.add(initials_label);
center.add(initials);
center.add(yos_label);
center.add(yearofStudy);
if (isSelected) {
studnum_label.setForeground(Color.blue);
surname_label.setForeground(Color.blue);
initials_label.setForeground(Color.blue);
yos_label.setForeground(Color.blue);
studnum.setForeground(Color.blue);
surname.setForeground(Color.blue);
initials.setForeground(Color.blue);
yearofStudy.setForeground(Color.blue);
}
if (cellHasFocus) {
studnum_label.setForeground(Color.red);
surname_label.setForeground(Color.red);
initials_label.setForeground(Color.red);
yos_label.setForeground(Color.red);
studnum.setForeground(Color.red);
surname.setForeground(Color.red);
initials.setForeground(Color.red);
yearofStudy.setForeground(Color.red);
}
JLabel title = new JLabel("Student Card");
JLabel image = new JLabel(new ImageIcon("earth.jpg"));
panel.add(BorderLayout.NORTH, title);
panel.setBorder(blackline);
panel.add(BorderLayout.WEST, image);
panel.add(BorderLayout.CENTER, center);
return panel;
}
}