一、描述
开发一个MyFrame窗体应用程序,该窗体继承JFrame类,窗体中的标题、按钮上的文字等信息都可以写在一个xml配置文件中,即使以后想更改所有的属性,只需要更改xml配置文件中的相应属性即可。
本案例使用java中的Properties类来加载一个xml配置文件,并读取文件中的所有属性(key-value),并将取得的所有键值对应用于JFrame窗体属性中。
二、源代码
package tong.day4_27.systemUse;
import java.awt.FlowLayout;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JFrame;
class MyFrame extends JFrame{
//在构造方法中获取Properties对象中的每一个属性,并把属性使用到窗体属性上
public MyFrame(Properties properties) {
String title = properties.getProperty("title");
String buttonOK = properties.getProperty("buttonOK");
String buttonCancel = properties.getProperty("buttonCancel");
//设置窗体标题
setTitle(title);
setLayout(new FlowLayout());
//创建两个按钮,上面的文字就是xml配置文件中的文字
JButton btnOK = new JButton(buttonOK);
JButton btnCancel = new JButton(buttonCancel);
add(btnOK);
add(btnCancel);
setBounds(200, 100, 300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
class UseOfProperties{
private Properties properties ;
//在构造方法中创建 Properties对象,并调用加载xml文件的函数loadXMLFile()
public UseOfProperties(){
properties = new Properties();
loadXMLFile();
}
public Properties getProperties() {
return properties;
}
//使用java中的IO流加载文件,这里使用高效的BufferedReader流加载xml文件,将文件中配置的属性使用到窗体中的属性上
private void loadXMLFile() {
//使用BufferedReader读取xml文件中的属性
BufferedReader bufferedReader = null;
try {
//该配置文件放在d盘根目录下,当然也可以放在eclipse中该项目的根目录下
bufferedReader = new BufferedReader(new FileReader("d:\\property.xml"));
//使用Properties对象的load()方法加载文件
properties.load(bufferedReader);
} catch (FileNotFoundException e) {
System.out.println("文件未找到!");
e.printStackTrace();
}catch (IOException e) {
System.out.println("文件载入失败!");
}finally{
//关闭BufferedReader流,释放资源
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class SetPropertyByXML {
/**
* @param args
*/
public static void main(String[] args) {
//创建UseOfProperties对象则会调用构造方法,并把最终获取的Properties属性列表传入MyFrame()构造方法中
UseOfProperties useOfProperties = new UseOfProperties();
MyFrame myFrame = new MyFrame(useOfProperties.getProperties());
}
}
1、property.xml文件放在了d盘根目录下,这里可以根据需要放在项目根目录下或者其它位置,对应要修改代码中BufferedReader中加载文件的目录即可
property.xml文件内容(这是多个键值对):
title=通过xml文件获取窗口属性
buttonOK=确定
buttonCancel=取消
2、运行结果