swing開發一個修改項目數據庫鏈接參數配置文件

咱們在開發web項目中,常常有properties配置文件配置數據庫鏈接參數,每次修改的時候還要去找到配置文件,感受有點麻煩,就用swing作了個小工具修改參數,運行界面以下:java

==============================================================mysql

1、項目結構:web

2、相關代碼:sql

  一、ConfigTools.java  數據庫

package com.xie.main;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;

import com.xie.util.PropertiesUtils;
import javax.swing.JTabbedPane;
import java.awt.Dimension;

import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

@SuppressWarnings("serial")
public class ConfigTools extends JFrame {
    
    private static Properties properties;    
    // 配置文件路徑
    private static String CONFIG_PATH = "resource/config-path.properties";
    
    private static String TITLE_IMG;        //圖片
    private static String DB_CONFIG;        //數據庫
    private static Map<String, String> dataconf;

    private JPanel contentPane;
    private JTabbedPane tabbedPane;
    private JPanel panel_data;
    private JComboBox<String> datatypeValue;
    private JTextField dataurlValue;
    private JTextField usernameValue;
    private JPasswordField passwordValue;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    getAllConfPath();
                    getDbConf();
                    ConfigTools frame = new ConfigTools();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    
    /**
     * 讀取配置文件路徑
     * 配置文件:config-path.properties
     */
    private static void getAllConfPath() {
        properties = PropertiesUtils.getProperty(CONFIG_PATH);
        TITLE_IMG = properties.getProperty("img.path");
        DB_CONFIG = properties.getProperty("db.path");
    }
    
    
    /**
     * 讀取數據源
     * 數據源配置文件:config.properties
     */
    public static void getDbConf(){
        dataconf = new HashMap<String, String>();
        Properties properties= PropertiesUtils.getProperty(DB_CONFIG);
        dataconf.put("db_type", properties.getProperty("db.db_type"));
        dataconf.put("db_url", properties.getProperty("db.url"));
        dataconf.put("db_username", properties.getProperty("db.username"));
        dataconf.put("db_password", properties.getProperty("db.password"));
    }
    
    
    /**
     * Create the frame.
     */
    public ConfigTools() {
        setTitle("\u914D\u7F6E\u6587\u4EF6\u4FEE\u6539\u5DE5\u5177");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 775, 550);
        // 設置窗體最小值
        setMinimumSize(new Dimension(775, 550));
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout(0, 0));
        
        // 居中顯示
        Toolkit kit = Toolkit.getDefaultToolkit(); // 定義工具包 
        Dimension screenSize = kit.getScreenSize(); // 獲取屏幕的尺寸 
        int screenWidth = screenSize.width/2; // 獲取屏幕的寬
        int screenHeight = screenSize.height/2; // 獲取屏幕的高
        int height = this.getHeight(); 
        int width = this.getWidth(); 
        setLocation(screenWidth-width/2, screenHeight-height/2);
        
        /**
         * 頭部
         */
        //==================================開始======================================//
        String path = TITLE_IMG;
        ImageIcon image = new ImageIcon(path);
        JLabel labImage = new JLabel(image);
        
        JPanel panel_title = new JPanel();
        panel_title.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        contentPane.add(panel_title, BorderLayout.NORTH);
        
        panel_title.add(labImage);
        
        //==================================結束======================================//
        
        
        
        /**
         * 左邊菜單
         */
        //==================================開始======================================//
        JPanel panel_left = new JPanel();
        panel_left.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        contentPane.add(panel_left, BorderLayout.WEST);
        
        JButton db_button = new JButton("\u6570 \u636E \u914D \u7F6E");        
        db_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tabbedPane.setSelectedIndex(0);
            }
        });
        JButton finish_button = new JButton("\u5B8C \u6210 \u914D \u7F6E");
        finish_button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tabbedPane.setSelectedIndex(1);
            }
        });
        
        GroupLayout gl_panel_left = new GroupLayout(panel_left);
        gl_panel_left.setHorizontalGroup(
            gl_panel_left.createParallelGroup(Alignment.TRAILING)
                .addGroup(Alignment.LEADING, gl_panel_left.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(db_button)
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(gl_panel_left.createSequentialGroup()
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(finish_button, GroupLayout.PREFERRED_SIZE, 99, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
        );
        gl_panel_left.setVerticalGroup(
            gl_panel_left.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_left.createSequentialGroup()
                    .addGap(54)
                    .addComponent(db_button)
                    .addGap(18)
                    .addComponent(finish_button)
                    .addContainerGap(364, Short.MAX_VALUE))
        );
        panel_left.setLayout(gl_panel_left);
        
        JPanel panel_centre = new JPanel();
        panel_centre.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        contentPane.add(panel_centre, BorderLayout.CENTER);
        //==================================結束======================================//
        
        

        /**
         * 中間內容
         */
        //==================================開始======================================//
        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        GroupLayout gl_panel_centre = new GroupLayout(panel_centre);
        gl_panel_centre.setHorizontalGroup(
            gl_panel_centre.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_panel_centre.createSequentialGroup()
                .addContainerGap()
                .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)
                .addContainerGap())
        );
        gl_panel_centre.setVerticalGroup(
            gl_panel_centre.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_panel_centre.createSequentialGroup()
                .addContainerGap()
                .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                .addContainerGap())
        );
        /**
         * 數據庫配置
         */
        //==================================開始======================================//
        panel_data = new JPanel();
        panel_data.setToolTipText("");
        tabbedPane.addTab("\u6570\u636E\u914D\u7F6E", null, panel_data, null);
        
        JPanel panel_data_parameter = new JPanel();
        panel_data_parameter.setBorder(new TitledBorder(null, "\u8FDE\u63A5\u53C2\u6570\u914D\u7F6E", TitledBorder.LEADING, TitledBorder.TOP, null, null));
            
        
        JLabel datatype = new JLabel("\u6570\u636E\u5E93\u7C7B\u578B\uFF1A");        
        JLabel dataurl = new JLabel("\u8FDE\u63A5\u5730\u5740\uFF1A");
        JLabel username = new JLabel("\u7528 \u6237 \u540D\uFF1A");
        JLabel password = new JLabel("\u5BC6    \u7801\uFF1A");        
        
        datatypeValue = new JComboBox<String>();
        datatypeValue.setEnabled(false);
        // 讀取當前配置寫入輸入框(數據庫類型)
        datatypeValue.addItem(dataconf.get("db_type"));
        
        dataurlValue = new JTextField();
        dataurlValue.setEnabled(false);
        dataurlValue.setColumns(10);
        // 讀取當前配置寫入輸入框(URL)
        dataurlValue.setText(dataconf.get("db_url"));        
        
        usernameValue = new JTextField();
        usernameValue.setEnabled(false);
        usernameValue.setColumns(10);
        // 讀取當前配置寫入輸入框(用戶名)
        usernameValue.setText(dataconf.get("db_username"));
        
        passwordValue = new JPasswordField();
        passwordValue.setEnabled(false);
        // 讀取當前配置寫入輸入框(密碼)
        passwordValue.setText(dataconf.get("db_password"));
        
        GroupLayout gl_panel_data_parameter = new GroupLayout(panel_data_parameter);
        gl_panel_data_parameter.setHorizontalGroup(
            gl_panel_data_parameter.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_data_parameter.createSequentialGroup()
                .addGap(20)
                .addGroup(gl_panel_data_parameter.createParallelGroup(Alignment.LEADING)
                .addComponent(datatype)
                .addComponent(password)
                .addComponent(dataurl)
                .addComponent(username))
                .addGap(41)
                .addGroup(gl_panel_data_parameter.createParallelGroup(Alignment.TRAILING)
                .addComponent(passwordValue, GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                .addComponent(usernameValue, GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                .addComponent(dataurlValue, GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                .addComponent(datatypeValue, Alignment.LEADING, 0, 361, Short.MAX_VALUE))
                .addGap(71))
        );
        gl_panel_data_parameter.setVerticalGroup(
            gl_panel_data_parameter.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_data_parameter.createSequentialGroup()
                .addContainerGap()
                .addGroup(gl_panel_data_parameter.createParallelGroup(Alignment.BASELINE)
                .addComponent(datatype)
                .addComponent(datatypeValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18)
                .addGroup(gl_panel_data_parameter.createParallelGroup(Alignment.BASELINE)
                .addComponent(dataurlValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addComponent(dataurl))
                .addGap(21)
                .addGroup(gl_panel_data_parameter.createParallelGroup(Alignment.BASELINE)
                .addComponent(usernameValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addComponent(username))
                .addGap(18)
                .addGroup(gl_panel_data_parameter.createParallelGroup(Alignment.BASELINE)
                .addComponent(password)
                .addComponent(passwordValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(88, Short.MAX_VALUE))
        );
        
        //==============================================================//
        /**
         * 點擊編輯按鈕,輸入框能夠編輯
         */
        JButton database_edit = new JButton("\u7F16 \u8F91");
        JButton database_save = new JButton("\u4FDD \u5B58");
        database_save.setEnabled(false);
        
        database_edit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                datatypeValue.setEnabled(true);
                datatypeValue.removeAllItems();
                datatypeValue.addItem("oracle");      //oracle數據庫
                datatypeValue.addItem("mysql");       //mysql數據庫
                datatypeValue.addItem("mssql");        //mssql數據庫
                dataurlValue.setEnabled(true);
                usernameValue.setEnabled(true);
                passwordValue.setEnabled(true);
                database_save.setEnabled(true);
            }
        });
        
        /**
         * 點擊保存後,將數據寫入配置文件
         */
        database_save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Map<String, String> data = new HashMap<String, String>();
                String datatype = datatypeValue.getSelectedItem().toString();
                String dataurl = dataurlValue.getText().toString();
                String username = usernameValue.getText().toString();
                String password = new String(passwordValue.getPassword());
                if("".equals(datatype)){
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, "數據庫類型不能爲空!", "提示", JOptionPane.INFORMATION_MESSAGE);
                }else if("".equals(dataurl)){
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, "鏈接地址不能爲空!", "提示", JOptionPane.INFORMATION_MESSAGE);
                }else if("".equals(username)){
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, "用戶名不能爲空!", "提示", JOptionPane.INFORMATION_MESSAGE);
                }else if("".equals(password)){
                    Toolkit.getDefaultToolkit().beep();
                    JOptionPane.showMessageDialog(null, "密碼不能爲空!", "提示", JOptionPane.INFORMATION_MESSAGE);
                }else{
                    data.put("db.db_type", datatype);
                    data.put("db.url", dataurl);
                    data.put("db.username", username);
                    data.put("db.password", new String(password));
                    String msg = PropertiesUtils.setProperty(DB_CONFIG, data);
                    if("true".equals(msg)){
                        Toolkit.getDefaultToolkit().beep();
                        JOptionPane.showMessageDialog(null, "保存成功!", "提示", JOptionPane.PLAIN_MESSAGE);
                    }else{
                        Toolkit.getDefaultToolkit().beep();
                        JOptionPane.showMessageDialog(null, "保存異常!", "提示", JOptionPane.ERROR_MESSAGE);
                    }
                }
                
            }
        });
        //==============================================================//
        
        
        GroupLayout gl_panel_data = new GroupLayout(panel_data);
        gl_panel_data.setHorizontalGroup(
            gl_panel_data.createParallelGroup(Alignment.TRAILING)
                .addGroup(gl_panel_data.createSequentialGroup()
                .addGap(133)
                .addComponent(database_edit, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(ComponentPlacement.RELATED, 142, Short.MAX_VALUE)
                .addComponent(database_save, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)
                .addGap(132))
                .addGroup(gl_panel_data.createSequentialGroup()
                .addGap(20)
                .addComponent(panel_data_parameter, GroupLayout.DEFAULT_SIZE, 577, Short.MAX_VALUE))
        );
        gl_panel_data.setVerticalGroup(
            gl_panel_data.createParallelGroup(Alignment.TRAILING)
                .addGroup(gl_panel_data.createSequentialGroup()
                .addContainerGap()
                .addComponent(panel_data_parameter, GroupLayout.PREFERRED_SIZE, 209, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(ComponentPlacement.RELATED, 159, Short.MAX_VALUE)
                .addGroup(gl_panel_data.createParallelGroup(Alignment.BASELINE)
                .addComponent(database_save)
                .addComponent(database_edit))
                .addGap(32))
        );
        panel_data_parameter.setLayout(gl_panel_data_parameter);
        panel_data.setLayout(gl_panel_data);
        //==================================結束======================================//
        
        
        
        /**
         * 完成配置
         */
        //==================================開始======================================//
        JPanel panel_finish = new JPanel();
        tabbedPane.addTab("\u5B8C\u6210\u914D\u7F6E", null, panel_finish, null);
        
        JButton start = new JButton("\u542F \u52A8");
        
        JPanel panel_finish_parameter = new JPanel();
        panel_finish_parameter.setBorder(new TitledBorder(null, "\u8FD0\u884C\u4FE1\u606F", TitledBorder.LEADING, TitledBorder.TOP, null, null));
        GroupLayout gl_panel_finish = new GroupLayout(panel_finish);
        gl_panel_finish.setHorizontalGroup(
            gl_panel_finish.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_finish.createSequentialGroup()
                .addContainerGap()
                .addGroup(gl_panel_finish.createParallelGroup(Alignment.LEADING)
                .addComponent(panel_finish_parameter, GroupLayout.DEFAULT_SIZE, 577, Short.MAX_VALUE)
                .addComponent(start))
                .addContainerGap())
        );
        gl_panel_finish.setVerticalGroup(
            gl_panel_finish.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_panel_finish.createSequentialGroup()
                .addContainerGap()
                .addComponent(start)
                .addPreferredGap(ComponentPlacement.UNRELATED)
                .addComponent(panel_finish_parameter, GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                .addContainerGap())
        );
        
        JScrollPane scrollPane = new JScrollPane();
        GroupLayout gl_panel_finish_parameter = new GroupLayout(panel_finish_parameter);
        gl_panel_finish_parameter.setHorizontalGroup(
            gl_panel_finish_parameter.createParallelGroup(Alignment.LEADING)
                .addComponent(scrollPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
        );
        gl_panel_finish_parameter.setVerticalGroup(
            gl_panel_finish_parameter.createParallelGroup(Alignment.LEADING)
                .addComponent(scrollPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
        );
        
        JTextArea textArea = new JTextArea();
        scrollPane.setViewportView(textArea);
        panel_finish_parameter.setLayout(gl_panel_finish_parameter);
        panel_finish.setLayout(gl_panel_finish);
        panel_centre.setLayout(gl_panel_centre);
        
        //==================================結束======================================//
        
    }
}
View Code

  二、PropertiesUtils.javaoracle

package com.xie.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;


public class PropertiesUtils {
    
    /**
     * 經過配置文件名獲取配置信息
     * @param fileName
     * @return
     */
    public static Properties getProps(String fileName){
        Properties props = new Properties();
        try {
            // 只須要文件名 dbconfig.properties與resource/dbconfig.properties的區別
            props.load(new InputStreamReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName), "UTF-8")); 
        } catch (IOException e) {
            e.printStackTrace();
        }
        return props;
    }
    
    /**
     * 經過配置文件路徑獲取配置信息
     * @param fileName
     * @return
     */
    public static Properties getProperty(String fileName) {
        //第一步是取得一個Properties對象  
        Properties props = new Properties();  
        //第二步是取得配置文件的輸入流  
        //InputStream is = PropertiesUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");//在非WEB環境下用這種方式比較方便  
        try { 
            InputStream input = new FileInputStream(fileName);
            // 第三步是把配置文件的輸入流load到Properties對象中,
            props.load(input);
            // 注意兩種的區別
            //props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName), "UTF-8")); 
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();  
        }  
        return props;  
    }
    
    /**
     * properties獲取key值
     * @param fileName
     * @param key
     * @return
     */
    public static String getProperty(String fileName, String key) {  
        String value = "";  
        //第一步是取得一個Properties對象  
        Properties props = new Properties();  
        //第二步是取得配置文件的輸入流  
        //InputStream is = PropertiesUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");//在非WEB環境下用這種方式比較方便  
        try {  
            //InputStream input = new FileInputStream("dbconfig.properties");//在WEB環境下用這種方式比較方便,不過當配置文件是放在非Classpath目錄下的時候也須要用這種方式  
            //第三步講配置文件的輸入流load到Properties對象中,這樣在後面就能夠直接取來用了  
            props.load(new InputStreamReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));  
            value = props.getProperty(key);  
            //is.close();  
        } catch (IOException e) {
            e.printStackTrace();  
        }  
        return value;  
    }
    
    /**
     * properties寫入key值
     * @param fileName
     * @param data
     */
    public static String setProperty(String fileName, Map<String, String> data) {
        String message = "true";
        
        // 第一步也是取得一個Properties對象
        Properties props = new Properties();
        // 第二步也是取得該配置文件的輸入流
        // InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties");
        try {
            InputStream input = new FileInputStream(fileName);
            // 第三步是把配置文件的輸入流load到Properties對象中,
            // props.load(new InputStreamReader(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName), "UTF-8"));
            props.load(input);
            // 接下來就能夠隨便往配置文件裏面添加內容了
            // props.setProperty(key, value);
            if (data != null) {
                Iterator<Entry<String, String>> iter = data.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, String> entry = iter.next();
                    props.setProperty(entry.getKey().toString(), entry.getValue().toString());
                }
            }
            // 在保存配置文件以前還須要取得該配置文件的輸出流,切記,若是該項目是須要導出的且是一個非WEB項目,
            // 則該配置文件應當放在根目錄下,不然會提示找不到配置文件
            OutputStream out = new FileOutputStream(fileName);
            // 最後就是利用Properties對象保存配置文件的輸出流到文件中;
            props.store(out, null);
            input.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            message = "false";
            e.printStackTrace();
        }
        
        return message;
    }
    
    
    public static void main(String[] args) {
        System.out.println(PropertiesUtils.getProps("dbconfig.properties"));
//        System.out.println(PropertiesUtils.getProperty("resource/dbconfig.properties"));
//        Map<String, String> data = new HashMap<String, String>();
//        data.put("db.db_type", "oracle1");
//        data.put("db.username", "root1");
//        data.put("db.password", "root1");
//        PropertiesUtils.setProperty("resource/dbconfig.properties", data);
    }
    
}
View Code

  三、config-path.propertiesapp

img.path=resource/image/title.png
db.path=resource/dbconfig.properties

  四、dbconfig.propertieside

#Oracle
db.db_type=oracle
db.driver=oracle.jdbc.driver.OracleDriver
db.dialect=org.hibernate.dialect.Oracle10gDialect
db.url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:tsm1
db.username=root
db.password=root
相關文章
相關標籤/搜索