当前位置: 移动技术网 > IT编程>软件设计>面向对象 > 【代码总结● Swing中的一些操作与设置】

【代码总结● Swing中的一些操作与设置】

2018年10月25日  | 移动技术网IT编程  | 我要评论

 

swing中设置关闭窗口验证与添加背景图片

package com.swing.test;

import java.awt.eventqueue;
import java.awt.image;
import java.awt.event.windowadapter;
import java.awt.event.windowevent;

import javax.swing.imageicon;
import javax.swing.jframe;
import javax.swing.jlabel;
import javax.swing.joptionpane;
import javax.swing.jpanel;

/**
 *@title backgroundpic.java
 *@description todo
 *@ time 2018-8-31 下午11:11:50
 *@author anderson
 *@version 1.0
 */
public class backgroundpic extends jframe {
    private static final long serialversionuid = 1l;

    private jpanel contentpane;//最大的jpanel层
    private jlabel lblbackgroundl;//背景图片标签

    /**
     * create the frame.
     */
    public backgroundpic() {
        contentpane = new jpanel();
        setcontentpane(contentpane);
        contentpane.setlayout(null);//绝对布局
        setresizable(false);//不允许用户自定义大小
        setsize(612 ,398);//设置jpanel大小
        setlocationrelativeto(null);//居中

        //设置点关闭后什么也不做.为添加关闭窗口验证做铺垫
        setdefaultcloseoperation(do_nothing_on_close);

        /**
         * 为整个窗口添加退出确认,前提是
         * setdefaultcloseoperation(do_nothing_on_close);
         */
        addwindowlistener(new windowadapter() {
            public void windowclosing(windowevent e) {
                int isexits = joptionpane.showconfirmdialog(null, "确认退出吗?",
                        "exit", joptionpane.ok_cancel_option,
                        joptionpane.question_message);
                if (isexits == joptionpane.ok_option) {
                    system.exit(0);
                }
            }
        });

/**********************设置背景图片***********************/
        /**
         * @author administrator
         * getscaledinstance(width,height,hints);
         * //width,height,hints为方法中的参数 
         * width the width to which to scale the image.
         * height the height to which to scale the image. 
         * hints flags to indicate the type of algorithm to use for image resampling.
         * //指示用于图像重新取样的算法类型的标志,指定缩放的比例算法
         */
        imageicon background = new imageicon("./img/login_box.jpg");
        background.setimage(
                background.getimage().getscaledinstance(
                        background.geticonwidth(), background.geticonheight(),
                        image.scale_default
                        )
                );
        lblbackgroundl = new jlabel();
        lblbackgroundl.setbounds(0, 0, 608, 369);
        lblbackgroundl.seticon(background);
        lblbackgroundl.sethorizontalalignment(0);
        getcontentpane().add(lblbackgroundl);
        system.out.println(
        "图片宽: "+background.geticonwidth() + 
        "高:" + background.geticonheight() 
        );
/**********************以上,设置背景图片***********************/    

    }


    /**
     * launch the application.
     */
    public static void main(string[] args) {
        eventqueue.invokelater(new runnable() {
            public void run() {
                try {
                    backgroundpic frame = new backgroundpic();
                    frame.setvisible(true);
                } catch (exception e) {
                    e.printstacktrace();
                }
            }
        });
    }

}

字符串下拉框的设置

private static jcombobox<string> cobauth;

cobauth = new jcombobox<string>();
cobauth.setbounds(244, 235, 147, 21);

cobauth.additem("leader");//添加下拉内容
cobauth.additem("worker");
//cobauth.setselectedindex(0);//设置默认显示下拉框
contentpane.add(cobauth);

//获取下拉框值
private static string auth1;
auth1 = (string) cobauth.getselecteditem();

密码输入框的设置

private static jpasswordfield pwdfield;

pwdfield = new jpasswordfield();
pwdfield.setbounds(244, 210, 147, 21);
contentpane.add(pwdfield);

//获取密码框值
private static string pwd1;
pwd1 = string.valueof(pwdfield.getpassword()).trim();

自己写的一些判断的工具类

package pers.jason.market.util;

import java.util.regex.matcher;
import java.util.regex.pattern;

/**
 * 工具包
 * @author administrator
 *
 */
