List of usage examples for javax.swing JDialog dispose
public void dispose()
From source file:com.t3.macro.api.functions.input.InputFunctions.java
/** * <pre>//ww w . j a v a 2 s.c o m * <span style="font-family:sans-serif;">The input() function prompts the user to input several variable values at once. * * Each of the string parameters has the following format: * "varname|value|prompt|inputType|options" * * Only the first section is required. * varname - the variable name to be assigned * value - sets the initial contents of the input field * prompt - UI text shown for the variable * inputType - specifies the type of input field * options - a string of the form "opt1=val1; opt2=val2; ..." * * The inputType field can be any of the following (defaults to TEXT): * TEXT - A text field. * "value" sets the initial contents. * The return value is the string in the text field. * Option: WIDTH=nnn sets the width of the text field (default 16). * LIST - An uneditable combo box. * "value" populates the list, and has the form "item1,item2,item3..." (trailing empty strings are dropped) * The return value is the numeric index of the selected item. * Option: SELECT=nnn sets the initial selection (default 0). * Option: VALUE=STRING returns the string contents of the selected item (default NUMBER). * Option: TEXT=FALSE suppresses the text of the list item (default TRUE). * Option: ICON=TRUE causes icon asset URLs to be extracted from the "value" and displayed (default FALSE). * Option: ICONSIZE=nnn sets the size of the icons (default 50). * CHECK - A checkbox. * "value" sets the initial state of the box (anything but "" or "0" checks the box) * The return value is 0 or 1. * No options. * RADIO - A group of radio buttons. * "value" is a list "name1, name2, name3, ..." which sets the labels of the buttons. * The return value is the index of the selected item. * Option: SELECT=nnn sets the initial selection (default 0). * Option: ORIENT=H causes the radio buttons to be laid out on one line (default V). * Option: VALUE=STRING causes the return value to be the string of the selected item (default NUMBER). * LABEL - A label. * The "varname" is ignored and no value is assigned to it. * Option: TEXT=FALSE, ICON=TRUE, ICONSIZE=nnn, as in the LIST type. * PROPS - A sub-panel with multiple text boxes. * "value" contains a StrProp of the form "key1=val1; key2=val2; ..." * One text box is created for each key, populated with the matching value. * Option: SETVARS=SUFFIXED causes variable assignment to each key name, with appended "_" (default NONE). * Option: SETVARS=UNSUFFIXED causes variable assignment to each key name. * TAB - A tabbed dialog tab is created. Subsequent variables are contained in the tab. * Option: SELECT=TRUE causes this tab to be shown at start (default SELECT=FALSE). * * All inputTypes except TAB accept the option SPAN=TRUE, which causes the prompt to be hidden and the input * control to span both columns of the dialog layout (default FALSE). * </span> * </pre> * @param parameters a list of strings containing information as described above * @return a HashMap with the returned values or null if the user clicked on cancel * @author knizia.fan * @throws MacroException */ public static Map<String, String> input(TokenView token, String... parameters) throws MacroException { // Extract the list of specifier strings from the parameters // "name | value | prompt | inputType | options" List<String> varStrings = new ArrayList<String>(); for (Object param : parameters) { String paramStr = (String) param; if (StringUtils.isEmpty(paramStr)) { continue; } // Multiple vars can be packed into a string, separated by "##" for (String varString : StringUtils.splitByWholeSeparator(paramStr, "##")) { if (StringUtils.isEmpty(paramStr)) { continue; } varStrings.add(varString); } } // Create VarSpec objects from each variable's specifier string List<VarSpec> varSpecs = new ArrayList<VarSpec>(); for (String specifier : varStrings) { VarSpec vs; try { vs = new VarSpec(specifier); } catch (VarSpec.SpecifierException se) { throw new MacroException(se); } catch (InputType.OptionException oe) { throw new MacroException(I18N.getText("macro.function.input.invalidOptionType", oe.key, oe.value, oe.type, specifier)); } varSpecs.add(vs); } // Check if any variables were defined if (varSpecs.isEmpty()) return Collections.emptyMap(); // No work to do, so treat it as a successful invocation. // UI step 1 - First, see if a token is given String dialogTitle = "Input Values"; if (token != null) { String name = token.getName(), gm_name = token.getGMName(); boolean isGM = TabletopTool.getPlayer().isGM(); String extra = ""; if (isGM && gm_name != null && gm_name.compareTo("") != 0) extra = " for " + gm_name; else if (name != null && name.compareTo("") != 0) extra = " for " + name; dialogTitle = dialogTitle + extra; } // UI step 2 - build the panel with the input fields InputPanel ip = new InputPanel(varSpecs); // Calculate the height // TODO: remove this workaround int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; int maxHeight = screenHeight * 3 / 4; Dimension ipPreferredDim = ip.getPreferredSize(); if (maxHeight < ipPreferredDim.height) { ip.modifyMaxHeightBy(maxHeight - ipPreferredDim.height); } // UI step 3 - show the dialog JOptionPane jop = new JOptionPane(ip, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); JDialog dlg = jop.createDialog(TabletopTool.getFrame(), dialogTitle); // Set up callbacks needed for desired runtime behavior dlg.addComponentListener(new FixupComponentAdapter(ip)); dlg.setVisible(true); int dlgResult = JOptionPane.CLOSED_OPTION; try { dlgResult = (Integer) jop.getValue(); } catch (NullPointerException npe) { } dlg.dispose(); if (dlgResult == JOptionPane.CANCEL_OPTION || dlgResult == JOptionPane.CLOSED_OPTION) return null; HashMap<String, String> results = new HashMap<String, String>(); // Finally, assign values from the dialog box to the variables for (ColumnPanel cp : ip.columnPanels) { List<VarSpec> panelVars = cp.varSpecs; List<JComponent> panelControls = cp.inputFields; int numPanelVars = panelVars.size(); StringBuilder allAssignments = new StringBuilder(); // holds all values assigned in this tab for (int varCount = 0; varCount < numPanelVars; varCount++) { VarSpec vs = panelVars.get(varCount); JComponent comp = panelControls.get(varCount); String newValue = null; switch (vs.inputType) { case TEXT: { newValue = ((JTextField) comp).getText(); break; } case LIST: { Integer index = ((JComboBox) comp).getSelectedIndex(); if (vs.optionValues.optionEquals("VALUE", "STRING")) { newValue = vs.valueList.get(index); } else { // default is "NUMBER" newValue = index.toString(); } break; } case CHECK: { Integer value = ((JCheckBox) comp).isSelected() ? 1 : 0; newValue = value.toString(); break; } case RADIO: { // This code assumes that the Box container returns components // in the same order that they were added. Component[] comps = ((Box) comp).getComponents(); int componentCount = 0; Integer index = 0; for (Component c : comps) { if (c instanceof JRadioButton) { JRadioButton radio = (JRadioButton) c; if (radio.isSelected()) index = componentCount; } componentCount++; } if (vs.optionValues.optionEquals("VALUE", "STRING")) { newValue = vs.valueList.get(index); } else { // default is "NUMBER" newValue = index.toString(); } break; } case LABEL: { newValue = null; // The variable name is ignored and not set. break; } case PROPS: { // Read out and assign all the subvariables. // The overall return value is a property string (as in StrPropFunctions.java) with all the new settings. Component[] comps = ((JPanel) comp).getComponents(); StringBuilder sb = new StringBuilder(); int setVars = 0; // "NONE", no assignments made if (vs.optionValues.optionEquals("SETVARS", "SUFFIXED")) setVars = 1; if (vs.optionValues.optionEquals("SETVARS", "UNSUFFIXED")) setVars = 2; if (vs.optionValues.optionEquals("SETVARS", "TRUE")) setVars = 2; // for backward compatibility for (int compCount = 0; compCount < comps.length; compCount += 2) { String key = ((JLabel) comps[compCount]).getText().split("\\:")[0]; // strip trailing colon String value = ((JTextField) comps[compCount + 1]).getText(); sb.append(key); sb.append("="); sb.append(value); sb.append(" ; "); switch (setVars) { case 0: // Do nothing break; case 1: results.put(key + "_", value); break; case 2: results.put(key, value); break; } } newValue = sb.toString(); break; } default: // should never happen newValue = null; break; } // Set the variable to the value we got from the dialog box. if (newValue != null) { results.put(vs.name, newValue.trim()); allAssignments.append(vs.name + "=" + newValue.trim() + " ## "); } } if (cp.tabVarSpec != null) { results.put(cp.tabVarSpec.name, allAssignments.toString()); } } return results; // success // for debugging: //return debugOutput(varSpecs); }
From source file:Main.java
/** * Initialises the {@link JDialog} for the {@link JComponent}. * /* w ww. j ava 2 s. co m*/ * @param dialog * @param component * @param parentComponent */ private static void initDialog(final JDialog dialog, final JComponent component, final Component parentComponent) { dialog.setResizable(true); dialog.setComponentOrientation(component.getComponentOrientation()); Container contentPane = dialog.getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.add(component, BorderLayout.CENTER); final int buttonWidth = 75; final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS)); buttonPanel.setBorder(BorderFactory.createEmptyBorder(2, 4, 4, 4)); buttonPanel.add(Box.createHorizontalGlue()); @SuppressWarnings("serial") final Action closeAction = new AbstractAction("Close") { @Override public void actionPerformed(ActionEvent e) { dialog.dispose(); } }; final JButton button = new JButton(closeAction); fixWidth(button, buttonWidth); buttonPanel.add(button); contentPane.add(buttonPanel, BorderLayout.SOUTH); if (JDialog.isDefaultLookAndFeelDecorated()) { boolean supportsWindowDecorations = UIManager.getLookAndFeel().getSupportsWindowDecorations(); if (supportsWindowDecorations) { dialog.setUndecorated(true); component.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); } } dialog.pack(); dialog.setLocationRelativeTo(parentComponent); WindowAdapter adapter = new WindowAdapter() { // private boolean gotFocus = false; public void windowClosing(WindowEvent we) { fireAction(we.getSource(), closeAction, "close"); } }; dialog.addWindowListener(adapter); dialog.addWindowFocusListener(adapter); }
From source file:Main.java
/** * Adds a glass layer to the dialog to intercept all key events. If the * espace key is pressed, the dialog is disposed (either with a fadeout * animation, or directly)./*from w w w.j a v a 2s. c om*/ */ public static void addEscapeToCloseSupport(final JDialog dialog, final boolean fadeOnClose) { LayerUI<Container> layerUI = new LayerUI<Container>() { private boolean closing = false; @Override public void installUI(JComponent c) { super.installUI(c); ((JLayer) c).setLayerEventMask(AWTEvent.KEY_EVENT_MASK); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); ((JLayer) c).setLayerEventMask(0); } @Override public void eventDispatched(AWTEvent e, JLayer<? extends Container> l) { if (e instanceof KeyEvent && ((KeyEvent) e).getKeyCode() == KeyEvent.VK_ESCAPE) { if (closing) return; closing = true; if (fadeOnClose) fadeOut(dialog); else dialog.dispose(); } } }; JLayer<Container> layer = new JLayer<>(dialog.getContentPane(), layerUI); dialog.setContentPane(layer); }
From source file:Main.java
/** * Creates an animation to fade the dialog opacity from 0 to 1, wait at 1 * and then fade to 0 and dispose./*from www.j a v a 2 s . c om*/ * * @param dialog the dialog to display * @param delay the delay in ms before starting and between each change * @param incrementSize the increment size * @param displayTime the time in ms the dialog is fully visible */ public static void fadeInAndOut(final JDialog dialog, final int delay, final float incrementSize, final int displayTime) { final Timer timer = new Timer(delay, null); timer.setRepeats(true); timer.addActionListener(new ActionListener() { private float opacity = 0; private boolean displayed = false; @Override public void actionPerformed(ActionEvent e) { if (!displayed) { opacity += incrementSize; dialog.setOpacity(Math.min(opacity, 1)); // requires java 1.7 if (opacity >= 1) { timer.setDelay(displayTime); displayed = true; } } else { timer.setDelay(delay); opacity -= incrementSize; dialog.setOpacity(Math.max(opacity, 0)); // requires java 1.7 if (opacity < 0) { timer.stop(); dialog.dispose(); } } } }); dialog.setOpacity(0); // requires java 1.7 timer.start(); dialog.setVisible(true); }
From source file:net.pms.PMS.java
/** * Check if server is running in headless (console) mode. * * @return true if server is running in headless (console) mode, false otherwise *///from w w w. j a va 2s .c o m public static synchronized boolean isHeadless() { if (isHeadless == null) { if (System.getProperty(CONSOLE) != null) { isHeadless = true; } else { try { javax.swing.JDialog d = new javax.swing.JDialog(); d.dispose(); isHeadless = false; } catch (Throwable throwable) { isHeadless = true; } } } return isHeadless; }
From source file:Main.java
public static boolean showModalDialogOnEDT(JComponent contents, String title, String okButtonMessage, String cancelButtonMessage, ModalityType modalityType, final boolean systemExitOnDisposed) { class Result { boolean OK = false; }//from www .java 2 s . co m final Result result = new Result(); final JDialog dialog = new JDialog((Frame) null, title, true) { @Override public void dispose() { super.dispose(); if (systemExitOnDisposed) { System.exit(0); } } }; // ensure it doesn't block other dialogs if (modalityType != null) { dialog.setModalityType(modalityType); } // See http://stackoverflow.com/questions/1343542/how-do-i-close-a-jdialog-and-have-the-window-event-listeners-be-notified dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); if (okButtonMessage != null) { buttonPane.add(new JButton(new AbstractAction(okButtonMessage) { @Override public void actionPerformed(ActionEvent e) { result.OK = true; dialog.dispose(); } })); } if (cancelButtonMessage != null) { buttonPane.add(new JButton(new AbstractAction(cancelButtonMessage) { @Override public void actionPerformed(ActionEvent e) { dialog.dispose(); } })); } JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); panel.setLayout(new BorderLayout()); panel.add(contents, BorderLayout.CENTER); panel.add(buttonPane, BorderLayout.SOUTH); // startup frame dialog.getContentPane().add(panel); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.pack(); // This hopefully centres the dialog even though the parameter is null // see http://stackoverflow.com/questions/213266/how-do-i-center-a-jdialog-on-screen dialog.setLocationRelativeTo(null); dialog.setVisible(true); return result.OK; }
From source file:de.codesourcery.jasm16.ide.ui.utils.UIUtils.java
/** * // ww w . j av a2s . co m * @param parent * @param title * @param message * @return <code>true</code> if project should also be physically deleted, * <code>false</code> is project should be deleted but all files should be left alone, * <code>null</code> if user cancelled the dialog/project should not be deleted */ public static Boolean showDeleteProjectDialog(IAssemblyProject project) { final JDialog dialog = new JDialog((Window) null, "Delete project " + project.getName()); dialog.setModal(true); final JTextArea message = createMultiLineLabel( "Do you really want to delete project '" + project.getName() + " ?"); final JCheckBox checkbox = new JCheckBox("Delete project files"); final DialogResult[] outcome = { DialogResult.CANCEL }; final JButton yesButton = new JButton("Yes"); yesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { outcome[0] = DialogResult.YES; dialog.dispose(); } }); final JButton noButton = new JButton("No"); noButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { outcome[0] = DialogResult.NO; dialog.dispose(); } }); final JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { outcome[0] = DialogResult.CANCEL; dialog.dispose(); } }); final JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); buttonPanel.add(yesButton); buttonPanel.add(noButton); buttonPanel.add(cancelButton); final JPanel messagePanel = new JPanel(); messagePanel.setLayout(new GridBagLayout()); GridBagConstraints cnstrs = constraints(0, 0, true, false, GridBagConstraints.NONE); cnstrs.gridwidth = GridBagConstraints.REMAINDER; cnstrs.weighty = 0; cnstrs.gridheight = 1; messagePanel.add(message, cnstrs); cnstrs = constraints(0, 1, true, true, GridBagConstraints.NONE); cnstrs.gridwidth = GridBagConstraints.REMAINDER; cnstrs.gridheight = 1; cnstrs.weighty = 0; messagePanel.add(checkbox, cnstrs); final JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); cnstrs = constraints(0, 0, true, false, GridBagConstraints.NONE); cnstrs.gridwidth = GridBagConstraints.REMAINDER; cnstrs.gridheight = 1; cnstrs.weighty = 0; cnstrs.insets = new Insets(5, 2, 5, 2); // top,left,bottom,right panel.add(messagePanel, cnstrs); cnstrs = constraints(0, 1, true, true, GridBagConstraints.HORIZONTAL); cnstrs.gridwidth = GridBagConstraints.REMAINDER; cnstrs.gridheight = 1; cnstrs.weighty = 0; cnstrs.insets = new Insets(0, 2, 10, 2); // top,left,bottom,right panel.add(buttonPanel, cnstrs); dialog.getContentPane().add(panel); dialog.pack(); dialog.setVisible(true); if (outcome[0] != DialogResult.YES) { return null; } return checkbox.isSelected(); }
From source file:Main.java
public Main() { super(BoxLayout.Y_AXIS); Box info = Box.createVerticalBox(); info.add(new Label("Please wait 3 seconds")); final JButton continueButton = new JButton("Continue"); info.add(continueButton);/*from w w w. ja v a 2s . co m*/ JDialog d = new JDialog(); d.setModalityType(ModalityType.APPLICATION_MODAL); d.setContentPane(info); d.pack(); continueButton.addActionListener(e -> d.dispose()); continueButton.setVisible(false); SwingWorker sw = new SwingWorker<Integer, Integer>() { protected Integer doInBackground() throws Exception { int i = 0; while (i++ < 30) { System.out.println(i); Thread.sleep(100); } return null; } @Override protected void done() { continueButton.setVisible(true); } }; JButton button = new JButton("Click Me"); button.addActionListener(e -> { sw.execute(); d.setVisible(true); }); add(button); }
From source file:com.aw.swing.mvp.JDialogView.java
public void close() { JDialog dlg = (JDialog) parentContainer; dlg.setVisible(false); dlg.dispose(); }
From source file:com.diversityarrays.update.UpdateDialog.java
private void checkForUpdates(PrintStream ps) { StringBuilder sb = new StringBuilder(updateCheckRequest.updateBaseUrl); sb.append(updateCheckRequest.versionCode); if (RunMode.getRunMode().isDeveloper()) { sb.append("-dev"); //$NON-NLS-1$ }/*from w w w . j a v a 2 s .co m*/ sb.append(".json"); //$NON-NLS-1$ final String updateUrl; updateUrl = sb.toString(); // updateUrl = "NONEXISTENT"; // Uncomment to check error final ProgressMonitor progressMonitor = new ProgressMonitor(updateCheckRequest.owner, Msg.PROGRESS_CHECKING(), null, 0, 0); worker = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { // Thread.sleep(3000); // Uncomment to check delay BufferedReader reader = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(updateUrl); reader = new BufferedReader(new InputStreamReader(url.openStream())); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) { if (progressMonitor.isCanceled()) { cancel(true); return null; } buffer.append(chars, 0, read); } } catch (IOException e) { System.err.println("checkForUpdates: " + e.getMessage()); //$NON-NLS-1$ } finally { if (reader != null) { reader.close(); } } return buffer.toString(); } @Override protected void done() { try { String json = get(); Gson gson = new Gson(); setKDXploreUpdate(gson.fromJson(json, KDXploreUpdate.class)); } catch (CancellationException ignore) { } catch (InterruptedException ignore) { } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof UnknownHostException) { String site = extractSite(updateUrl); ps.println(Msg.ERRMSG_UNABLE_TO_CONTACT_UPDATE_SITE(site)); } else { cause.printStackTrace(ps); } if (cause instanceof FileNotFoundException) { FileNotFoundException fnf = (FileNotFoundException) cause; if (updateUrl.equals(fnf.getMessage())) { // Well maybe someone forgot to create the file on // the server! System.err.println("Maybe someone forgot to create the file!"); //$NON-NLS-1$ System.err.println(fnf.getMessage()); setKDXploreUpdate(new KDXploreUpdate(Msg.ERRMSG_PROBLEMS_CONTACTING_UPDATE_SERVER_1())); return; } } String msg = Msg.HTML_PROBLEMS_CONTACTING_UPDATE_2(StringUtil.htmlEscape(updateUrl), cause.getClass().getSimpleName(), StringUtil.htmlEscape(cause.getMessage())); kdxploreUpdate = new KDXploreUpdate(msg); kdxploreUpdate.unknownHost = (cause instanceof UnknownHostException); return; } } private String extractSite(final String updateUrl) { String site = null; int spos = updateUrl.indexOf("://"); if (spos > 0) { int epos = updateUrl.indexOf('/', spos + 1); if (epos > 0) { site = updateUrl.substring(0, epos); } } if (site == null) { site = updateUrl; } return site; } }; Closure<JDialog> onComplete = new Closure<JDialog>() { @Override public void execute(JDialog d) { if (!processReadUrlResult(updateUrl)) { d.dispose(); } else { d.setVisible(true); } } }; SwingWorkerCompletionWaiter waiter = new SwingWorkerCompletionWaiter(this, onComplete); worker.addPropertyChangeListener(waiter); worker.execute(); }