java中使用Properties加载XML文件设置java窗体应用程序的窗体属性

一、描述

开发一个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、运行结果

Properties使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值