superjoptionpane.java

来自「Java生成PDF Java生成PDF Java生成PDF」· Java 代码 · 共 258 行

JAVA
258
字号
// $Id: SuperJOptionPane.java,v 1.14 2007/11/16 00:58:51 mike Exp $package org.faceless.pdf2.viewer2;import javax.swing.*;import javax.swing.border.*;import javax.swing.text.*;import java.awt.*;import java.awt.event.*;import java.util.*;import java.util.List;/** * <p> * An abstract Dialog class that lays out it's fields (specified as a Map), * optionally validates it's content before saving then returns the values * from the fields in a {@link Map}. * </p> * <p>This class is only of interest to those extending the viewer package with * custom features. Even then, it may disappear or be rewrittein in the future * and shouldn't be relied upon by third parties</p> * * <p><i>This code is copyright the Big Faceless Organization. You're welcome to use, modify and distribute it in any form in your own projects, provided those projects continue to make use of the Big Faceless PDF library.</i></p> * @since 2.8 */public class SuperJOptionPane extends JPanel {    private Map output;    private JDialog dialog;    /**     * Create a new SuperJOptionPane     * @param map a Map mapping field names -> {@link JComponent} objects to be displayd     * in the dialog. A LinkedHashMap is required to preserve the order     */    public SuperJOptionPane(final LinkedHashMap map) {        super(new BorderLayout());        final SuperJOptionPane thiscomp = this;        JPanel contentpanel = new JPanel(new GridBagLayout());        GridBagConstraints c = new GridBagConstraints();        c.fill = c.HORIZONTAL;        for (Iterator i = map.entrySet().iterator();i.hasNext();) {            Map.Entry e = (Map.Entry)i.next();            String key = (String)e.getKey();            Object comp = (Component)e.getValue();            if (comp instanceof JFileChooser) {                ((JFileChooser)comp).setControlButtonsAreShown(false);            }            if (comp==null) {                c.gridwidth = 2;                c.gridx = 0;                c.weighty = 0;                contentpanel.add(new JLabel(getLocalizedString(key)), c);                c.gridy++;      // ??? Why?            } else if (comp instanceof JPanel || comp instanceof JFileChooser || comp instanceof JTextArea || comp instanceof JScrollPane) {                c.gridwidth = 2;                c.gridx = 0;                c.weighty = 1;                contentpanel.add((Component)comp, c);                c.gridy++;      // ??? Why?            } else {                if (comp instanceof ButtonGroup) {                    JPanel buttonpanel = new JPanel();                    for (Enumeration en = ((ButtonGroup)comp).getElements();en.hasMoreElements();) {                        AbstractButton button = (AbstractButton)en.nextElement();                        buttonpanel.add(button);                        buttonpanel.add(new JLabel(button.getActionCommand()));                    }                    comp = buttonpanel;                }                c.weighty = 0;                c.gridwidth = 1;                c.gridx = 0;                contentpanel.add(new JLabel(getLocalizedString(key)+"   "), c);                c.gridx = 1;                contentpanel.add((Component)comp, c);            }            c.gridy++;        }        JPanel buttonpanel = new JPanel();        JButton okbutton = new JButton(getLocalizedString("OK"));        okbutton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {                Map output = new HashMap();                for (Iterator i = map.entrySet().iterator();i.hasNext();) {                    Map.Entry e = (Map.Entry)i.next();                    String key = (String)e.getKey();                    Component value = (Component)e.getValue();                    if (value instanceof JPasswordField) {                        output.put(key, ((JPasswordField)value).getPassword());                    } else if (value instanceof JTextComponent) {                        output.put(key, ((JTextComponent)value).getText());                    } else if (value instanceof JPanel) {                        JPanel panel = (JPanel)value;                        String val = "";                        for (int j=0;j<panel.getComponentCount();j++) {                            Component c = panel.getComponent(j);                            if (c instanceof AbstractButton && ((AbstractButton)c).isSelected()) {                                val += ((AbstractButton)c).getActionCommand()+"\n";                            }                        }                        output.put(key, val);                    } else if (value instanceof JFileChooser) {                        output.put(key, ((JFileChooser)value).getSelectedFile());                    } else if (value instanceof JSlider) {                        output.put(key, new Integer(((JSlider)value).getValue()));                    } else if (value instanceof JSpinner) {                        output.put(key, ((JSpinner)value).getValue());                    } else if (value instanceof JComboBox) {                        output.put(key, ((JComboBox)value).getSelectedItem());                    }                }                String error = validate(output);                if (error!=null) {                    JOptionPane.showMessageDialog(thiscomp, error, getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE);                } else {                    thiscomp.output = output;                    dialog.dispose();                }            }        });        JButton cancelbutton = new JButton(getLocalizedString("Cancel"));        cancelbutton.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent evt) {                output = null;                dialog.dispose();            }        });        buttonpanel.add(cancelbutton);        buttonpanel.add(okbutton);        buttonpanel.setBorder(BorderFactory.createEtchedBorder());        contentpanel.setBorder(new CompoundBorder(BorderFactory.createEtchedBorder(), new EmptyBorder(10,10,10,10)));        add(contentpanel, BorderLayout.CENTER);        add(buttonpanel, BorderLayout.SOUTH);    }    /**     * Validate the values. This method shoudl return <code>null</code> if all     * the values are valid, or a String containing an error message otherwise.     * @param entries a Map containing field-name -> values which can be validated. The     * values are the same as returned by {@link #getValues getValue()}     */    public String validate(Map entries) {        return null;    }    private JDialog createDialog(Component parentComponent, String title) {        Window window = JOptionPane.getFrameForComponent(parentComponent);        if (window instanceof Frame) {            dialog = new JDialog((Frame)window, getLocalizedString(title), true);        } else {            dialog = new JDialog((Dialog)window, getLocalizedString(title), true);        }        Container content = dialog.getContentPane();        content.setLayout(new BorderLayout());        content.add(this);        dialog.setResizable(false);        dialog.pack();        dialog.setLocationRelativeTo(parentComponent);        dialog.addWindowListener(new WindowAdapter() {            public void windowClosing(WindowEvent evt) {                output = null;                dialog.dispose();            }        });        return dialog;    }    /**     * Display the dialog and pause until it's approved, at which point the     * values will be validated (with the {@link #validate validate()} method)     * and returned. The returned map has an entry for each field name passed     * in to the constructor, and the values depend on the type of field:     * char[] for {@link JPasswordField}, String for {@link JTextComponent},     * File for {@link JFileChooser}, Integer for {@link JSlider} and the like.     * If the user selected the "Cancel" button, this method returns <code>null</code>     */    public Map getValues(Component parent, String title) {        JDialog dialog = createDialog(parent, title);        dialog.setVisible(true);        dialog.dispose();        return output;    }    /**     * Display an Error message, including the stack trace     * @param title the title of the Dialog     * @param throwable the Throwable object this error relates to     * @param parent the parent component     */    public static void displayThrowable(String title, final Throwable throwable, Component parent) {        String name = throwable.getClass().getName();        name = name.substring(name.lastIndexOf('.') + 1);        if (throwable.getMessage()!=null) {            name += ": "+throwable.getMessage();        }        final String msg = name;        final JLabel label = new JLabel(msg);        final JButton details = new JButton(getLocalizedString("Show"));        JOptionPane pane = new JOptionPane(label, JOptionPane.ERROR_MESSAGE, JOptionPane.YES_NO_OPTION, null, new Object[] { details, getLocalizedString("Exit") });        final JDialog dialog = pane.createDialog(parent, title);        dialog.setModal(true);        details.addActionListener(new ActionListener() {            public void actionPerformed(ActionEvent event) {                try {                    if (details.getText().equals(getLocalizedString("Show"))) {                        StringBuffer b = new StringBuffer("<html>");                        int last = 1;                        Throwable e = throwable;                        while (e != null) {                            b.append("<b>"+e.getClass().getName()+"</b>: "+e.getMessage()+"<ul>");                            StackTraceElement[] s = e.getStackTrace();                            for (int i=0;i<=s.length-last;i++) {                                b.append("<li> in " + s[i].getClassName() + ".");                                b.append("<b>"+s[i].getMethodName()+"</b>() at ");                                b.append("<tt>"+s[i].getFileName()+":"+s[i].getLineNumber()+"</tt>");                            }                            b.append("</ul>");                            e = e.getCause();                            if (e!=null) {                                b.append("<i>Caused by: </i>");                                last = s.length;                            }                        }                        b.append("</html>");                        label.setText(b.toString());                        details.setText(getLocalizedString("Hide"));                    } else {                        label.setText(msg);                        details.setText(getLocalizedString("Show"));                    }                    dialog.pack();                } catch (Throwable e) {                    e.printStackTrace();                }            }        });        dialog.setVisible(true);    }    public static String getLocalizedString(String key) {        return ResourceBundle.getBundle("org.faceless.pdf2.viewer2.resources.Text").getString(key);    }    public static String getLocalizedString(String key, String v1) {        String v = getLocalizedString(key);        v = v.replaceAll("\\{1\\}", v1);        return v;    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?