public final class util {
    /**
     * 判断字符串是否为空
     * @param str
     * @return
     */
    public static boolean isempty(string str) {
        return null == str || "" .equals(str.trim()) ? true : false;
    }
    /**
     * 判断字符串是否为整数
     * @title : isnumber
     * @description:
     * @param str
     * @return
     * @return boolean
     * @author anderson
     * @data 2018-8-23 下午10:05:06
     */
    public static boolean isint (string str){


        pattern pattern = pattern.compile("[0-9]+"); 
           matcher isnum = pattern.matcher(str);
           if( !isnum.matches() ){
               return false; 
           }
        return true;
    }
    /**
     * 判断是否为小数
     * @title : isdouble
     * @description:
     * @param str
     * @return
     * @return boolean
     * @author anderson
     * @data 2018-8-23 下午10:59:04
     */
    public static boolean isdouble (string str){
        string [] num = str.split("\\.");
        if(num.length == 2 && isint(num[0]) && isint(num[1]) ){
            return true;
        }
        return false;
    }
    /**
     * 
     * @title : isdolores
     * @description:判断是否为美元
     * @param str
     * @return
     * @return boolean
     * @author anderson
     * @data 2018-8-27 上午11:38:26
     */
    public static boolean isdolores(string str){
        if("$".equals(str)){
        return true;
        }else
            return false;
    }
    /**
     * 
     * @title : isrmb
     * @description: 判断是否为人民币
     * @param str
     * @return
     * @return boolean
     * @author anderson
     * @data 2018-8-27 下午12:33:11
     */
    public static boolean isrmb(string str){
        if("¥".equals(str)){
            return true;
        }
        return false;
    }
}

object.properties 配置文件(对象属性)

transaction=pers.jason.market.transaction.impl.transactionimpl
userdao=pers.jason.market.dao.impl.userdaoimpl
userservice=pers.jason.market.service.impl.userserviceimpl
accountdao=pers.jason.market.dao.impl.accountdaoimpl
accountservice=pers.jason.market.service.impl.accountserviceimpl
supplierdao=pers.jason.market.dao.impl.supplierdaoimpl
supplierservice=pers.jason.market.service.impl.supplierserviceimpl

suppliergroupdao=pers.jason.market.dao.impl.suppliergroupdaoimpl
suppliergroupservice=pers.jason.market.service.impl.suppliergroupserviceimpl
goodsgroupdao=pers.jason.market.dao.impl.goodsgroupdaoimpl
goodsgroupservice=pers.jason.market.service.impl.goodsgroupserviceimpl

等号左边是接口,等号右边是其对应的实现类所在的包及实现类本身

之所以要写这个,是因为要写对象工厂

对象工厂

package pers.jason.market.object.factoy;


import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.util.enumeration;
import java.util.hashmap;
import java.util.map;
import java.util.properties;
/**
 * 
 * @title objectfactory.java
 * @description todo 对象工厂
 * @time 2018-8-20 下午3:11:19 
 * @author anderson
 * @version 1.0 ok
 */
public final class objectfactory {
    private static map<string, object> objectmap  = new hashmap<string,object>();
    static {
        properties properties = new properties();
        try {
            properties.load(new fileinputstream("object.properties"));
            enumeration<?> enumeration =properties.keys();
            while(enumeration.hasmoreelements()) {
                string key = (string)enumeration.nextelement();
                string value = properties.getproperty(key);
                objectmap.put(key, class.forname(value).newinstance());
            }
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        } catch (instantiationexception e) {
            e.printstacktrace();
        } catch (illegalaccessexception e) {
            e.printstacktrace();
        } catch (classnotfoundexception e) {
            e.printstacktrace();
        }
    }
    public static object getinstance(string key) {//得到对象
        //system.out.println(key+":"+objectmap.get(key));
        return objectmap.get(key);
    }

}

事务管理接口

package pers.jason.market.transaction;
/**
 *@title transaction.java
 *@description todo 事务管理接口
 *@ time 2018-8-18 下午11:50:51
 *@author anderson
 *@version 1.0 
 */
public interface transaction {

    /**
     * 
     * @title : begin
     * @description:事务开启
     * @return void
     * @author anderson
     * @data 2018-8-18 下午11:51:21
     */
    public  abstract  void begin();

    /**
     * 
     * @title : commit
     * @description:事务提交
     * @return void
     * @author anderson
     * @data 2018-8-18 下午11:51:26
     */
    public  abstract  void commit();

    /**
     * 
     * @title : rollback
     * @description:事务回滚
     * @return void
     * @author anderson
     * @data 2018-8-18 下午11:51:30
     */
    public  abstract  void rollback();
}

事务管理接口实现类

package pers.jason.market.transaction.impl;

import java.sql.connection;
import java.sql.sqlexception;

import pers.jason.market.transaction.transaction;
import pers.jason.market.util.jdbcutil;

/**
 *@title transactionimpl.java
 *@description todo 事务管理接口实现类
 *@ time 2018-8-18 下午11:52:59
 *@author anderson
 *@version 1.0 照抄完毕
 */
public class transactionimpl implements transaction{

