By GokiSoft.com|
22:35 29/10/2021|
Java Advanced
[Video] - Hướng dẫn tạo dự án quản lý sinh viên + import + export XML File
Source Code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lession2;
/**
*
* @author Diep.Tran
*/
public class Student {
String rollNo, fullname, gender, address;
public Student() {
}
public Student(String rollNo, String fullname, String gender, String address) {
this.rollNo = rollNo;
this.fullname = fullname;
this.gender = gender;
this.address = address;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" + "rollNo=" + rollNo + ", fullname=" + fullname + ", gender=" + gender + ", address=" + address + '}';
}
public String getXMLString() {
return "<student>\n" +
" <rollNo>"+rollNo+"</rollNo>\n" +
" <fullname>"+fullname+"</fullname>\n" +
" <address>"+address+"</address>\n" +
" <gender>"+gender+"</gender>\n" +
" </student>";
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lession2;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author Diep.Tran
*/
public class StudentHandler extends DefaultHandler{
List<Student> studentList = new ArrayList<>();
Student currentStudent = null;
boolean isRollNo = false, isFullname = false, isGender = false, isAddress = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(qName.equalsIgnoreCase("student")) {
currentStudent = new Student();
} else if(qName.equalsIgnoreCase("rollNo")) {
isRollNo = true;
} else if(qName.equalsIgnoreCase("fullname")) {
isFullname = true;
} else if(qName.equalsIgnoreCase("gender")) {
isGender = true;
} else if(qName.equalsIgnoreCase("address")) {
isAddress = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("student")) {
studentList.add(currentStudent);
currentStudent = null;
} else if(qName.equalsIgnoreCase("rollNo")) {
isRollNo = false;
} else if(qName.equalsIgnoreCase("fullname")) {
isFullname = false;
} else if(qName.equalsIgnoreCase("gender")) {
isGender = false;
} else if(qName.equalsIgnoreCase("address")) {
isAddress = false;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String value = new String(ch, start, length);
if(isRollNo) {
currentStudent.setRollNo(value);
} else if(isFullname) {
currentStudent.setFullname(value);
} else if(isGender) {
currentStudent.setGender(value);
} else if(isAddress) {
currentStudent.setAddress(value);
}
}
public List<Student> getStudentList() {
return studentList;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<studentList>
<student>
<rollNo>R001</rollNo>
<fullname>TRAN VAN A</fullname>
<address>HA NOI</address>
<gender>Male</gender>
</student><student>
<rollNo>R002</rollNo>
<fullname>TRAN VAN B</fullname>
<address>NAM DINH</address>
<gender>Male</gender>
</student><student>
<rollNo>R003</rollNo>
<fullname>TRAN VAN B</fullname>
<address>NAM DINH</address>
<gender>Male</gender>
</student><student>
<rollNo>R004</rollNo>
<fullname>TRAN VAN C</fullname>
<address>NAM DINH</address>
<gender>Male</gender>
</student><student>
<rollNo>R005</rollNo>
<fullname>TRAN VAN E</fullname>
<address>NAM DINH</address>
<gender>Male</gender>
</student><student>
<rollNo>R006</rollNo>
<fullname>Tran Van T</fullname>
<address>OKOK</address>
<gender>Male</gender>
</student>
</studentList>
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lession2;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
/**
*
* @author Diep.Tran
*/
public class StudentFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Student> studentList = new ArrayList<>();
/**
* Creates new form StudentFrame
*/
public StudentFrame() {
initComponents();
tableModel = (DefaultTableModel) tblStudent.getModel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtRollNo = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
txtFullName = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtAddress = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
cbGender = new javax.swing.JComboBox<>();
btnSave = new javax.swing.JButton();
btnExportXML = new javax.swing.JButton();
btnImportXML = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tblStudent = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Student Manager");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Student's Detail Information"));
jLabel1.setText("Roll No:");
jLabel2.setText("Full Name:");
jLabel3.setText("Gender:");
jLabel4.setText("Address:");
cbGender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "Female" }));
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnExportXML.setText("Export XML");
btnExportXML.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExportXMLActionPerformed(evt);
}
});
btnImportXML.setText("Import XML");
btnImportXML.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnImportXMLActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGap(28, 28, 28)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(165, 165, 165)
.addComponent(btnExportXML, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addComponent(btnImportXML, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSave))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnImportXML))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExportXML))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(30, Short.MAX_VALUE))
);
tblStudent.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Roll No", "Full Name", "Gender", "Address"
}
) {
boolean[] canEdit = new boolean [] {
false, false, true, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(tblStudent);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String rollNo = txtRollNo.getText();
String fullname = txtFullName.getText();
String gender = cbGender.getSelectedItem().toString();
String address = txtAddress.getText();
if(rollNo.isEmpty() || fullname.isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "RollNo is empty || fullname is empty?");
return;
}
for (Student student : studentList) {
if(student.getRollNo().equalsIgnoreCase(rollNo)) {
JOptionPane.showMessageDialog(rootPane, "RollNo existed!!!");
return;
}
}
Student std = new Student(rollNo, fullname, gender, address);
studentList.add(std);
tableModel.addRow(new Object[] {rollNo, fullname, gender, address});
}
private void btnImportXMLActionPerformed(java.awt.event.ActionEvent evt) {
FileInputStream fis = null;
try {
// TODO add your handling code here:
fis = new FileInputStream("student.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
StudentHandler handler = new StudentHandler();
parser.parse(fis, handler);
studentList = handler.getStudentList();
tableModel.setRowCount(0);
for (Student student : studentList) {
tableModel.addRow(new Object[] {
student.getRollNo(), student.getFullname(),
student.getGender(), student.getAddress()
});
}
} catch (FileNotFoundException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
JOptionPane.showMessageDialog(rootPane, "Import success!!!");
}
private void btnExportXMLActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
StringBuilder builder = new StringBuilder();
for (Student student : studentList) {
builder.append(student.getXMLString());
}
String body = builder.toString();
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<studentList>\n" +
body+
"\n</studentList>";
//save into file student.xml
FileOutputStream fos = null;
try {
fos = new FileOutputStream("student.xml");
byte[] data = xml.getBytes();
fos.write(data);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
JOptionPane.showMessageDialog(rootPane, "Save success!!!");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StudentFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnExportXML;
private javax.swing.JButton btnImportXML;
private javax.swing.JButton btnSave;
private javax.swing.JComboBox<String> cbGender;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblStudent;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtFullName;
private javax.swing.JTextField txtRollNo;
// End of variables declaration
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)
![lê văn phương [T1907A]](https://www.gravatar.com/avatar/a07ddfb51e1e7189c76b4e42dbdbcddc.jpg?s=80&d=mm&r=g)
lê văn phương
2020-04-17 11:14:57
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lesson2;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
/**
*
* @author HOME
*/
public class StudentFrame extends javax.swing.JFrame {
DefaultTableModel tableModel;
List<Student> studentList = new ArrayList<>();
/**
* Creates new form StudentFrame
*/
public StudentFrame() {
initComponents();
tableModel = (DefaultTableModel) btlStudent.getModel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
txtRollNo = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtFullName = new javax.swing.JTextField();
txtAddress = new javax.swing.JTextField();
btnSave = new javax.swing.JButton();
btnInportXML = new javax.swing.JButton();
btnExport = new javax.swing.JButton();
cbGender = new javax.swing.JComboBox<>();
jScrollPane2 = new javax.swing.JScrollPane();
btlStudent = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input Student's Detail Information"));
jLabel1.setText("Roll No :");
jLabel2.setText("Full Name :");
jLabel3.setText("Gender :");
jLabel4.setText("Address :");
btnSave.setText("Save");
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnInportXML.setText("Import XML");
btnInportXML.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInportXMLActionPerformed(evt);
}
});
btnExport.setText("Export XML");
btnExport.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExportActionPerformed(evt);
}
});
cbGender.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Male", "female" }));
cbGender.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbGenderActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel4)
.addComponent(jLabel3))
.addGap(58, 58, 58)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnSave))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addComponent(btnInportXML))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnExport)))
.addGap(28, 28, 28))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtRollNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(btnSave)))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtFullName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18))
.addComponent(btnInportXML, javax.swing.GroupLayout.Alignment.TRAILING))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(29, 29, 29)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(cbGender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(12, 12, 12)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExport))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
btlStudent.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Roll No", "Full Name", "Gender", "Address"
}
));
jScrollPane2.setViewportView(btlStudent);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
pack();
}// </editor-fold>
private void cbGenderActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String RollNo = txtRollNo.getText();
String FullName = txtFullName.getText();
String Gender =cbGender.getSelectedItem().toString();
String Address = txtAddress.getText();
if(RollNo.isEmpty() || FullName.isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "RollNo is empty || FullName is empty?");
return;
}
for (Student student : studentList) {
if(student.getRollNo().equalsIgnoreCase(RollNo)) {
JOptionPane.showMessageDialog(rootPane, "RollNo existed!!!");
return;
}
}
Student std = new Student(RollNo, FullName, Gender, Address);
studentList.add(std);
tableModel.addRow(new Object[] {RollNo, FullName, Gender, Address});
}
private void btnExportActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
StringBuilder builder = new StringBuilder();
for (Student student : studentList) {
builder.append(student.getXMLString());
}
String body = builder.toString();
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<studentList>\n"
+ body+
"\n</studentList>";
//save into file student.xml
FileOutputStream fos = null;
try {
fos = new FileOutputStream("student.xml");
byte[] data = xml.getBytes();
fos.write(data);
} catch(Exception e) {
e.printStackTrace();
} finally {
if(fos != null) {
try {
fos.close();
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
JOptionPane.showMessageDialog(rootPane, "Save success!!!");
}
private void btnInportXMLActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
FileInputStream fis = null;
try {
// TODO add your handling code here:
fis = new FileInputStream("student.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
StudentHandler handler = new StudentHandler();
parser.parse(fis, handler);
studentList = handler.getStudentList();
tableModel.setRowCount(0);
for (Student student : studentList) {
tableModel.addRow(new Object[] {
student.getRollNo(), student.getFullname(),
student.getGender(), student.getAddress()
});
}
} catch (FileNotFoundException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fis.close();
} catch (IOException ex) {
Logger.getLogger(StudentFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
JOptionPane.showMessageDialog(rootPane, "Import success!!!");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StudentFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StudentFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable btlStudent;
private javax.swing.JButton btnExport;
private javax.swing.JButton btnInportXML;
private javax.swing.JButton btnSave;
private javax.swing.JComboBox<String> cbGender;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtAddress;
private javax.swing.JTextField txtFullName;
private javax.swing.JTextField txtRollNo;
// End of variables declaration
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lesson2;
/**
*
* @author HOME
*/
public class Student {
String rollNo, fullname, gender, address;
public Student() {
}
public Student(String rollNo, String fullname, String gender, String address) {
this.rollNo = rollNo;
this.fullname = fullname;
this.gender = gender;
this.address = address;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" + "rollNo=" + rollNo + ", fullname=" + fullname + ", gender=" + gender + ", address=" + address + '}';
}
public String getXMLString() {
return "<student>\n" +
" <rollNo>"+rollNo+"</rollNo>\n" +
" <fullname>"+fullname+"</fullname>\n" +
" <gender>"+gender+"</gender>\n" +
" <address>"+address+"</address>\n" +
" </student>";
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package lesson2;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author HOME
*/
public class StudentHandler extends DefaultHandler{
List<Student> studentList = new ArrayList<>();
Student currentStudent = null;
boolean isRollNo = false, isFullname = false, isGender = false, isAddress = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(qName.equalsIgnoreCase("student")) {
currentStudent = new Student();
} else if(qName.equalsIgnoreCase("rollNo")) {
isRollNo = true;
} else if(qName.equalsIgnoreCase("fullname")) {
isFullname = true;
} else if(qName.equalsIgnoreCase("gender")) {
isGender = true;
} else if(qName.equalsIgnoreCase("address")) {
isAddress = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("student")) {
studentList.add(currentStudent);
currentStudent = null;
} else if(qName.equalsIgnoreCase("rollNo")) {
isRollNo = false;
} else if(qName.equalsIgnoreCase("fullname")) {
isFullname = false;
} else if(qName.equalsIgnoreCase("gender")) {
isGender = false;
} else if(qName.equalsIgnoreCase("address")) {
isAddress = false;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String value = new String(ch, start, length);
if(isRollNo) {
currentStudent.setRollNo(value);
} else if(isFullname) {
currentStudent.setFullname(value);
} else if(isGender) {
currentStudent.setGender(value);
} else if(isAddress) {
currentStudent.setAddress(value);
}
}
public List<Student> getStudentList() {
return studentList;
}
}