Simple GUI dialog for a Simple App
Java
84
White

Joe viết ngày 14/07/2018

Hi

Time for something useful. Today I show you how to build a simple GUI Dialog API. When you write an example to explain some APIs you've developed and you usually confront a "wee" problem to create an example using:

  • some plain text dialog or
  • a simple GUI dialog

A plain text dialog usually bases on "printf( ), scanf( )" in C/C++, or "Console.ReadLine( ), Console.WriteLine( )" in C#, or "System.out.println( ), Scanner(System.in)" in JAVA. And it could be as following:

in C#

   class Program
    {
        static void Main(string[] args)
        {
            float f = 0;
            Console.WriteLine("Enter a float:");
            string fstring = Console.ReadLine();
            if (float.TryParse(fstring, out f))
            {
                Console.WriteLine("Read f = {0}", f);
            }
            else
            {
                Console.WriteLine("Invalid input");
            }
        }
    }

in JAVA

public class Program {
  public static void main(String... args) {
     Scanner scanner = new Scanner(System.in);
     System.out.println("Enter a float:");
     float f = scanner.nextFloat();
     System.out.println("Read f = "+f);
  }
}

Very simple and very effortless. But it looks somehow a bit "newbie-ish", a bit primitive, unappetizing. Not very fancy, isn't it? In an era when images govern the world why should we still selfie ourselves with such an archaic technique? Why not a bit GUI? Images make the world becoming more colorful and more comprehensible.

In C# it's usually a bit more complicated than in JAVA. C# users have to toil with the HRESULT TaskDialog while JAVA users enjoy an ease of use with JOptionPane. Whatever it is you have to work a bit with the named API. Instead of System.out.println() and Scanner.nextXYZ() a GUI dialog is so simple that you have to astound:

public class Program {
  public static void main(String... args) {
     String fstring = javax.swing.JOptionPane.showInputDialog("Enter a float:");
     float f = Float.parseFloat(fstring);
     javax.swing.JOptionPane.showMessageDialog(null,
                                   "Read f = "+f,
                                   "information",
                                   javax.swing.JOptionPane.INFORMATION_MESSAGE);
  }
}

Simple and easy, isn't it? But what's about complicated stuffs like inputting a "password" (which should be blurred or defaced) or pasting a long copied string into an input field (instead of patiently typing a long text) ? Well, it's simple. If you read the JOptionPane API carefully you might learn this harmless exemplary pattern (which is the door to an amazing GUI world):

Direct Use:
To create and use an JOptionPane directly, the standard pattern is roughly as follows:

     JOptionPane pane = new JOptionPane(arguments);
     pane.set.Xxxx(...); // Configure
     JDialog dialog = pane.createDialog(parentComponent, title);
     dialog.show();
     Object selectedValue = pane.getValue();
     if(selectedValue == null)
       return CLOSED_OPTION;
     //If there is not an array of option buttons:
     if(options == null) {
       if(selectedValue instanceof Integer)
          return ((Integer)selectedValue).intValue();
       return CLOSED_OPTION;
     }
     //If there is an array of option buttons:
     for(int counter = 0, maxCounter = options.length;
        counter < maxCounter; counter++) {
        if(options[counter].equals(selectedValue))
        return counter;
     }
     return CLOSED_OPTION;

This innocent example shows us how we can personally "tailor" a JOptionPane.

Note: Since Oracle becomes the master of SUN many things go "bad". Why? In this "passage" you see the line dialog.show(); which is deprecated and it's strongly discouraged from using it. Instead of dialog.show() it should (or must) be dialog.setVisible(true).

I show you hereunder two tailored JOptionPanes to cope with the needs for a JPasswordField and for a JTextField with the Copy&Paste features.

public class MyJOptionPane {
  /**
  This is an input of JOptionPane with JPasswordField properties
  @param msg String, the title for JOptionPane
  @return String of JPasswordText 
  */
  public static String passwordField(String msg) {
    JPasswordField pf = new JPasswordField();
    JOptionPane op = new JOptionPane(pf);
    JDialog dialog = op.createDialog(msg);
    //Add a listener to the dialog to request focus of Password Field
    dialog.addComponentListener(new ComponentListener(){
      public void componentShown(ComponentEvent e) {
        pf.requestFocusInWindow();
      }
      public void componentHidden(ComponentEvent e) {}
      public void componentResized(ComponentEvent e) {}
      public void componentMoved(ComponentEvent e) {}
    });
    dialog.setVisible(true);
    return new String(pf.getPassword());
  }
  /**
  This is an input of JOptionPane with Copy and Paste 
  @param msg String, the title for JOptionPane
  @return String of JTextText 
  */
  public static String textField(String msg) {
    JTextField tf = new JTextField( );
    JOptionPane op = new JOptionPane(tf);
    JDialog dialog = op.createDialog(msg);
    //Add a listener to the dialog to request focus of Password Field
    dialog.addComponentListener(new ComponentListener(){
      public void componentShown(ComponentEvent e) {
        tf.requestFocusInWindow();
      }
      public void componentHidden(ComponentEvent e) {}
      public void componentResized(ComponentEvent e) {}
      public void componentMoved(ComponentEvent e) {}
    });
    tf.addMouseListener(new MouseListener(){
      public void mousePressed(MouseEvent e){
        if (e.isPopupTrigger())
          showMenu(e);
      }    
      public void mouseReleased(MouseEvent e){
        if (e.isPopupTrigger())
          showMenu(e);
      }
      public void mouseEntered(MouseEvent e) { }
      public void mouseClicked(MouseEvent e) { }
      public void mouseExited(MouseEvent e)  { }
      //
      protected void showMenu(MouseEvent e){
        CopyPaste menu = new CopyPaste(tf);
        menu.show(e.getComponent(), e.getX(), e.getY());
      }       
    });
    dialog.setVisible(true);
    return tf.getText();
  }
}
// CopyPaste protected class
class CopyPaste extends JPopupMenu {
  public JPopup(JComponent tf){
    JMenuItem copy = new JMenuItem(tf.getActionMap().get(DefaultEditorKit.copyAction));
    copy.setAccelerator(KeyStroke.getKeyStroke((int)'C', ActionEvent.CTRL_MASK));
    copy.setText("Copy");
    add(copy);

    JMenuItem paste = new JMenuItem(tf.getActionMap().get(DefaultEditorKit.pasteAction));
    paste.setAccelerator(KeyStroke.getKeyStroke((int)'P', ActionEvent.CTRL_MASK));
    paste.setText("Paste");
    add(paste);
  }
}

Invocation

    String pw  = MyJOptionPane.passwordField("Your Password");
    String uID = MyJOptionPane.textField("User's ID");

And the results are as following
ALT
ALT

Enjoy the simplest GUI-Dialog app.

Bình luận


White
{{ comment.user.name }}
Bỏ hay Hay
{{comment.like_count}}
Male avatar
{{ comment_error }}
Hủy
   

Hiển thị thử

Chỉnh sửa

White

Joe

31 bài viết.
280 người follow
Kipalog
{{userFollowed ? 'Following' : 'Follow'}}
Cùng một tác giả
White
36 14
Chao cac ban To the Admins: if you think that this posting breaks some rules of your site please just delete it. NO need to send me a feedback. Th...
Joe viết 4 tháng trước
36 14
White
28 15
Fuzzy Logic and Machine Learning Hi First of all: I apologize everyone for my writing in English. I come to this site because someone of Daynhauh...
Joe viết 1 năm trước
28 15
White
27 11
You're a fresh graduate and work for more than 12 months in an IT company with some boring coding tasks... The tasks are unchallenging. Day in, day...
Joe viết 4 tháng trước
27 11
Bài viết liên quan
White
0 0
Trong bài viết này, một số hình ảnh hoặc nọi dung có thể bị thiếu do quá trình chế bản. Vui lòng xem nội dung ở blog gốc sau: (Link) (Link), chúng...
programmerit viết 3 năm trước
0 0
Male avatar
9 5
Facade Design Patern Facade Patern thuộc vào họ mô hình cấu trúc (structural patern). Facade patern phát biểu rằng : "just provide a unified an...
DuongVanTien viết 2 năm trước
9 5
White
4 2
Một số hàm giúp mapping data đơn giản với Groovy Ví dụ với list data như sau: def student1 = name: "Huan", age: 22, gender: "male"] def student...
Tất Huân viết 4 tháng trước
4 2
{{like_count}}

kipalog

{{ comment_count }}

bình luận

{{liked ? "Đã kipalog" : "Kipalog"}}


White
{{userFollowed ? 'Following' : 'Follow'}}
31 bài viết.
280 người follow

 Đầu mục bài viết

Vẫn còn nữa! x

Kipalog vẫn còn rất nhiều bài viết hay và chủ đề thú vị chờ bạn khám phá!