(一)添加IP配置对话框
用SWT新建一个对话框类,在原来文件类的按钮响应事件中添加如下代码
// CANVAS中鼠标事件 canvas.addMouseListener(new MouseAdapter() { // 鼠标释放 public void mouseUp(final MouseEvent e) { Dlg_IPCONFIG dlg = new Dlg_IPCONFIG(shell); dlg.open(); } });
对话框类代码如下:
import operate.file.xml.IpConfig; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import com.swtdesigner.SWTResourceManager; public class Dlg_IPCONFIG extends Dialog { private Text Text_port; private Text Text_ip; private String strIp=""; private String strPort=""; protected Object result; protected Shell shell; // 文本修改标记 private boolean ModifiedFlag = false; /** * Create the dialog * * @param parent * @param style */ public Dlg_IPCONFIG(Shell parent, int style) { super(parent, style); } /** * Create the dialog * * @param parent */ public Dlg_IPCONFIG(Shell parent) { this(parent, SWT.NONE); } /** * Open the dialog * * @return the result */ public Object open() { createContents(); shell.open(); shell.layout(); Display display = getParent().getDisplay(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return result; } /** * Create contents of the dialog */ protected void createContents() { shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); // 取屏幕大小 Rectangle src_area = Display.getDefault().getClientArea(); // 使窗口居中显示 shell.setLocation((src_area.width - 242) / 2, (src_area.height - 143) / 2); shell.setSize(242, 143); shell.setText("IP CONFIG"); /* 创建"IP"标签 */ final Label Lab_ip = new Label(shell, SWT.CENTER); Lab_ip.setFont(SWTResourceManager.getFont("", 12, SWT.NONE)); Lab_ip.setAlignment(SWT.CENTER); Lab_ip.setText("IP:"); Lab_ip.setBounds(15, 17, 37, 22); /* 创建"IP"文本框 */ Text_ip = new Text(shell, SWT.BORDER); // 输入事件,限制输入为IP格式文本 Text_ip.addKeyListener(new KeyAdapter() { public void keyPressed(final KeyEvent e) { // 不允许复制操作 if (e.keyCode == 118) { e.doit = false; return; } ModifiedFlag=true; shell.setText("IP CONFIG *"); String ipText = Text_ip.getText(); char ch = e.character; // 不允许存在4个'.'及两点间不为空 if (ch == '.') { int n = ipText.length(); if ((n > 1) && (ipText.charAt(n - 1) == '.')) { e.doit = false; return; } String[] segments = ipText.split("//."); if (segments.length >= 4) { e.doit = false; return; } } else { // 只允许输入数字,退格键,左右箭头 if (Character.isLetter(ch)) { e.doit = false; return; } } } }); Text_ip.setFont(SWTResourceManager.getFont("", 12, SWT.NONE)); Text_ip.setBounds(65, 15, 132, 22); /* 创建"PORT"标签 */ final Label Lab_port = new Label(shell, SWT.NONE); Lab_port.setFont(SWTResourceManager.getFont("", 12, SWT.NONE)); Lab_port.setText("PORT:"); Lab_port.setBounds(15, 53, 37, 22); /* 创建"PORT"文本框 */ Text_port = new Text(shell, SWT.BORDER); Text_port.addKeyListener(new KeyAdapter() { public void keyPressed(final KeyEvent e) { ModifiedFlag=true; shell.setText("IP CONFIG *"); } }); Text_port.setFont(SWTResourceManager.getFont("", 12, SWT.NONE)); Text_port.setBounds(65, 50, 71, 22); /* 创建"确定"按钮 */ final Button Btn_ok = new Button(shell, SWT.NONE); Btn_ok.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent e) { //没做修改,马上返回 if(ModifiedFlag==false)return; //修改 else{ try { final IpConfig xmlfile = new IpConfig("Res//config.xml"); xmlfile.readXMLFile(); xmlfile.updateXMLFile("IP",Text_ip.getText()); strIp=Text_ip.getText(); xmlfile.updateXMLFile("PORT",Text_port.getText()); strPort=Text_port.getText(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } ModifiedFlag=false; shell.setText("IP CONFIG"); } } }); Btn_ok.setText("确定"); Btn_ok.setBounds(110, 85, 48, 22); /* 创建"取消"按钮 */ final Button Btn_cancel = new Button(shell, SWT.NONE); Btn_cancel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent e) { if (ModifiedFlag) { MessageBox mb = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL); mb.setText("提示"); mb.setMessage("未保存,确定要关闭吗?"); int rc = mb.open(); if (e.doit == (rc == SWT.CANCEL)) { // 选择取消,返回IPCONFIG对话框 return; } } // 做窗口关闭事件 shell.close(); } }); Btn_cancel.setText("取消"); Btn_cancel.setBounds(171, 85, 48, 22); /* 读XML文件,初始化显示 */ try { final IpConfig xmlfile = new IpConfig("Res//config.xml"); xmlfile.readXMLFile(); strIp=xmlfile.getIpAddr(); strPort=String.valueOf(xmlfile.getNumPort()); Text_ip.setText(strIp); Text_port.setText(strPort); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
(二)读写XML文件,代码如下:
package operate.file.xml; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.Node; public class IpConfig { private String ipAddr; private int numPort; DocumentBuilderFactory dbf = null; DocumentBuilder db = null; Document doc = null; //XML完整路径名 String xmlPathFile=null; public String getIpAddr() { return ipAddr; } public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr; } public int getNumPort() { return numPort; } public void setNumPort(int numPort) { this.numPort = numPort; } public IpConfig(String xFile) throws Exception { /* 为解析XML作准备 */ // 创建DocumentBuilderFactory实例,指定DocumentBuilder xmlPathFile=xFile; dbf = DocumentBuilderFactory.newInstance(); try { db = dbf.newDocumentBuilder(); doc = db.parse(xFile); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /**写入XML文件中 filename:XML文件完整路径名 写入失败时返回false*/ public boolean doc2XmlFile(String filename) { boolean flag = true; try { /* 将document中的内容写入文件中 */ TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); /** 编码 */ //transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filename)); transformer.transform(source, result); } catch (Exception ex) { flag = false; ex.printStackTrace(); } return flag; } public void readXMLFile() { /* 下面是解析XML全过程 */ // 先取得根元素 Element root = doc.getDocumentElement(); // 取"IPCONFIG"元素列表 NodeList ipConfigs = root.getElementsByTagName("IPCONFIG"); // 取"IPCONFIG"元素 for (int i = 0; i < ipConfigs.getLength(); i++) { Element ipConfig = (Element) ipConfigs.item(i); // 赋值 NodeList ipAddrList = ipConfig.getElementsByTagName("IP"); if (ipAddrList.getLength() == 1) { Element e = (Element) ipAddrList.item(0); Text t = (Text) e.getFirstChild(); ipAddr = t.getNodeValue(); } NodeList numPortList = ipConfig.getElementsByTagName("PORT"); if (numPortList.getLength() == 1) { Element e = (Element) numPortList.item(0); Text t = (Text) e.getFirstChild(); numPort = Integer.parseInt(t.getNodeValue()); } } } // elemTarNode:目标元素 // strNew:新数据 public void updateXMLFile(String strTarNode, String strNew) { /* 下面是更新XML全过程 */ // 先取得根元素 Element root = doc.getDocumentElement(); // 下面对特定元素进行修改 /** 如果root有子元素 */ if (root.hasChildNodes()) { NodeList ipConfigNodes = root.getChildNodes(); /** 循环取得IPCONFIGS所有节点 */ for (int i = 0; i < ipConfigNodes.getLength(); i++) { NodeList ipConfiglist = ipConfigNodes.item(i).getChildNodes(); for (int k = 0; k < ipConfiglist.getLength(); k++) { Node subnode = ipConfiglist.item(k); /** 修改值为 strNew */ if (subnode.getNodeType() == Node.ELEMENT_NODE && subnode.getNodeName() == strTarNode) { subnode.getFirstChild().setNodeValue(strNew); } } } } doc2XmlFile(xmlPathFile); } /*类结尾括号*/ }
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
QQ咨询|关于我们|Archiver|手机版|小黑屋|( 辽ICP备15012455号-4 ) Powered by 期权论坛 X3.2 © 2001-2016 期权工具网&期权论坛 Inc.
下载期权论坛手机APP