zoukankan      html  css  js  c++  java
  • 【代码总结● Swing中的一些操作与设置】

    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();
            }
        }
    
    }
    
  • 相关阅读:
    Callback2.0
    设计模式之Composite
    设计模式之Proxy
    React Native DEMO for Android
    React Native 与 夜神模拟器的绑定
    Skipping 'Android SDK Tools, revision 24.0.2'; it depends on 'Android SDK Platform-tools, revision 20' which was not installed.
    .ui/qrc文件自动生成.py文件
    简单排序算法
    Big O
    设计模式之Adapter
  • 原文地址:https://www.cnblogs.com/jsccc520/p/9839628.html
Copyright © 2011-2022 走看看