    /**
     * 事务开启
     */
    @override
    public void begin() {
        connection conn = jdbcutil.getconnection();
        try {
            conn.setautocommit(false);//false为禁止自动提交
        } catch (sqlexception e) {
            e.printstacktrace();
        }

    }

    /**
     * 事务提交
     */
    @override
    public void commit() {
        connection conn = jdbcutil.getconnection();
        try {
            conn.commit();//事务提交
        } catch (sqlexception e) {
            e.printstacktrace();
        }finally {
            jdbcutil.closeconnection(conn);
        }

    }

    /**
     * 事务回滚
     */
    @override
    public void rollback() {
        connection conn = jdbcutil.getconnection();
        try {
            conn.rollback();//事务回滚
        } catch (sqlexception e) {
            e.printstacktrace();
        }finally {
            jdbcutil.closeconnection(conn);
        }       
    }
}

加载数据库的连接类

package pers.jason.market.util;

import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.sql.connection;
import java.sql.sqlexception;
import java.util.properties;

import javax.sql.datasource;

import org.apache.commons.dbcp.basicdatasourcefactory;

/**
 *@title jdbcutil.java
 *@description todo 加载数据库的连接类
 *@ time 2018-8-18 下午11:58:34
 *@author anderson
 *@version 1.0 照抄完毕
 */

public final class jdbcutil {
    private static datasource  datasource =null;
    private static threadlocal<connection> threadlocal = new threadlocal<connection>();
    static {
        properties properties = new properties();
        try {
            //读取配置文件
            properties.load(new fileinputstream("database.properties"));
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } catch (ioexception e) {
            e.printstacktrace();
        }
        try {
            datasource = basicdatasourcefactory.createdatasource(properties);//加载配置文件
        } catch (exception e1) {
            e1.printstacktrace();
        }
    }

    /**
     * 获取连接
     * @return
     */
    public static connection getconnection() {
        connection conn = threadlocal.get();//从线程局部变量map中取出连接
        if(null == conn) {//首次获取连接为null。要读取配置文件获取连接
            try {
                conn =datasource.getconnection();//获取连接
                threadlocal.set(conn);//保存连接到局部变量中
            } catch (sqlexception e) {
                e.printstacktrace();
            }
        }
        return conn;
    }

    /**
     * 关闭连接
     * @param conn
     */
    public static void closeconnection(connection conn) {
        if(null != conn) {
            threadlocal.remove();//先从局部变量中删除
            try {
                conn.close();//然后再关闭自身连接
            } catch (sqlexception e) {
                e.printstacktrace();
            }
        }
    }


}

其中配置文件为:(database.properties)
driverclassname=com.mysql.jdbc.driver
url=jdbc:mysql://localhost:3306/db_market
username=root
password=cc321321

jdbc管理类

package pers.jason.market.util;


import java.sql.connection;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;
import java.util.arraylist;
import java.util.list;

import pers.jason.market.rowmapper.rowmapper;

/**
 * jdbc管理类
 * @author administrator
 *
 */
public  final class jdbctemplate {  
    /**
     * 增删改方法
     * @param sql
     * @param param
     * @return
     * @throws sqlexception
     */
    public static int executeupdate(string sql,object ...param) {
        int rows=-1;
        connection conn=jdbcutil.getconnection();
        try {
            preparedstatement ps=conn.preparestatement(sql);
            if(null!=param && param.length>0){
                for (int i = 0; i < param.length; i++) {
                    ps.setobject((i+1), param[i]);
                }

            }
            rows=ps.executeupdate();
            close(null,ps);
        } catch (sqlexception e) {
            e.printstacktrace();
        }
        return rows;

    }

    /**
     * 查询方法
     * @param sql
     * @param rowmapper
     * @param param
     * @return
     * @throws sqlexception
     */

    public static   list<object> executequery(string sql,rowmapper rowmapper,object ...param) throws sqlexception {
        list<object> list = new arraylist<object>();
        connection conn = jdbcutil.getconnection();//获取连接
        preparedstatement ps = conn.preparestatement(sql);
        if(null != param && param.length>0) {
            for (int i = 0; i < param.length; i++) {
                ps.setobject((i+1), param[i]);// 占位符从1开始   下标从0开始
            }
        }
        system.out.println("jdbc 中ps:    " + ps);                                         //测试
        resultset rs = ps.executequery();
        while(rs.next()) {
            object obj = rowmapper.getobjectmapper(rs);
            list.add(obj);
        }
        close(rs,ps);
        return list;
    }

    private static void close(resultset rs,preparedstatement ps) throws sqlexception {
        if(null != rs) {
            rs.close();
        }
        if(null != ps) {
            ps.close();
        }
    }

}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网