[英]Build GUI in swing using XML file
我正在尋找一種使用XML和swing構建UI的方法。 我有一個XML代碼,正在尋找一種使用swing使其脫離UI的方法。 我試過下面的Java代碼,但是我不確定這是否可以幫助我顯示框架和其他組件。
請幫忙。
下面是XML代碼,其中包含JFrame和我想要在UI中提供的其他功能。 我想從Java代碼中調用此文件,以便可以顯示我用XML編寫的所有內容。
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_161" class="java.beans.XMLDecoder">
<object class="javax.swing.JFrame">
<void property="size">
<object class="java.awt.Dimension">
<int>208</int>
<int>87</int>
</object>
</void>
<void property="contentPane">
<void method="add">
<object id="JLabel0" class="javax.swing.JLabel">
<void property="text">
<string>Hello1</string>
</void>
</object>
</void>
<void method="add">
<object id="JButton0" class="javax.swing.JButton">
<string>Hello2</string>
</object>
</void>
<void property="layout">
<object class="java.awt.BorderLayout">
<void method="addLayoutComponent">
<object idref="JButton0"/>
<string>South</string>
</void>
<void method="addLayoutComponent">
<object idref="JLabel0"/>
<string>Center</string>
</void>
</object>
</void>
</void>
<void property="name">
<string>frame0</string>
</void>
<void property="title">
<string>Save/Load View</string>
</void>
<void property="visible">
<boolean>true</boolean>
</void>
</object>
</java>
以下是Java代碼:
import javax.swing.*;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import java.awt.*;
import java.awt.event.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class MasterScreen{
public static void main (String argv []){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("MasterXML.xml"));
System.out.println("Siri");
doc.getDocumentElement ().normalize ();
System.out.println("Siriri");
}
catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
}
}
您的XML文件顯然是使用java.beans.XMLEncoder
從JFrame
對象生成的。
因此,對該XML文件進行解碼以生成原始對象非常簡單。 像這樣使用java.beans.XMLDecoder
:
public class Main {
public static void main(String[] args) throws IOException {
XMLDecoder xmlDecoder = new XMLDecoder(new FileInputStream("MasterXML.xml"));
Object frame = xmlDecoder.readObject();
xmlDecoder.close();
}
}
您無需像使用DocumentBuilder
那樣麻煩進行低級XML解析-
運行上面的代碼時,此JFrame
將顯示:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.