APP JOptions for SWING Application

Joe

Thành viên VIP
21/1/13
2,958
1,323
113
Hi
As I have already showed you the customized JOptionPane in the thread Password with JOptionPane ? I show you today the extension of the API and rename it to JOptions. The new API contains 4 following static methods:
  1. static String password(JFrame frame, String tit)
  2. static String[] multipleInputs(JFrame frame, String[] lab, String tit)
  3. static java.util.List<String> dynamicInputs(JFrame frame, String tit)
  4. static java.util.List<String> dynamicInputs(JFrame frame, String tit, int msgType)
so that the methods can be directly invoked without having to instantiate JOptions. Except the method password() all the method JTextFields can be copied and pasted from or to an external source using simultaneously 2 keys: CTRL and C for Copy or CTRL and P for Paste.
Example:
Java:
List<String> list = JOptions.dynamicInputs(jf,"dynamicInputs");
String res[] = JOptions.multipleInputs(jf,
                                       new String[] { "Name", "Address", "Profession", "Country" },
                                       "JOptions.multipleInputs");
// or
String res[] = JOptions.multipleInputs(jf, "Name!Address!Profession!Country".split("!"), "JOptions.multipleInputs");
The API can be documented by the tool javadoc. The source JOptions.java
Java:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.*;
// Joe Nartca (C)
public class JOptions {
  /**
  multipleInputs with Labels. The number of input fields is equal the number of the given lab array
  @param  frame   - JFrame the calling frame (owner) or NULL
  @param  lab     - string array for Labels
  @param  tit     - String, Title
  @return String array of inputs (incl. empty strings)
  */
  @SuppressWarnings({"unchecked", "deprecated"}) 
  public static String[] multipleInputs(JFrame frame, String[] lab, String tit) {
    JTextField tf[] = new JTextField[lab.length];
    String[] inp = new String[lab.length];
    
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints left = new GridBagConstraints();
    left.anchor = GridBagConstraints.EAST;
    GridBagConstraints right = new GridBagConstraints();
    right.anchor = GridBagConstraints.WEST;
    right.gridwidth = GridBagConstraints.REMAINDER;
    
    JPanel all = new JPanel(layout);
    JDialog dia = (new JOptionPane(all)).createDialog(frame, tit);
    //
    setMenu(dia);
    for (int i = 0; i < lab.length; ++i) {
      JLabel jlab = new JLabel(lab[i]+" ");
      layout.setConstraints(jlab, left);
      tf[i] = new JTextField(32);
      layout.setConstraints(tf[i], right);
      all.add(jlab);
      tf[i].setEditable(true);
      all.add(tf[i]);
    }
    dia.addComponentListener(listener(tf[0]));
    dia.pack();
    dia.setVisible(true);
    for (int i = 0; i < inp.length; ++i) inp[i] = tf[i].getText().trim();
    dia.dispose();
    return inp;
  }
  /**
  dynamicInputs. Return a list of inputs (String) if OK or CLOSE is clicked.
  <br>Previous inputs can be modified at anytime.
  <br>Note: all leading and ending blanks are truncated. Input with 0 length is ignored.
  @param frame JFrame, null to display JOptions in the center of screen
  @param tit title String
  @return list of input string (without empty string)
  */
  public static java.util.List<String> dynamicInputs(JFrame frame, String tit) {
    return dynamicInputs(frame, tit, -1);
  }
  /**
  dynamicInputs. Return a list of inputs (String) if OK or CLOSE is clicked.
  <br>Previous inputs can be modified at anytime.
  <br>Note: all leading and ending blanks are truncated. Input with 0 length is ignored.
  @param frame JFrame, null to display JOptions in the center of screen
  @param tit title String
  @param msgType int, JOptionPane.MessageType (e.g. JOptionPane.INFORMATION_MESSAGE, JOptionPane.QUESTION_MESSAGE, etc.) 
  @return list of input string (without empty string)
  */
  public static java.util.List<String> dynamicInputs(JFrame frame, String tit, int msgType) {
    java.util.List<String> list = new java.util.ArrayList<>();
    JPanel pan = new JPanel(new GridLayout(1,0));
    JTextField tf = new JTextField(32);
    pan.add(tf);
    JDialog dia;
    if (msgType >= 0) {
      JOptionPane op = new JOptionPane(pan);      
      op.setMessageType(msgType);        
      dia = op.createDialog(frame, tit);
    } else dia = (new JOptionPane(pan)).createDialog(frame, tit);
    //
    setMenu(dia);
    dia.addComponentListener(listener(tf));
    // recursive until OK or CLOSE is clicked
    tf.addActionListener(e->{[/COLOR][/SIZE]
      Component com[] = pan.getComponents();
      int n = 1; // set counter
      for (Component C:com) {
        if (((JTextField)C).getText().trim().length() > 0) ++n;
        else pan.remove(C);
      }
      JTextField jt = new JTextField();
      jt.addActionListener(tf.getActionListeners()[0]);
      pan.setLayout(new GridLayout(n, 0));
      pan.add(jt);
      jt.requestFocusInWindow();
      pan.validate();
      dia.pack();
    });
    dia.pack();
    dia.setVisible(true);
    // Load list
    list.clear();
    Component com[] = pan.getComponents();
    for (Component C:com) {
      String S = ((JTextField)C).getText().trim();
      if (S.length() > 0) list.add(S);
    }
    return list;
  }
  /**
  password allows to obfuscate the input characters.
  @param frame JFrame, null to display JOptions in the center of screen
  @param tit title String
  @return password string
  */
  public static String password(JFrame frame, String tit) {
    JPasswordField pf = new JPasswordField(32);
    JCheckBox cb = new JCheckBox("Show");
    JTextField tf = new JTextField(32);
    // create a panel for pf/tf and cb in 2 rows
    JPanel pan = new JPanel(new java.awt.GridLayout(2,0));
    pan.add(cb); pan.add(pf);
    // convert JOptionPane to JDialog
    JDialog dialog = (new JOptionPane(pan)).createDialog(frame, tit);
    dialog.addComponentListener(listener(pf));
    // toggle between Show/hide
    cb.addItemListener(e->{
      if (cb.isSelected()) {
        tf.setText(new String(pf.getPassword()));
        pan.remove(pf);
        pan.add(tf);
        tf.requestFocusInWindow();
      } else {
        pf.setText(tf.getText());
        pan.remove(tf);
        pan.add(pf);
        pf.requestFocusInWindow();
      }
      pan.validate();
    });
    dialog.pack();
    dialog.setVisible(true);
    if (cb.isSelected()) return tf.getText();
    return new String(pf.getPassword());
  }
  // private area---------------------------
  private static void setMenu(JDialog dia) {
    char[] mne = { 'C', 'P' };
    String[] key = { "Copy", "Paste" };
    JTextField ta = new JTextField();
    Action[] act = {
      ta.getActionMap().get(DefaultEditorKit.copyAction),
      ta.getActionMap().get(DefaultEditorKit.pasteAction)
    };
    JMenuItem[] mItem = new JMenuItem[2];
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("ActionMenu");
    for (int i = 0; i < 2; ++i) {
      mItem[i] = new JMenuItem(act[i]);
      mItem[i].setAccelerator(KeyStroke.getKeyStroke((int)mne[i], InputEvent.CTRL_DOWN_MASK));
      mItem[i].setMnemonic(mne[i]);
      mItem[i].setText(key[i]);
      menu.add(mItem[i]);
    }
    menuBar.add(menu);
    dia.setJMenuBar(menuBar);
  }
  //
  private static ComponentListener listener(final JComponent jcom) {
    ComponentListener l = new ComponentListener() {
      public void componentShown(ComponentEvent e) {
        jcom.requestFocusInWindow();
      }
      public void componentHidden(ComponentEvent e) {}
      public void componentResized(ComponentEvent e) {}
      public void componentMoved(ComponentEvent e) {}
    };
    return l;
  }
}
The following app shows you how to work with the API JOptions. With any character as a starting parameter you can switch the LAF (LookAndFeel) appearance from System default to Nimbus or vice-versa.

