package com.vci.client.ui.swing; import java.awt.Color; import java.awt.Component; import java.awt.Desktop; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.URL; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.prefs.Preferences; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.Border; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.plaf.FontUIResource; import com.vci.client.ui.swing.components.VCIJButton; import com.vci.client.ui.swing.components.VCIJLabel; import com.vci.client.ui.swing.components.VCIJMenuItem; import com.vci.client.ui.swing.components.VCIJOptionPane; import com.vci.client.utils.excel.ExcelFileOperation; import edu.stanford.smi.protege.util.LookAndFeelUtil; /** * *

Title:

*

Description:

*

Copyright: Copyright (c) 2012

*

Company: VCI

* @author xchao * @time 2012-5-10 * @version 1.0 */ public class VCISwingUtil { public final static Color TEXTCOLOR = new Color(48, 70, 110); public final static Color TEXTCOLOR_LOST = new Color(150, 150, 150); public final static Color FRAMECOLOR = new Color(98, 140, 97); public final static Color TBC1 = new Color(239, 243, 249); public final static Color TBC2 = new Color(220, 229, 241); public final static Color TBC3 = new Color(187, 206, 229); public final static Color TBC4 = new Color(221, 232, 242); private static Frame CLIENT_MAIN_FRAME = null; public final static String FONT_FAMILY = "宋体"; public final static Font FONT_SONTTI_PLAN_12 = new Font(FONT_FAMILY, Font.PLAIN, 12); public final static Font FONT_SONTTI_PLAN_13 = new Font(FONT_FAMILY, Font.PLAIN, 13); public final static Font FONT_SONTTI_PLAN_14 = new Font(FONT_FAMILY, Font.PLAIN, 14); public final static Font FONT_DEFAULT = FONT_SONTTI_PLAN_12; public final static Font ST12 = new Font("Dialog", Font.PLAIN, 12); public final static Font Font12B = new Font("Dialog", Font.BOLD, 12); public final static int JTEXT_FIELD_DEFAULT_HEIGHT = 23; public final static int JTEXT_FIELD_DEFAULT_WIDTH = 100; public final static Color JTEXT_FIELD_DEFAULT_BORDER_COLOR = new Color(160, 160, 160); public final static Color JTEXT_FIELD_MOUSE_ENTER_COLOR = new Color(77, 144, 254);//new Color(92, 163, 45); public final static Color JTEXT_FIELD_MOUSE_CLICK_COLOR = JTEXT_FIELD_MOUSE_ENTER_COLOR; public final static Color JTEXT_FIELD_MOUSE_EXITED_BACKGROUND_COLOR = Color.WHITE; public final static Color JTEXT_FIELD_MOUSE_CLICK_BACKGROUND_COLOR = new Color(254, 251, 189); public final static Border JTEXT_FIELD_BORDER_DEFAULT = BorderFactory.createLineBorder(JTEXT_FIELD_DEFAULT_BORDER_COLOR, 1); public final static Border JTEXT_FIELD_BORDER_MOUSE_ENTERED = BorderFactory.createLineBorder(JTEXT_FIELD_MOUSE_ENTER_COLOR, 1); public final static Border JTEXT_FIELD_BORDER_MOUSE_EXITED = BorderFactory.createLineBorder(JTEXT_FIELD_DEFAULT_BORDER_COLOR, 1); public final static Border JTEXT_FIELD_BORDER_MOUSE_CLICKED = BorderFactory.createLineBorder(JTEXT_FIELD_MOUSE_CLICK_COLOR, 1); public final static Border BORDER_EMPTY = BorderFactory.createEmptyBorder(); public final static String IMAGE_PATH = "/resource/images/"; public final static int JTABLE_ROW_HEIGHT = 25; public final static int JTABLE_HEADER_HEIGHT = JTABLE_ROW_HEIGHT; public final static Color JTABLE_ROW_BACKGROUND_COLOR_HOVER = new Color(255, 255, 225); public final static Color JTABLE_ROW_BACKGROUND_COLOR_CHECKED = new Color(255, 255, 200); public final static Color JTABLE_ROW_BACKGROUND_COLOR_ODD = new Color(242, 242, 242); public final static Color JTABLE_ROW_BACKGROUND_COLOR_EVEN = Color.WHITE; public final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public final static String LOOK_AND_FEEL_MetalLookAndFeel = "com.sun.java.swing.plaf.metal.MetalLookAndFeel"; public final static String LOOK_AND_FEEL_WindowsLookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; public final static String LOOK_AND_FEEL_AlloyLookAndFeel = "com.incors.plaf.alloy.AlloyLookAndFeel"; public final static String LOOK_AND_FEEL_NimbusLookAndFeel= "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; public final static String LOOK_AND_FEEL_PlasticLookAndFeel = "com.jgoodies.looks.plastic.PlasticLookAndFeel"; public final static String LOOK_AND_FEEL_FlatLightLaf = "com.formdev.flatlaf.FlatLightLaf"; /** * 设置客户端主Frame对象 *

Description:

* * @author xchao * @time 2012-5-19 * @param frame */ public static void setClientMainFrame(Frame frame){ if(CLIENT_MAIN_FRAME == null){ CLIENT_MAIN_FRAME = frame; } } /** * 返回客户端主Frame对象 *

Description:

* * @author xchao * @time 2012-5-19 * @return */ public static Frame getClientMainFrame(){ return CLIENT_MAIN_FRAME; } /** * *

Description:

* * @author xchao * @time 2012-5-19 * @param icon * @return */ public static ImageIcon createImageIconFromImagePath(String icon){ return createImageIcon(VCISwingUtil.class, IMAGE_PATH + icon); } /** * *

Description:

* * @author xchao * @time 2012-5-19 * @param icon * @return */ public static ImageIcon createImageIcon(String icon){ return createImageIcon(VCISwingUtil.class, icon); } /** * *

Description:

* * @author xchao * @time 2012-5-19 * @param classes * @param icon * @return */ public static ImageIcon createImageIcon(Class classes, String icon){ URL url = classes.getResource(icon); if(url == null){ url = classes.getResource(IMAGE_PATH + icon); } return createImageIcon(url); } /** * * @param classes * @param icon * @return */ public static Image createImage(String icon){ URL url = VCISwingUtil.class.getResource(icon); if(url == null){ url = VCISwingUtil.class.getResource(IMAGE_PATH + icon); } ImageIcon imgIcon = createImageIcon(url); return imgIcon.getImage(); } /** * *

Description:

* * @author xchao * @time 2012-5-19 * @param url * @return */ public static ImageIcon createImageIcon(URL url){ //ClientWithLog4j.logger.debug("ImageUrl=" + url); return new ImageIcon(url); } public static String[] getImages() { try { //ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); //Resource[] resources = resourceResolver.getResources("resource/images/*.*"); String path = "resource/images/*.*"; Enumeration urlEnumeration = VCISwingUtil.class.getClassLoader().getResources(path); List lstImage = new ArrayList(); while (urlEnumeration.hasMoreElements()) { URL url = (URL)urlEnumeration.nextElement(); File file = new File(url.toString()); String name = file.getName(); lstImage.add(name); } // for (int i = 0; i < resources.length; i++) { // String name = resources[i].getFilename(); // lstImage.add(name); // } return lstImage.toArray(new String[0]); } catch (IOException e) { e.printStackTrace(); } return new String[0]; } /** * *

Description:

* * @author xchao * @time 2012-5-19 * @param font */ public static void setFont(Font font){ FontUIResource fontUIResource = new FontUIResource(font); Enumeration keys = UIManager.getDefaults().keys(); while(keys.hasMoreElements()){ Object key = keys.nextElement(); Object value = UIManager.get(key); if(value instanceof java.awt.Font){ UIManager.put(key, font); } if(value instanceof FontUIResource){ UIManager.put(key, fontUIResource); } } } /** * 设置全部组件的默认字体 *

Description:

* * @author xchao * @time 2012-5-19 */ public static void setFont(){ setFont(FONT_DEFAULT); } /** * 设置默认的主题皮肤(NimbusLookAndFeel) *

Description:

* * @author xchao * @time 2012-5-19 */ public static void setLookAndFeel(){ //setLookAndFeel(LOOK_AND_FEEL_NimbusLookAndFeel); //setLookAndFeel(LOOK_AND_FEEL_AlloyLookAndFeel); setLookAndFeel(LOOK_AND_FEEL_PlasticLookAndFeel); //setLookAndFeel(LOOK_AND_FEEL_FlatLightLaf); //setLookAndFeel(LOOK_AND_FEEL_WindowsLookAndFeel); } /** * 根据指定class来设置LookAndFeel *

Description:

* * @author xchao * @time 2012-5-19 * @param lafClass */ public static void setLookAndFeel(String lafClass){ try { String javaVersion = System.getProperty("java.version"); if(javaVersion != null){ String[] versions = javaVersion.split("_"); if(versions.length == 2){ int major = Integer.valueOf(versions[0].replaceAll("1.", "").replaceAll(".0", "")); int minor = Integer.valueOf(versions[1]); /** * LOOK_AND_FEEL_NimbusLookAndFeel 正确使用问题: * 1、如果JAVA版本是6,但小版本低于10,则使用Windows主题 * 2、如果JAVA版本是5或更低,则使用Windows主题 */ if(major >= 6){ if(minor <= 10 && lafClass.equalsIgnoreCase(LOOK_AND_FEEL_NimbusLookAndFeel)){ lafClass = LOOK_AND_FEEL_WindowsLookAndFeel; } } else{ lafClass = LOOK_AND_FEEL_WindowsLookAndFeel; } } } LookAndFeel lookAndFeel = (LookAndFeel) Class.forName(lafClass).newInstance(); LookAndFeelUtil.setUpPlasticLF(); UIManager.put("ClassLoader", lookAndFeel.getClass().getClassLoader()); UIManager.setLookAndFeel(lookAndFeel); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); setAllComponentFont(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } } private static void setAllComponentFont(){ Font font = FONT_DEFAULT; FontUIResource fontUIResource = new FontUIResource(font); java.util.Enumeration keys = UIManager.getDefaults().keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); Object obj = UIManager.get (key); if(obj instanceof Font){ UIManager.put(key, font); } if(obj instanceof FontUIResource){ UIManager.put(key, fontUIResource); } } } /** * 延时执行 *

Description:

* * @author xchao * @time 2012-5-19 * @param doRun runnnable * @param lazyMillis 延时时间(单位为毫秒) */ public static void invokeLater(final Runnable doRun, final int lazyMillis){ SwingUtilities.invokeLater(new Runnable(){ public void run(){ try { Thread.sleep(lazyMillis); doRun.run(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } /** * 创建一个按钮对象 *

Description:

* * @author xchao * @time 2012-5-19 * @param actionCommand * @param text * @param toolTip * @param icon * @return * @see createVCIJButton */ public static VCIJButton createVCIJButton(String actionCommand, String text, String toolTip, String icon){ return createVCIJButton(actionCommand, text, toolTip, icon, null); } public static final Icon EMPTY_ICON = new Icon() { @Override public void paintIcon(Component c, Graphics g, int x, int y) { } @Override public int getIconWidth() { return 0; } @Override public int getIconHeight() { return 0; } }; /** * 创建一个VCIJButton对象 *

Description:

* * @author xchao * @time 2012-5-19 * @param actionCommand 按钮的 actionCommand * @param text text * @param toolTip toolTip * @param icon icon(如果icon在resource/images/包下,只需要写文件名,否则需要提供完整的路径) * @param actionListener actionListener * @return */ public static VCIJButton createVCIJButton(String actionCommand, String text, String toolTip, String icon, ActionListener actionListener){ VCIJButton btn = new VCIJButton(text); if(icon != null && !"".equals(icon.trim())){ btn.setIcon(VCISwingUtil.createImageIcon(icon)); } else { btn.setIcon(EMPTY_ICON); } if(actionListener != null){ btn.addActionListener(actionListener); } btn.setActionCommand(actionCommand); btn.setToolTipText(toolTip); btn.setText(text); return btn; } public static VCIJMenuItem createVCIJMenuItem(String actionCommand, String text, String toolTip, String icon){ return createVCIJMenuItem(actionCommand, text, toolTip, icon, null); } public static VCIJMenuItem createVCIJMenuItem(String actionCommand, String text, String toolTip, String icon, ActionListener actionListener){ VCIJMenuItem menuItem = new VCIJMenuItem(text, VCISwingUtil.createImageIcon(icon)); if(actionListener != null){ menuItem.addActionListener(actionListener); } menuItem.setActionCommand(actionCommand); menuItem.setToolTipText(toolTip); menuItem.setText(text); return menuItem; } /** * 返回日期的字符串表现形式 *

Description:

* * @author xchao * @time 2012-5-19 * @param date java.util.Date * @return */ public static String getDateString(java.util.Date date){ return SDF.format(date); } /** * *

Description:

* * @author xchao * @time 2012-5-19 * @param date java.sql.Date * @return */ public static String getDateString(java.sql.Date date){ @SuppressWarnings("deprecation") java.util.Date utDate = new java.util.Date( date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()); return getDateString(utDate); } /** * 返回从文件选择框中选择的Excel文件完整的路径 *

Description:

* @author xchao * @time 2013-7-8 * @param parent 父容器对象 * @param isSaveDialog 是否是保存文件模式 * @param defaultFileName 默认文件名称 * @param defaultVersionIs2003 首选文件格式是否是Excel 2003 * @return */ public static String getExcelFileURL(Component parent, boolean isSaveDialog, String defaultFileName, boolean defaultVersionIs2003){ LinkedHashMap filterMap = new LinkedHashMap(); if(defaultVersionIs2003){ filterMap.put("Excel 97-2003工作薄(*.xls)", "xls"); } filterMap.put("Excel 工作薄(*.xlsx)", "xlsx"); if(!defaultVersionIs2003){ filterMap.put("Excel 97-2003工作薄(*.xls)", "xls"); } String filePath = getFileURL(parent, isSaveDialog, filterMap, defaultFileName); if(!isSaveDialog && filePath != null && !"".equals(filePath) && !new ExcelFileOperation().isSupportExcelFormat(parent, filePath)){ filePath = null; } return filePath; } /** * 返回从文件选择框中选择的Excel文件完整的路径 *

Description:

* @author xchao * @time 2013-7-8 * @param parent 父容器对象 * @param isSaveDialog 是否是保存文件模式 * @param defaultFileName 默认文件名称 * @return */ public static String getExcelFileURL(Component parent, boolean isSaveDialog, String defaultFileName){ return getExcelFileURL(parent, isSaveDialog, defaultFileName, true); } /** * *

Description:

*

Description:

* @author xchao * @time 2013-7-8 * @param parent 父容器对象 * @param isSaveDialog 是否是保存文件模式 * @param filterMap 文件后续过滤map key:描述 value:后缀,如 xlsx或.xlsx * @param defaultFileName 默认文件名 * @return */ public static String getFileURL(Component parent, boolean isSaveDialog, Map filterMap, String defaultFileName){ String lastPath = ""; Preferences pref = Preferences.userRoot().node(VCISwingUtil.class.getName()); lastPath = pref.get("lastPath", ""); if(lastPath != null && lastPath.equals("") || lastPath == null){ lastPath = System.getProperty("user.home"); } JFileChooser jfc = new JFileChooser(lastPath); jfc.setAcceptAllFileFilterUsed(true); jfc.setMultiSelectionEnabled(false); jfc.setFileHidingEnabled(false); jfc.setMultiSelectionEnabled(false); jfc.setFileSelectionMode(JFileChooser.FILES_ONLY); String firstSuffix = ""; if(filterMap != null){ Iterator keys = filterMap.keySet().iterator(); FileNameExtensionFilter defaultFilter = null; while(keys.hasNext()){ String key = keys.next(); String value = filterMap.get(key); if((firstSuffix == null) || (firstSuffix.length() == 0)){ firstSuffix = value; } if(value.lastIndexOf(".") >= 0 ){ value = value.substring(value.lastIndexOf(".") + 1); } FileNameExtensionFilter filter = new FileNameExtensionFilter(key, value); jfc.addChoosableFileFilter(filter); if(defaultFilter == null){ defaultFilter = filter; } } // 设置对话框的默认扩展名 jfc.setFileFilter(defaultFilter); jfc.setAcceptAllFileFilterUsed(false); } if(defaultFileName != null){ jfc.setSelectedFile(new File(defaultFileName)); } int result = -1; if(isSaveDialog){ jfc.setDialogType(JFileChooser.SAVE_DIALOG); result = jfc.showSaveDialog(parent); } else{ jfc.setDialogType(JFileChooser.OPEN_DIALOG); result = jfc.showOpenDialog(parent); } pref.put("lastPath", lastPath); if (result == JFileChooser.APPROVE_OPTION){ pref.put("lastPath", jfc.getSelectedFile().getParent()); String selectedFilePath = jfc.getSelectedFile().getAbsolutePath(); boolean validSuffix = false; if(jfc.getFileFilter() instanceof FileNameExtensionFilter){ FileNameExtensionFilter filter = (FileNameExtensionFilter) jfc.getFileFilter(); String[] extensions = filter.getExtensions(); for(int i = 0; i < extensions.length; i++){ String ext = extensions[i]; if(i == 0){ firstSuffix = ext; } if(selectedFilePath.endsWith("." + ext)){ validSuffix = true; } } } if(!validSuffix){ selectedFilePath += "." + firstSuffix; } if(selectedFilePath.endsWith(".")){ selectedFilePath = selectedFilePath.substring(0, selectedFilePath.length() -1); } return selectedFilePath; } return null; } /** * 打开文件保存成功的消息提示框 * @param parentComponent 父组件对象 * @param file file对象 * @param isOpen * @throws IOException */ public static void showOpenOrExplorerFileMessage(Component parentComponent, File file) throws IOException{ Object[] message = {new VCIJLabel("

数据成功保存到:

" + file.getAbsolutePath() + "

 

")}; Object[] options = {"打开(O)", "打开文件夹(F)", "关闭(C)"}; int res = VCIJOptionPane.showOptionDialog(parentComponent, message, "数据导出成功", VCIJOptionPane.DEFAULT_OPTION, VCIJOptionPane.INFORMATION_MESSAGE, null, options, options[options.length-1]); if(res == 0){ VCISwingUtil.openOrExplorerFile(parentComponent, file, true); } else if(res == 1){ VCISwingUtil.openOrExplorerFile(parentComponent, file, false); } else if(res == 2){ } } /** * 打开文件或打开文件所在的文件夹并选中文件 * @param owner 父组件对象 * @param file 文件对象 * @param isOpen true:打开文件,false:打开文件所在的文件夹并选中文件 */ public static void openOrExplorerFile(Component parentComponent, File file, boolean isOpen){ boolean isWindowsPlatform = System.getProperty("os.name").toLowerCase().contains("windows"); String runCommand = "cmd.exe /C start \"{4}\" /D \"{1}\" \"{3}\""; runCommand = "explorer.exe /n, " + file.getAbsolutePath(); String explorerCommand = "explorer.exe /select,\"{2}\""; boolean hasBlank = file.getAbsolutePath().contains(" "); if(!isWindowsPlatform){ VCIJOptionPane.showMessage(parentComponent, "不支持本系统!"); return; } String errorMessage = "执行打开文件或文件夹时发生错误!"; String drive = null; String full_path = null; String parent_path = null; String file_name = null; full_path = file.getAbsolutePath(); if (file.isDirectory()) { parent_path = file.getPath(); file_name = "dir"; } else { parent_path = file.getParent(); file_name = file.getName(); } if (full_path != null) { if (full_path.indexOf(":") != -1) { drive = full_path.substring(0, full_path.indexOf(":")); } try { String target = ""; if (isOpen) { target = runCommand; } else { target = explorerCommand; } String[] args = new String[6]; args[0] = drive; args[1] = parent_path; args[2] = full_path; args[3] = file_name; args[4] = file.getParent(); args[5] = System.getProperty("line.separator"); if(hasBlank){ if(isOpen){ //showOpening(parentComponent); Desktop.getDesktop().open(file); } else{ int msgRes = VCIJOptionPane.showConfirmDialog(parentComponent, "文件路径中存在空格,不支持打开文件路径存在空格的文件夹,\n" + "您是否需要打开该文件?", "询问", VCIJOptionPane.YES_NO_OPTION , VCIJOptionPane.QUESTION_MESSAGE); if(msgRes == VCIJOptionPane.YES_OPTION){ showOpening(parentComponent); Desktop.getDesktop().open(file); } } } else { showOpening(parentComponent); String cmd = MessageFormat.format(target, args); Runtime.getRuntime().exec(cmd); } } catch (Exception e) { e.printStackTrace(); VCIJOptionPane.showError(parentComponent, errorMessage); } } else { VCIJOptionPane.showError(parentComponent, errorMessage); } } private static void showOpening(final Component parentComponent){ // new Thread(new Runnable() { // @Override // public void run() { // VCIJOptionPane.showMessage(parentComponent, "正在打开,请稍候..."); // } // }).start(); } private static File getExcelFile() { File file = null; String filePath = VCISwingUtil.getExcelFileURL(null, true, ""); if(filePath != null){ file = new File(filePath); } return file; } private static File getRequiredFile(){ File files = getExcelFile(); // add by xchao 2014.04.15 begin // 有错误数据要输出时,必须选择有效的excel文件 while(files == null){ files = getExcelFile(); } String fileName = files.getAbsolutePath(); // 如果文件被打开着,则必须选择其它的未打开着的文件 while (files.exists() && !files.renameTo(new File(fileName))) { VCIJOptionPane.showMessageDialog(null, "另一个程序正在使用此文件,进程无法访问,请重新选择!"); // 重新选择文件时,也必须选择有效的excel文件 files = null; while(files == null){ files = getExcelFile(); } fileName = files.getAbsolutePath(); } return files; } public static void main(String[] args){ // writeExcelFileInfo("", "", null, null); // final boolean[] ress = new boolean[1]; // final QANProcessBarFrame frame = new QANProcessBarFrame(); // Thread t = new Thread() { // public void run() { // try{ // File files = getRequiredFile(); // ress[0] = true; // System.out.println(files.getAbsolutePath()); // }catch(Exception e){ // e.printStackTrace(); // }finally{ // frame.setProcessBarCancel(true); // } // } // }; // QANProcessBar bar = new QANProcessBar(t, frame, frame, "断链检查", false); // bar.setVisible(true); System.exit(0); } }