Package com.subhajit.gui

Source Code of com.subhajit.gui.Dialog

/*
* Created on Jul 5, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.subhajit.gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.File;
import java.util.Map;
import java.util.Set;

import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;

import com.subhajit.gui.form.BindingEditor;
import com.subhajit.gui.form.BindingSpec;

/**
* @author Administrator
*
*         TODO To change the template for this generated type comment go to
*         Window - Preferences - Java - Code Generation - Code and Comments
*/
public abstract class Dialog {
  private static final int DEFAULT_HEIGHT = 400;
  private static final int DEFAULT_WIDTH = 500;

  /**
   * Private constructor, since we do not expect to instantiate this Class
   * directly
   *
   */
  private Dialog() {
    super();
  }

  public static JDialog newDialog(JPanel In, String[] Options,
      String DialogCaption, int width, int height) {
    JOptionPane op = new JOptionPane(In);
    op.setOptions(Options);
    op.setVisible(true);
    op.invalidate();
    JDialog dlg = op.createDialog(null, DialogCaption);
    dlg.setSize(width, height);
    In.putClientProperty(JOptionPane.class.getName(), op);
    return dlg;
  }

  /**
   * Creates and returns a new JDialog initialized with the given panel.
   *
   * @param panel
   * @param buttons
   * @return
   */
  public static JDialog newDialog(JPanel panel, int width, int height) {
    JDialog topFrame = new JDialog();
    topFrame.getContentPane().setLayout(new GridLayout(1, 1));
    topFrame.getContentPane().add(panel);
    panel.invalidate();
    panel.setVisible(true);
    if (width >= 0 && height >= 0) {
      topFrame.setSize(width, height);
    } else {
      topFrame.pack();
    }
    FrameUtils.centerDialog(topFrame);
    return topFrame;
  }

  public static JDialog newDialog(JPanel panel) {
    return newDialog(panel, -1, -1);
  }

  public static String ask(String caption, String initialValue,
      final int... dimensions) {
    Dimension size = getSize(dimensions);
    Map<String, Object> values = BindingEditor.edit(
        new BindingSpec[] { new BindingSpec.BindingSpecBuilder()
            .setValue(initialValue).setLabel(caption)
            .createBindingSpec() }, size.width, size.height);
    if (values == null) {
      return null;
    }
    return (String) values.get(caption);
  }

  private static Dimension getSize(final int... dimensions) {
    Dimension size = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    if (dimensions != null && dimensions.length > 0) {
      // Dimensions have been specified.
      size.width = dimensions[0];
      if (dimensions.length > 1) {
        size.height = dimensions[1];
      }
    }
    if (size.width <= 0) {
      throw new IllegalArgumentException("Width cannot be negative.");
    }
    if (size.height <= 0) {
      throw new IllegalArgumentException("Height cannot be negative.");
    }
    return size;
  }

  public static String askPassword(String caption, String initialValue,
      final int... dimensions) {
    Dimension size = getSize(dimensions);
    Map<String, Object> values = BindingEditor.edit(
        new BindingSpec[] { new BindingSpec.BindingSpecBuilder()
            .setValue(initialValue.toCharArray()).setLabel(caption)
            .createBindingSpec() }, size.width, size.height);
    if (values == null) {
      return null;
    }
    return new String((char[]) values.get(caption));
  }

  public static String select(String caption, String[] options,
      String initialValue, final int... dimensions) {
    Dimension size = getSize(dimensions);
    Map<String, Object> values = BindingEditor.edit(
        new BindingSpec[] { new BindingSpec.BindingSpecBuilder()
            .setLabel(caption).setValue(options)
            .createBindingSpec() }, size.width, size.height);
    if (values == null) {
      return null;
    }
    return (String) values.get(caption);
  }

  /**
   * Creates a modal dialog containing the given panel, and returns it.
   *
   * @param In
   * @param DialogCaption
   * @return
   */
  public static JDialog makeModalDialog(JPanel In, String[] Options,
      String DialogCaption) {
    JOptionPane op = new JOptionPane(In);
    op.setOptions(Options);
    op.setVisible(true);
    op.invalidate();
    JDialog dialog = op.createDialog(null, DialogCaption);
    dialog.setModal(true);
    FrameUtils.centerDialog(dialog);
    In.putClientProperty(JOptionPane.class.getName(), op);
    return dialog;
  }

  public static String showModalDialog(JPanel In, String[] Options,
      String DialogCaption, int width, int height) {
    JOptionPane op = new JOptionPane(In);
    op.setOptions(Options);
    op.setVisible(true);
    op.invalidate();
    JDialog dlg = op.createDialog(null, DialogCaption);
    dlg.setSize(width, height);
    dlg.setModal(true);
    dlg.setVisible(true);
    return (op.getValue() == null ? null : op.getValue().toString());
  }

  /**
   * Simple message box showing an information message. The message is an HTML
   * formatted String.
   *
   * @param Msg
   * @param ButtonCaptions
   * @param DialogCaption
   */
  public static Object info(String htmlMessage, String[] buttonCaptions,
      String dialogCaption) {
    JPanel messagePanel = new JPanel();
    messagePanel.setVisible(true);
    messagePanel.invalidate();
    messagePanel.setLayout(new GridLayout(1, 1));
    // messagePanel.setBorder(new LineBorder(Color.black,1));

    JEditorPane editorPane = setupHtmlComponent(htmlMessage);
    messagePanel.add(editorPane);
    JScrollPane sp = new JScrollPane();
    sp.setVisible(true);
    sp.setViewportView(messagePanel);
    JDialog Dlg = Dialog.makeModalDialog(messagePanel, buttonCaptions,
        dialogCaption);

    JOptionPane optionPane = (JOptionPane) messagePanel
        .getClientProperty(JOptionPane.class.getName());

    // The dialog must be at least the dimensions 1/3 and 1/7 of the screen.
    int widthNum = 1;
    int widthDenon = 3;
    int heightNum = 1;
    int heightDenom = 7;
    int desiredMinimumWidth = ((widthNum * FrameUtils.ScreenSize.width) / widthDenon);
    int desiredMinimumHeight = ((heightNum * FrameUtils.ScreenSize.height) / heightDenom);
    if (Dlg.getSize().width < desiredMinimumWidth) {
      Dlg
          .setSize(new Dimension(desiredMinimumWidth,
              Dlg.getSize().height));
    }
    if (Dlg.getSize().height < desiredMinimumHeight) {
      Dlg
          .setSize(new Dimension(Dlg.getSize().width,
              desiredMinimumHeight));
    }
    FrameUtils.centerDialog(Dlg);
    Dlg.setVisible(true);
    return optionPane.getValue();
  }

  public static JEditorPane setupHtmlComponent(String htmlMessage) {
    JPanel messagePanel = new JPanel();
    messagePanel.setVisible(true);
    messagePanel.invalidate();
    messagePanel.setLayout(new GridLayout(1, 1));

    // Setup the background color HTML fragment
    Color BkColor = messagePanel.getBackground();
    StringBuffer ColorBuf = new StringBuffer();
    ColorBuf.append("BGCOLOR=\"#");
    String RedComponent = Integer.toHexString(BkColor.getRed());
    if (RedComponent.length() < 2) {
      ColorBuf.append("0");
      ColorBuf.append(RedComponent);
    } else
      ColorBuf.append(RedComponent);

    String GreenComponent = Integer.toHexString(BkColor.getGreen());
    if (GreenComponent.length() < 2) {
      ColorBuf.append("0");
      ColorBuf.append(GreenComponent);
    } else
      ColorBuf.append(GreenComponent);

    String BlueComponent = Integer.toHexString(BkColor.getBlue());
    if (BlueComponent.length() < 2) {
      ColorBuf.append("0");
      ColorBuf.append(BlueComponent);
    } else
      ColorBuf.append(BlueComponent);

    ColorBuf.append("\"");

    StringBuffer MsgBuf = new StringBuffer();
    MsgBuf.append("<html><head></head><body ");
    MsgBuf.append(ColorBuf.toString());
    MsgBuf.append(">");

    // MsgBuf
    // .append("<table cellspacing=\"0\" cellpadding=\"0\"
    // width=\"100%\"><tr><td align=\"left\" width=\"100%\">");
    MsgBuf.append("<font face=\"Courier");
    MsgBuf.append(messagePanel.getFont().getName());
    MsgBuf.append("\" size=\6");
    MsgBuf.append(3);
    MsgBuf.append("\">");
    MsgBuf.append(htmlMessage);
    MsgBuf.append("</font>");
    // MsgBuf.append("</td></tr></table>");
    MsgBuf.append("</body>");

    JEditorPane ep = new JEditorPane("text/html", MsgBuf.toString());
    ep.setBackground(BkColor);
    ep.setEditable(false);
    ep.setFont(messagePanel.getFont());
    ep.setVisible(true);
    ep.invalidate();
    ep.setBorder(new LineBorder(messagePanel.getBackground()));
    return ep;
  }

  public static void info(String htmlMessage, String dialogCaption) {
    Dialog.info(htmlMessage, new String[] { "Ok" }, dialogCaption);
  }

  public static void main(String[] args) {
    try {
      Dialog.info("Hi there", new String[] { "Yes", "No" }, "Grok");
      Dialog
          .info(
              "GrokGrokGrokGrokGrokGrokGrokGrokGrokGrok<br>GrokGrokGrokGrokGrokGrokGrokGrokGrok<br>GrokGrokGrokGrokGrokGrokGrokGrokGrok<br>GrokGrokGrokGrokGrokGrokGrokGrokGrok<br>GrokGrokGrokGrokGrokGrokGrokGrokGrok<br>GrokGrokGrokGrokGrokGrokGrokGrokGrok<br>GrokGrokGrokGrokGrokGrokGrokGrokGrok",
              new String[] { "Yes", "No" }, "Hi there");
      Dialog
          .info(
              "GrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrokGrok",
              new String[] { "Yes", "No" }, "Hi there");
    } catch (Throwable exc) {
      exc.printStackTrace();
    } finally {
      System.exit(0);
    }
  }

  public static final File[] selectFiles(JFileChooser chooser,
      File initialDirectory, final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    if (initialDirectory != null && initialDirectory.exists()
        && initialDirectory.isDirectory()) {
      chooser.setCurrentDirectory(initialDirectory);
    }
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
      @Override
      public boolean accept(File f) {
        if (f.isDirectory()) {
          return true;
        }
        if (extensionsMayBeNull == null
            || extensionsMayBeNull.isEmpty()) {
          return true;
        }
        int lastIndex = f.getName().lastIndexOf('.');
        if (lastIndex != -1) {
          String extension = f.getName().substring(lastIndex + 1);
          if (extensionsMayBeNull.contains(extension)) {
            return true;
          }
        }
        return false;
      }

      @Override
      public String getDescription() {
        return descriptionMayBeNull;
      }
    });
    JDialog dialog = new JDialog();
    dialog.setSize(800, 600);
    dialog.setModal(true);
    if (chooser.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION) {
      if (chooser.getSelectedFiles().length == 0) {
        return new File[] { chooser.getSelectedFile() };
      }
      return chooser.getSelectedFiles();
    } else {
      return null;
    }
  }

  public static final File selectDirectory(JFileChooser chooser,
      File initialDirectory, final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
      @Override
      public boolean accept(File f) {
        if (f.isDirectory()) {
          return true;
        }
        return false;
      }

      @Override
      public String getDescription() {
        return descriptionMayBeNull;
      }
    });
    JDialog dialog = new JDialog();
    dialog.setSize(800, 600);
    dialog.setModal(true);
    if (chooser.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION) {
      return chooser.getSelectedFile();
    } else {
      return null;
    }
  }

  /**
   * Allows the user to select and return multiple files and directories.
   *
   * @param initialDirectory
   * @param extensionsMayBeNull
   * @param descriptionMayBeNull
   * @return
   */
  public static final File[] selectMultipleFileOrDirectories(
      File initialDirectory, final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setMultiSelectionEnabled(true);
    return selectFiles(chooser, initialDirectory, extensionsMayBeNull,
        descriptionMayBeNull);
  }

  /**
   * Allows the user to select and return a single file or directory.
   *
   * @param initialDirectory
   * @param extensionsMayBeNull
   * @param descriptionMayBeNull
   * @return
   */
  public static final File selectSingleFileOrDirectory(File initialDirectory,
      final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setCurrentDirectory(initialDirectory);
    File[] selectedFiles = selectFiles(chooser, initialDirectory,
        extensionsMayBeNull, descriptionMayBeNull);
    if (selectedFiles == null || selectedFiles.length == 0) {
      return null;
    } else {
      return selectedFiles[0];
    }
  }

  public static final File selectSingleFile(File initialDirectory,
      final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setCurrentDirectory(initialDirectory);
    File[] selectedFiles = selectFiles(chooser, initialDirectory,
        extensionsMayBeNull, descriptionMayBeNull);
    if (selectedFiles == null || selectedFiles.length == 0) {
      return null;
    } else {
      return selectedFiles[0];
    }
  }

  public static final File[] selectFileToSaveAs(File initialDirectory,
      String initialFileName, final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setCurrentDirectory(initialDirectory);
    chooser.setSelectedFile(new File(initialDirectory, initialFileName));
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
      @Override
      public boolean accept(File f) {
        if (f.isDirectory()) {
          return true;
        }
        if (extensionsMayBeNull == null
            || extensionsMayBeNull.isEmpty()) {
          return true;
        }
        int lastIndex = f.getName().lastIndexOf('.');
        if (lastIndex != -1) {
          String extension = f.getName().substring(lastIndex + 1);
          if (extensionsMayBeNull.contains(extension)) {
            return true;
          }
        }
        return false;
      }

      @Override
      public String getDescription() {
        return descriptionMayBeNull;
      }
    });
    JDialog dialog = new JDialog();
    dialog.setSize(800, 600);
    dialog.setModal(true);
    if (chooser.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION) {
      if (chooser.getSelectedFiles().length == 0) {
        return new File[] { chooser.getSelectedFile() };
      }
      return chooser.getSelectedFiles();
    } else {
      return null;
    }
  }

  public static final File selectSingleDirectory(File initialDirectory,
      final Set<String> extensionsMayBeNull,
      final String descriptionMayBeNull) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    File selectedDirectory = selectDirectory(chooser, initialDirectory,
        extensionsMayBeNull, descriptionMayBeNull);
    if (selectedDirectory == null) {
      return null;
    } else {
      return selectedDirectory;
    }
  }

}
TOP

Related Classes of com.subhajit.gui.Dialog

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.