Java:
import java.util.*;
import javax.swing.*;
// Joe Nartca (C) - Test JOptions
public class JOptionsTest {
  public static void main(String... a) throws Exception {
    if (a.length == 0) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    else UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    JFrame jf = new JFrame("JOptions");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton but = new JButton("JOptions.password");
    but.addActionListener(e->{
      System.out.println(JOptions.password(jf, "Enter Password"));
    });
    JButton mul = new JButton("Plain Joptions.dynamicInputs");
    mul.addActionListener(e->{
      List<String> list = JOptions.dynamicInputs(jf,"dynamicInputs");
      for (String s : list) System.out.println("- "+s);
    });
    JButton que = new JButton("Question Joptions.dynamicInputs");
    que.addActionListener(e->{
      List<String> list = JOptions.dynamicInputs(jf,"Questioned dynamicInputs", JOptionPane.QUESTION_MESSAGE);
      for (String s : list) System.out.println("- "+s);
    });
    JButton inf = new JButton("Information Joptions.dynamicInputs");
    inf.addActionListener(e->{
      List<String> list = JOptions.dynamicInputs(jf,"Information dynamicInput", JOptionPane.INFORMATION_MESSAGE);
      for (String s : list) System.out.println("- "+s);
    });
    JButton dia = new JButton("JOptions.multipleInputs");
    dia.addActionListener(e->{
      String res[] = JOptions.multipleInputs(jf, "Name!Address!Profession!Country".split("!"), "JOptions.multipleInputs");
      for (String s : res) System.out.println("Result:"+s);
    });
    JPanel pan = new JPanel(new java.awt.GridLayout(5,0));
    pan.add(but); pan.add(mul); pan.add(que); pan.add(inf);
    pan.add(dia);
    jf.add(pan);
    jf.pack();
    jf.setVisible(true);   
  }
}
and the JOptions Popus are:
JOptionPassword_1.png JOptionPassword_2.png

pDynamic.png qDynamic.png iDynamic.png

Multiple.png

CommandScreen.png
 
Sửa lần cuối:

Joe

Thành viên VIP
21/1/13
2,958
1,323
113
For the multipleInputs with String Array for multiple Choices:
Java:
    JButton cbs = new JButton("JOptions.multipleInputs");
    cbs.addActionListener(e->{
       // Age and Gender as String Array.
      Object[] objs = { null, "20!21!22!23!24!25!26!27!28!29!30!31!32!33!34!35!36!37!38!39!40!41!42!43!44!45!".split("!"),
                              "male!female".split("!"), null, null, null, null };
      String res[] = JOptions.multipleInputs(jf, "Name!Age!Gender!Address!Profession!Country".split("!"), objs,
                                             "JOptions.multipleInputs");
      for (String s : res) System.out.println("Result:"+s);
ComboMultiple.png

To download the full codes: jop.zip
 

Attachments

Sửa lần cuối: