基於java利用JDOM讀取XML檔案實現簡單留言簿程式

來源:互聯網
上載者:User
JDOM.javapackage Ex_5;import java.io.FileWriter;import java.io.IOException;import java.util.List;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;@SuppressWarnings("unused")public class JDOM {private Document docwriter,docreader;static private Element root = new Element("留言列表");private Element rootReader;public Element getRoot(){return this.rootReader;}public Document getDoc(){return this.docreader;}private SAXBuilder builder;public JDOM() throws Exception{builder = new SAXBuilder();docwriter = new Document();docwriter.setRootElement(root);}public void JDOMWriter() throws Exception{JDOMReader();List<?> list = rootReader.getChildren();int size = list.size();if(size>0){for(int i = 0;i<list.size();i++){String []data = new String[5];Element message = (Element)list.get(i);data[0] = message.getAttributeValue("編號");data[1] = ((Element)message.getChildren().get(0)).getValue();data[2] = ((Element)message.getChildren().get(1)).getValue();data[3] = ((Element)message.getChildren().get(2)).getValue();data[4] = ((Element)message.getChildren().get(3)).getValue();addData(data[0],data[1],data[2],data[3],data[4]);//Form.tableModel.addRow(data);}return;}//Element stu = new Element("留言");//stu.setAttribute("編號", "1");//Element title = new Element("標題");//title.addContent("今晚有約");//stu.addContent(title);//Element date = new Element("日期");//date.addContent("2009-08-09");//stu.addContent(date);//Element name = new Element("留言人");//name.addContent("張軍");//stu.addContent(name);//Element content = new Element("內容");//content.addContent("到電影院看電影");//stu.addContent(content);//root.addContent(stu);//Element stu2 = new Element("留言");//stu2.setAttribute("編號", "2");//Element title2 = new Element("標題");//title2.addContent("家庭作業");//stu2.addContent(title2);//Element date2 = new Element("日期");//date2.addContent("2009-08-10");//stu2.addContent(date2);//Element name2 = new Element("留言人");//name2.addContent("張軍");//stu2.addContent(name2);//Element content2 = new Element("內容");//content2.addContent("編程實現一個留言管理系統。增加、修改、刪除、查閱留言功能");//stu2.addContent(content2);//root.addContent(stu2);//XMLOutputter outputter = new XMLOutputter();//Format format = outputter.getFormat();//format.setEncoding("GB2312");//format.setIndent("  ");//outputter.setFormat(format);//outputter.output(docwriter, new FileWriter(".\\myxml.xml"));}public void JDOMReader() throws Exception{docreader = builder.build(".\\myxml.xml");rootReader = docreader.getRootElement();}public void delData(String id) throws Exception{JDOMReader();List<?> list1 = rootReader.getChildren();for(int i = 0;i<list1.size();i++){int tmp = Integer.parseInt(id);System.out.println(tmp);Element message = (Element)list1.get(i);if(message.getAttributeValue("編號").equals(id)){System.out.println(message.getValue());rootReader.removeContent(message);}}XMLOutputter outputter = new XMLOutputter();Format format = outputter.getFormat();format.setEncoding("GB2312");format.setIndent("  ");outputter.setFormat(format);outputter.output(docreader, new FileWriter(".\\myxml.xml"));}public void addData(String id,String title,String date,String name,String content) throws Exception{Element stu = new Element("留言");stu.setAttribute("編號", id);Element title1 = new Element("標題");title1.addContent(title);stu.addContent(title1);Element date1 = new Element("日期");date1.addContent(date);stu.addContent(date1);Element name1 = new Element("留言人");name1.addContent(name);stu.addContent(name1);Element content1 = new Element("內容");content1.addContent(content);stu.addContent(content1);root.addContent(stu);XMLOutputter outputter = new XMLOutputter();Format format = outputter.getFormat();format.setEncoding("GB2312");format.setIndent("  ");outputter.setFormat(format);outputter.output(docwriter, new FileWriter(".\\myxml.xml"));}public void selectData(int i){switch(i){case 1:break;case 2:break;case 3:break;default:break;}}}

Form.javapackage Ex_5;import java.awt.Color;import javax.swing.*;import javax.swing.table.DefaultTableCellRenderer;import javax.swing.table.DefaultTableModel;import javax.swing.table.TableColumn;import javax.swing.table.TableColumnModel;import javax.swing.table.TableModel;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.List;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import org.jdom.Document;import org.jdom.Element;import org.jdom.JDOMException;import org.jdom.input.SAXBuilder;import org.jdom.output.Format;import org.jdom.output.XMLOutputter;@SuppressWarnings({ "unused", "serial" })public class Form extends JFrame{private static final int DISPOSE_ON_CLOSE = 0;private JFrame f;private JScrollPane tablePanel;private JLabel person,title,content,date;private JTextField perTxt,titleTxt,contentTxt,dateTxt;private JButton addBtn,delBtn,updBtn,selBtn;static public JTable table;static public DefaultTableModel tableModel;private JDOM jdom;static public int i = 1;private List<?> list;public void addListener() {// TODO Auto-generated method stubselBtn.addMouseListener(new MouseListener(){@Overridepublic void mouseClicked(MouseEvent arg0) {// TODO Auto-generated method stubtry {select();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void mouseEntered(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent arg0) {// TODO Auto-generated method stub}});addBtn.addMouseListener(new MouseListener(){@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stubtry {jdom.JDOMReader();} catch (Exception e3) {// TODO Auto-generated catch blocke3.printStackTrace();}list = jdom.getRoot().getChildren();int id = list.size()+1;try {jdom.addData(String.valueOf(id), titleTxt.getText(), dateTxt.getText(), perTxt.getText(), contentTxt.getText());} catch (Exception e2) {// TODO Auto-generated catch blocke2.printStackTrace();}try {update();} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}perTxt.setText("");titleTxt.setText("");contentTxt.setText("");}@Overridepublic void mousePressed(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}});updBtn.addMouseListener(new MouseListener(){@Overridepublic void mouseClicked(MouseEvent arg0) {// TODO Auto-generated method stubtableModel.setRowCount(0);try {update();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void mouseEntered(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent arg0) {// TODO Auto-generated method stub}});table.addMouseListener(new MouseListener(){@Overridepublic void mouseClicked(MouseEvent arg0) {// TODO Auto-generated method stubint row = table.getSelectedRow();if(row>=0){String str0 = table.getValueAt(row, 0).toString(); String str1 = table.getValueAt(row, 1).toString(); String str2 = table.getValueAt(row, 2).toString();String str3 = table.getValueAt(row, 3).toString(); String str4 = table.getValueAt(row, 4).toString();perTxt.setText(str3);titleTxt.setText(str1);contentTxt.setText(str4);}}@Overridepublic void mouseEntered(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent arg0) {// TODO Auto-generated method stub}});delBtn.addMouseListener(new MouseListener(){@Overridepublic void mouseClicked(MouseEvent arg0) {// TODO Auto-generated method stubint sel = table.getSelectedRow();//int sel = table.getSelectedColumn();TableColumnModel tcm = table.getColumnModel();try {jdom.JDOMReader();list = jdom.getRoot().getChildren();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}if(list.size()>0 && sel>=0){String first = (String) tableModel.getValueAt(sel, 0);try {jdom.delData(first);//update();tableModel.removeRow(sel);//jdom.JDOMWriter();update();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}//((JTable) tcm).sizeColumnsToFit(-1);perTxt.setText("");//dateTxt.setText("");titleTxt.setText("");contentTxt.setText("");}else{return;}}@Overridepublic void mouseEntered(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent arg0) {// TODO Auto-generated method stub}});}public void update() throws Exception{tableModel.setRowCount(0);// 清除原有行//jdom.JDOMWriter();jdom.JDOMReader();list = jdom.getRoot().getChildren();for(int i = 0;i<list.size();i++){String []data = new String[5];Element message = (Element)list.get(i);data[0] = message.getAttributeValue("編號");data[1] = ((Element)message.getChildren().get(0)).getValue();data[2] = ((Element)message.getChildren().get(1)).getValue();data[3] = ((Element)message.getChildren().get(2)).getValue();data[4] = ((Element)message.getChildren().get(3)).getValue();tableModel.addRow(data);}}public void select() throws Exception{//tableModel.setRowCount(0);// 清除原有行//jdom.JDOMWriter();jdom.JDOMReader();list = jdom.getRoot().getChildren();tableModel.setRowCount(0);for(int i = 0;i<list.size();i++){String []data = new String[5];Element message = (Element)list.get(i);data[0] = message.getAttributeValue("編號");data[1] = ((Element)message.getChildren().get(0)).getValue();data[2] = ((Element)message.getChildren().get(1)).getValue();data[3] = ((Element)message.getChildren().get(2)).getValue();data[4] = ((Element)message.getChildren().get(3)).getValue();String _title = titleTxt.getText();String _name = perTxt.getText();String _content = contentTxt.getText();if((_title.equals(data[1]))||(_name.equals(data[3]))||(_content.equals(data[4]))){tableModel.addRow(data);perTxt.setText(data[3]);titleTxt.setText(data[1]);contentTxt.setText(data[4]);}}}//@SuppressWarnings("static-access")public void init() throws Exception {// TODO Auto-generated method stubf = new JFrame("留言資訊綜合查詢系統");f.setLayout(null);f.setBackground(Color.BLUE);//f.setLocationRelativeTo(null);person = new JLabel("留言人");person.setBounds(64,14,52,14);perTxt = new JTextField();perTxt.setBounds(120, 13, 140, 20);title = new JLabel("標題");title.setBounds(270, 14, 40, 14);titleTxt = new JTextField();titleTxt.setBounds(315, 13, 210, 20);content = new JLabel("內容");content.setBounds(64, 50, 162, 14);contentTxt = new JTextField();contentTxt.setBounds(120, 48, 340, 20);addBtn = new JButton("增加");addBtn.setBounds(470, 46, 70, 25);delBtn = new JButton("刪除");delBtn.setBounds(150, 320, 70, 25);updBtn = new JButton("更新");updBtn.setBounds(230, 320, 70, 25);date = new JLabel("日期");date.setBounds(310, 325, 50, 14);dateTxt = new JTextField();dateTxt.setBounds(340, 323, 140, 20);Calendar cal = Calendar.getInstance();SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");System.out.println(sdf.format(cal.getTime()));dateTxt.setText(sdf.format(cal.getTime()));dateTxt.setEditable(false);selBtn = new JButton("查詢");selBtn.setBounds(490, 320, 70, 25);table = new JTable(new DefaultTableModel(new Object[][] { {"編號","標題","日期","留言人","內容"} },new String[]{"編號","標題","日期","留言人","內容"}));//table.addColumn(aColumn);//table.setBounds(20, 80, 555, 200);table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //單選           table.setSelectionBackground(Color.YELLOW);          table.setSelectionForeground(Color.RED);tableModel = (DefaultTableModel) table.getModel();tablePanel = new JScrollPane(table);tablePanel.setBounds(20, 80, 555, 200);table.setFillsViewportHeight(true);tablePanel.setViewportView(table); //支援滾動update();f.add(person);f.add(perTxt);f.add(title);f.add(titleTxt);f.add(content);f.add(contentTxt);f.add(addBtn);f.add(delBtn);f.add(updBtn);f.add(date);f.add(dateTxt);f.add(selBtn);f.add(tablePanel);f.addWindowListener(new WindowListener(){@Overridepublic void windowActivated(WindowEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void windowClosed(WindowEvent arg0) {// TODO Auto-generated method stubSystem.exit(0);}@Overridepublic void windowClosing(WindowEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void windowDeactivated(WindowEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void windowDeiconified(WindowEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void windowIconified(WindowEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void windowOpened(WindowEvent arg0) {// TODO Auto-generated method stub}});//this.setLocationRelativeTo(f); ///簡單的置中f.setResizable(false);f.setSize(600, 400);f.setVisible(true);}public Form() throws Exception{jdom = new JDOM();this.setLocationRelativeTo(null);this.init();this.addListener();jdom.JDOMWriter();}}

Test.javapackage Ex_5;public class Test {/** * @param args * @throws Exception  */@SuppressWarnings("unused")public static void main(String[] args) throws Exception {// TODO Auto-generated method stubForm form = new Form();}}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.