List of usage examples for javax.swing JOptionPane OK_CANCEL_OPTION
int OK_CANCEL_OPTION
To view the source code for javax.swing JOptionPane OK_CANCEL_OPTION.
Click Source Link
showConfirmDialog
. From source file:gov.nih.nci.nbia.StandaloneDMV3.java
public void launch(List<String> seriesList) { checkCompatibility();// w w w. j a v a 2 s. c o m if ((seriesList == null) || (seriesList.size() <= 0)) { JOptionPane.showMessageDialog(null, "This version of Download App requires to have at least one series instance UID in manifest file."); System.exit(0); } else { this.seriesList = seriesList; if (seriesList.size() > 9999) { int result = JOptionPane.showConfirmDialog(null, "The number of series in manifest file exceeds the maximum 9,999 series threshold. Only the first 9,999 series will be downloaded.", "Threshold Exceeded Notification", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE); if (result != JOptionPane.OK_OPTION) { System.exit(0); } } JFrame f; String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("mac")) { f = showProgressForMac("Loading your data"); SwingUtilities.invokeLater(new Runnable() { public void run() { createMainWin(); f.setVisible(false); f.dispose(); } }); } else { f = showProgress("Loading your data"); createMainWin(); f.setVisible(false); f.dispose(); } } }
From source file:com.compomics.pladipus.controller.setup.InstallPladipus.java
/** * Queries the user for the valid user login and password * * @throws IOException/*from w ww . java2 s. c o m*/ */ public boolean validateUser() throws IOException { JPanel panel = new JPanel(new BorderLayout(5, 5)); JPanel label = new JPanel(new GridLayout(0, 1, 2, 2)); label.add(new JLabel("Username", SwingConstants.RIGHT)); label.add(new JLabel("Password", SwingConstants.RIGHT)); panel.add(label, BorderLayout.WEST); JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2)); JTextField username = new JTextField(); controls.add(username); JPasswordField password = new JPasswordField(); controls.add(password); panel.add(controls, BorderLayout.CENTER); int showConfirmDialog = JOptionPane.showConfirmDialog(null, panel, "Pladipus Login", JOptionPane.OK_CANCEL_OPTION); if (showConfirmDialog == JOptionPane.CANCEL_OPTION) { return false; } String user = username.getText(); String pass = new String(password.getPassword()); if (login(user, pass)) { writeWorkerBash(user, pass); return true; } else { throw new SecurityException("User credentials are incorrect!"); } }
From source file:net.pms.newgui.SelectRenderers.java
/** * Create the GUI and show it./*from w ww . j a va2 s . co m*/ */ public void showDialog() { if (!init) { // Initial call build(); init = true; } SrvTree.validate(); // Refresh setting if modified selectedRenderers = configuration.getSelectedRenderers(); TreePath root = new TreePath(allRenderers); if (selectedRenderers.isEmpty() || (selectedRenderers.size() == 1 && selectedRenderers.get(0) == null)) { checkTreeManager.getSelectionModel().clearSelection(); } else if (selectedRenderers.size() == 1 && selectedRenderers.get(0).equals(allRenderersTreeName)) { checkTreeManager.getSelectionModel().setSelectionPath(root); } else { if (root.getLastPathComponent() instanceof SearchableMutableTreeNode) { SearchableMutableTreeNode rootNode = (SearchableMutableTreeNode) root.getLastPathComponent(); SearchableMutableTreeNode node = null; List<TreePath> selectedRenderersPath = new ArrayList<>(selectedRenderers.size()); for (String selectedRenderer : selectedRenderers) { try { node = rootNode.findInBranch(selectedRenderer, true); } catch (IllegalChildException e) { } if (node != null) { selectedRenderersPath.add(new TreePath(node.getPath())); } } checkTreeManager.getSelectionModel().setSelectionPaths( selectedRenderersPath.toArray(new TreePath[selectedRenderersPath.size()])); } else { LOGGER.error("Illegal node class in SelectRenderers.showDialog(): {}", root.getLastPathComponent().getClass().getSimpleName()); } } int selectRenderers = JOptionPane.showOptionDialog((Component) PMS.get().getFrame(), this, Messages.getString("GeneralTab.5"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null); if (selectRenderers == JOptionPane.OK_OPTION) { TreePath[] selected = checkTreeManager.getSelectionModel().getSelectionPaths(); if (selected.length == 0) { if (configuration.setSelectedRenderers("")) { PMS.get().getFrame().setReloadable(true); // notify the user to restart the server } } else if (selected.length == 1 && selected[0].getLastPathComponent() instanceof SearchableMutableTreeNode && ((SearchableMutableTreeNode) selected[0].getLastPathComponent()).getNodeName() .equals(allRenderers.getNodeName())) { if (configuration.setSelectedRenderers(allRenderersTreeName)) { PMS.get().getFrame().setReloadable(true); // notify the user to restart the server } } else { List<String> selectedRenderers = new ArrayList<>(); for (TreePath path : selected) { String rendererName = ""; if (path.getPathComponent(0).equals(allRenderers)) { for (int i = 1; i < path.getPathCount(); i++) { if (path.getPathComponent(i) instanceof SearchableMutableTreeNode) { if (!rendererName.isEmpty()) { rendererName += " "; } rendererName += ((SearchableMutableTreeNode) path.getPathComponent(i)) .getNodeName(); } else { LOGGER.error("Invalid tree node component class {}", path.getPathComponent(i).getClass().getSimpleName()); } } if (!rendererName.isEmpty()) { selectedRenderers.add(rendererName); } } else { LOGGER.warn("Invalid renderer treepath encountered: {}", path.toString()); } } if (configuration.setSelectedRenderers(selectedRenderers)) { PMS.get().getFrame().setReloadable(true); // notify the user to restart the server } } } }
From source file:com.sittinglittleduck.DirBuster.CheckForUpdates.java
private int showUpdateToLatestVersionConfirmDialog(String latestversion, String changelog) { return JOptionPane.showConfirmDialog(manager.gui, "A new version of DirBuster (" + latestversion + ") is available\n\n" + "Change log:\n\n" + changelog + "\n\n" + "Do you wish to get the new version now?\n\n" + "(Auto checking can be disabled from 'Advanced Options -> DirBuster Options')", "A new version of DirBuster is Avaliable", JOptionPane.OK_CANCEL_OPTION); }
From source file:net.sf.jabref.external.MoveFileAction.java
@Override public void actionPerformed(ActionEvent event) { int selected = editor.getSelectedRow(); if (selected == -1) { return;/*from w ww . j ava 2 s . c om*/ } FileListEntry entry = editor.getTableModel().getEntry(selected); // Check if the current file exists: String ln = entry.link; boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http"); if (httpLink) { // TODO: notify that this operation cannot be done on remote links return; } // Get an absolute path representation: List<String> dirs = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory(); int found = -1; for (int i = 0; i < dirs.size(); i++) { if (new File(dirs.get(i)).exists()) { found = i; break; } } if (found < 0) { JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); return; } File file = new File(ln); if (!file.isAbsolute()) { file = FileUtil.expandFilename(ln, dirs).orElse(null); } if ((file != null) && file.exists()) { // Ok, we found the file. Now get a new name: String extension = null; if (entry.type.isPresent()) { extension = "." + entry.type.get().getExtension(); } File newFile = null; boolean repeat = true; while (repeat) { repeat = false; String chosenFile; if (toFileDir) { // Determine which name to suggest: String suggName = FileUtil .createFileNameFromPattern(eEditor.getDatabase(), eEditor.getEntry(), Globals.journalAbbreviationLoader, Globals.prefs) .concat(entry.type.isPresent() ? "." + entry.type.get().getExtension() : ""); CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("Move file to file directory?"), Localization.lang("Rename to '%0'", suggName), Globals.prefs.getBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR)); int answer; // Only ask about renaming file if the file doesn't have the proper name already: if (suggName.equals(file.getName())) { answer = JOptionPane.showConfirmDialog(frame, Localization.lang("Move file to file directory?"), MOVE_RENAME, JOptionPane.YES_NO_OPTION); } else { answer = JOptionPane.showConfirmDialog(frame, cbm, MOVE_RENAME, JOptionPane.YES_NO_OPTION); } if (answer != JOptionPane.YES_OPTION) { return; } Globals.prefs.putBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR, cbm.isSelected()); StringBuilder sb = new StringBuilder(dirs.get(found)); if (!dirs.get(found).endsWith(File.separator)) { sb.append(File.separator); } if (cbm.isSelected()) { // Rename: sb.append(suggName); } else { // Do not rename: sb.append(file.getName()); } chosenFile = sb.toString(); } else { chosenFile = FileDialogs.getNewFile(frame, file, Collections.singletonList(extension), JFileChooser.SAVE_DIALOG, false); } if (chosenFile == null) { return; // canceled } newFile = new File(chosenFile); // Check if the file already exists: if (newFile.exists() && (JOptionPane.showConfirmDialog(frame, Localization.lang("'%0' exists. Overwrite file?", newFile.getName()), MOVE_RENAME, JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)) { if (toFileDir) { return; } else { repeat = true; } } } if (!newFile.equals(file)) { try { boolean success = file.renameTo(newFile); if (!success) { success = FileUtil.copyFile(file, newFile, true); } if (success) { // Remove the original file: if (!file.delete()) { LOGGER.info("Cannot delete original file"); } // Relativise path, if possible. String canPath = new File(dirs.get(found)).getCanonicalPath(); if (newFile.getCanonicalPath().startsWith(canPath)) { if ((newFile.getCanonicalPath().length() > canPath.length()) && (newFile .getCanonicalPath().charAt(canPath.length()) == File.separatorChar)) { String newLink = newFile.getCanonicalPath().substring(1 + canPath.length()); editor.getTableModel().setEntry(selected, new FileListEntry(entry.description, newLink, entry.type)); } else { String newLink = newFile.getCanonicalPath().substring(canPath.length()); editor.getTableModel().setEntry(selected, new FileListEntry(entry.description, newLink, entry.type)); } } else { String newLink = newFile.getCanonicalPath(); editor.getTableModel().setEntry(selected, new FileListEntry(entry.description, newLink, entry.type)); } eEditor.updateField(editor); //JOptionPane.showMessageDialog(frame, Globals.lang("File moved"), // Globals.lang("Move/Rename file"), JOptionPane.INFORMATION_MESSAGE); frame.output(Localization.lang("File moved")); } else { JOptionPane.showMessageDialog(frame, Localization.lang("Move file failed"), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); } } catch (SecurityException | IOException ex) { LOGGER.warn("Could not move file", ex); JOptionPane.showMessageDialog(frame, Localization.lang("Could not move file '%0'.", file.getAbsolutePath()) + ex.getMessage(), MOVE_RENAME, JOptionPane.ERROR_MESSAGE); } } } else { // File doesn't exist, so we can't move it. JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link), Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE); } }
From source file:de.dal33t.powerfolder.PowerFolder.java
/** * Starts a PowerFolder controller with the given command line arguments * * @param args// w w w . ja v a2 s .co m */ public static void startPowerFolder(String[] args) { // Touch Logger immediately to initialize handlers. LoggingManager.isLogToFile(); // Default exception logger Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { e.printStackTrace(); log.log(Level.SEVERE, "Exception in " + t + ": " + e.toString(), e); } }); CommandLine commandLine = parseCommandLine(args); if (commandLine == null) { return; } // -l --log console log levels (severe, warning, info, fine and finer). if (commandLine.hasOption("l")) { String levelName = commandLine.getOptionValue("l"); Level level = LoggingManager.levelForName(levelName); if (level != null) { LoggingManager.setConsoleLogging(level); } } if (commandLine.hasOption("s")) { // Server mode, suppress debug output on console // Logger.addExcludeConsoleLogLevel(Logger.DEBUG); } if (commandLine.hasOption("h")) { // Show help HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("PowerFolder", COMMAND_LINE_OPTIONS); return; } int rconPort = Integer.valueOf(ConfigurationEntry.NET_RCON_PORT.getDefaultValue()); String portStr = commandLine.getOptionValue("k"); if (StringUtils.isNotBlank(portStr)) { try { rconPort = Integer.valueOf(portStr.trim()); } catch (Exception e) { log.warning("Unable to parse rcon port: " + portStr + ". " + e); } } boolean runningInstanceFound = RemoteCommandManager.hasRunningInstance(rconPort); if (commandLine.hasOption("k")) { if (runningInstanceFound) { System.out.println("Stopping " + NAME); // Send quit command RemoteCommandManager.sendCommand(rconPort, RemoteCommandManager.QUIT); } else { System.err.println("Process not running"); } // stop return; } // set language from commandline to preferences if (commandLine.hasOption("g")) { Preferences.userNodeForPackage(Translation.class).put("locale", commandLine.getOptionValue("g")); } if (JavaVersion.systemVersion().isOpenJDK()) { Object[] options = { "Open Oracle home page and exit", "Exit" }; int n = JOptionPane.showOptionDialog(null, "You are using OpenJDK which is unsupported.\n" + "Please install the client with bundled JRE or install the Oracle JRE", "Unsupported JRE", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (n == 0) { try { BrowserLauncher.openURL("http://www.java.com"); } catch (IOException e1) { e1.printStackTrace(); } } return; } // The controller. Controller controller = Controller.createController(); String[] files = commandLine.getArgs(); // Parsing of command line completed boolean commandContainsRemoteCommands = files != null && files.length >= 1 || commandLine.hasOption("e") || commandLine.hasOption("r") || commandLine.hasOption("a"); // Try to start controller boolean startController = !commandContainsRemoteCommands || !runningInstanceFound; try { log.info("PowerFolder v" + Controller.PROGRAM_VERSION); // Start controller if (startController) { controller.startConfig(commandLine); } // Send remote command if there a files in commandline if (files != null && files.length > 0) { // Parse filenames and build remote command StringBuilder openFilesRCommand = new StringBuilder(RemoteCommandManager.OPEN); for (String file : files) { openFilesRCommand.append(file); // FIXME: Add ; separator ? } // Send remote command to running PowerFolder instance RemoteCommandManager.sendCommand(openFilesRCommand.toString()); } if (commandLine.hasOption("e")) { RemoteCommandManager.sendCommand(RemoteCommandManager.MAKEFOLDER + commandLine.getOptionValue("e")); } if (commandLine.hasOption("r")) { RemoteCommandManager .sendCommand(RemoteCommandManager.REMOVEFOLDER + commandLine.getOptionValue("r")); } if (commandLine.hasOption("a")) { RemoteCommandManager.sendCommand(RemoteCommandManager.COPYLINK + commandLine.getOptionValue("a")); } } catch (Throwable t) { t.printStackTrace(); log.log(Level.SEVERE, "Throwable", t); return; } // Begin monitoring memory usage. if (controller.isStarted() && controller.isUIEnabled()) { ScheduledExecutorService service = controller.getThreadPool(); service.scheduleAtFixedRate(new MemoryMonitor(controller), 1, 1, TimeUnit.MINUTES); } // Not go into console mode if ui is open if (!startController) { if (runningInstanceFound) { RemoteCommandManager.sendCommand(RemoteCommandManager.SHOW_UI); } return; } System.out.println("------------ " + NAME + " " + Controller.PROGRAM_VERSION + " started ------------"); boolean restartRequested = false; do { // Go into restart loop while (controller.isStarted() || controller.isShuttingDown()) { try { Thread.sleep(500); } catch (InterruptedException e) { log.log(Level.WARNING, "InterruptedException", e); return; } } restartRequested = controller.isRestartRequested(); if (restartRequested) { Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces(); for (Thread thread : threads.keySet()) { if (thread.getName().startsWith("PoolThread") || thread.getName().startsWith("Reconnector") || thread.getName().startsWith("ConHandler")) { thread.interrupt(); } } log.info("Restarting controller"); System.out.println( "------------ " + NAME + " " + Controller.PROGRAM_VERSION + " restarting ------------"); controller = null; System.gc(); controller = Controller.createController(); // Start controller controller.startConfig(commandLine); } } while (restartRequested); }
From source file:coolmap.canvas.datarenderer.renderer.impl.NumberComposite.java
public NumberComposite() { setName("Number to Composite"); // System.out.println("Created a new NumberComposite"); setDescription("A renderer that can be used to assign renderers to different aggregations"); configUI.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0;/*from w w w.j a v a 2 s.c om*/ c.gridy = 0; c.ipadx = 5; c.ipady = 5; c.insets = new Insets(2, 2, 2, 2); c.gridwidth = 1; //This combo box will need to be able to add registered singleComboBox = new JComboBox(); rowComboBox = new JComboBox(); columnComboBox = new JComboBox(); rowColumnComboBox = new JComboBox(); singleLegend = new JLabel(); rowLegend = new JLabel(); columnLegend = new JLabel(); rowColumnLegend = new JLabel(); singleLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); rowLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); columnLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); rowColumnLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5)); //Add them JLabel label = new JLabel("Default:"); label.setToolTipText("Default renderer"); c.gridx = 0; c.gridy++; configUI.add(label, c); c.gridx = 1; configUI.add(singleComboBox, c); singleComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { updateRenderer(); } } }); c.gridx = 2; JButton config = new JButton(UI.getImageIcon("gear")); configUI.add(config, c); config.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (singleRenderer == null) { return; } // JOptionPane.showmess int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(), singleRenderer.getConfigUI(), "Default Renderer Config", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null); if (returnVal == JOptionPane.OK_OPTION) { updateRenderer(); } } }); c.gridx = 1; c.gridy++; c.gridwidth = 1; configUI.add(singleLegend, c); ////////////////////////////////////////////////////////////// c.gridx = 0; c.gridy++; c.gridwidth = 1; label = new JLabel("Row Group:"); label.setToolTipText("Renderer for row ontology nodes"); configUI.add(label, c); c.gridx = 1; configUI.add(rowComboBox, c); c.gridx++; config = new JButton(UI.getImageIcon("gear")); configUI.add(config, c); config.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (rowGroupRenderer == null) { return; } // JOptionPane.showmess int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(), rowGroupRenderer.getConfigUI(), "Row Group Renderer Config", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null); if (returnVal == JOptionPane.OK_OPTION) { updateRenderer(); } } }); rowComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { updateRenderer(); } } }); c.gridx = 1; c.gridy++; c.gridwidth = 1; configUI.add(rowLegend, c); c.gridx = 0; c.gridy++; c.gridwidth = 1; label = new JLabel("Column Group:"); label.setToolTipText("Renderer for column ontology nodes"); configUI.add(label, c); c.gridx = 1; configUI.add(columnComboBox, c); c.gridx++; config = new JButton(UI.getImageIcon("gear")); configUI.add(config, c); config.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (columnGroupRenderer == null) { return; } // JOptionPane.showmess int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(), columnGroupRenderer.getConfigUI(), "Column Group Renderer Config", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null); if (returnVal == JOptionPane.OK_OPTION) { updateRenderer(); } } }); c.gridx = 1; c.gridy++; c.gridwidth = 1; configUI.add(columnLegend, c); columnComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { updateRenderer(); } } }); c.gridx = 0; c.gridy++; c.gridwidth = 1; label = new JLabel("Row & Column Group:"); label.setToolTipText("Renderer for row and column ontology nodes"); configUI.add(label, c); c.gridx = 1; configUI.add(rowColumnComboBox, c); c.gridx++; config = new JButton(UI.getImageIcon("gear")); configUI.add(config, c); config.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (rowColumnGroupRenderer == null) { return; } // JOptionPane.showmess int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(), rowColumnGroupRenderer.getConfigUI(), "Row + Column Group Renderer Config", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null); if (returnVal == JOptionPane.OK_OPTION) { updateRenderer(); } } }); rowColumnComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { updateRenderer(); } } }); c.gridx = 1; c.gridy++; c.gridwidth = 1; configUI.add(rowColumnLegend, c); JButton button = new JButton("Apply Changes", UI.getImageIcon("refresh")); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateRenderer(); } }); c.gridx = 0; c.gridy++; c.gridwidth = 2; configUI.add(button, c); singleComboBox.setRenderer(new ComboRenderer()); rowComboBox.setRenderer(new ComboRenderer()); columnComboBox.setRenderer(new ComboRenderer()); rowColumnComboBox.setRenderer(new ComboRenderer()); _updateLists(); }
From source file:com.t3.macro.api.functions.input.InputFunctions.java
/** * <pre>//from w w w. j a v a 2s . 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:com.sshtools.tunnel.PortForwardingPane.java
protected void addPortForward() { PortForwardEditorPane editor = new PortForwardEditorPane(); int option = JOptionPane.showConfirmDialog(this, editor, "Add New Tunnel", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (option != JOptionPane.CANCEL_OPTION && option != JOptionPane.CLOSED_OPTION) { try {//from w w w . j a va2 s . co m ForwardingClient forwardingClient = client; //.getForwardingClient(); String id = editor.getForwardName(); if (id.equals("x11")) { throw new Exception("The id of x11 is reserved."); } int i = model.getRowCount(); if (editor.isLocal()) { ForwardingConfiguration f = forwardingClient.addLocalForwarding(id, editor.getBindAddress(), editor.getLocalPort(), editor.getHost(), editor.getRemotePort()); forwardingClient.startLocalForwarding(id); active.addConfiguration(f); } else { ForwardingConfiguration f = forwardingClient.addRemoteForwarding(id, editor.getBindAddress(), editor.getLocalPort(), editor.getHost(), editor.getRemotePort()); forwardingClient.startRemoteForwarding(id); active.addConfiguration(f); } if (i < model.getRowCount()) { table.getSelectionModel().addSelectionInterval(i, i); } } catch (Exception e) { sessionPanel.setAvailableActions(); JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } finally { model.refresh(); sessionPanel.setAvailableActions(); } } }
From source file:net.sf.jabref.gui.preftabs.PreferencesDialog.java
public PreferencesDialog(JabRefFrame parent) { super(parent, Localization.lang("JabRef preferences"), false); JabRefPreferences prefs = JabRefPreferences.getInstance(); frame = parent;// www .j a v a 2s . co m main = new JPanel(); JPanel mainPanel = new JPanel(); JPanel lower = new JPanel(); getContentPane().setLayout(new BorderLayout()); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(lower, BorderLayout.SOUTH); final CardLayout cardLayout = new CardLayout(); main.setLayout(cardLayout); List<PrefsTab> tabs = new ArrayList<>(); tabs.add(new GeneralTab(prefs)); tabs.add(new NetworkTab(prefs)); tabs.add(new FileTab(frame, prefs)); tabs.add(new FileSortTab(prefs)); tabs.add(new EntryEditorPrefsTab(frame, prefs)); tabs.add(new GroupsPrefsTab(prefs)); tabs.add(new AppearancePrefsTab(prefs)); tabs.add(new ExternalTab(frame, this, prefs)); tabs.add(new TablePrefsTab(prefs)); tabs.add(new TableColumnsTab(prefs, parent)); tabs.add(new LabelPatternPrefTab(prefs, parent.getCurrentBasePanel())); tabs.add(new PreviewPrefsTab(prefs)); tabs.add(new NameFormatterTab(prefs)); tabs.add(new ImportSettingsTab(prefs)); tabs.add(new XmpPrefsTab(prefs)); tabs.add(new AdvancedTab(prefs)); // add all tabs tabs.forEach(tab -> main.add((Component) tab, tab.getTabName())); mainPanel.setBorder(BorderFactory.createEtchedBorder()); String[] tabNames = tabs.stream().map(PrefsTab::getTabName).toArray(String[]::new); JList<String> chooser = new JList<>(tabNames); chooser.setBorder(BorderFactory.createEtchedBorder()); // Set a prototype value to control the width of the list: chooser.setPrototypeCellValue("This should be wide enough"); chooser.setSelectedIndex(0); chooser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Add the selection listener that will show the correct panel when // selection changes: chooser.addListSelectionListener(e -> { if (e.getValueIsAdjusting()) { return; } String o = chooser.getSelectedValue(); cardLayout.show(main, o); }); JPanel buttons = new JPanel(); buttons.setLayout(new GridLayout(4, 1)); buttons.add(importPreferences, 0); buttons.add(exportPreferences, 1); buttons.add(showPreferences, 2); buttons.add(resetPreferences, 3); JPanel westPanel = new JPanel(); westPanel.setLayout(new BorderLayout()); westPanel.add(chooser, BorderLayout.CENTER); westPanel.add(buttons, BorderLayout.SOUTH); mainPanel.setLayout(new BorderLayout()); mainPanel.add(main, BorderLayout.CENTER); mainPanel.add(westPanel, BorderLayout.WEST); JButton ok = new JButton(Localization.lang("OK")); JButton cancel = new JButton(Localization.lang("Cancel")); ok.addActionListener(new OkAction()); CancelAction cancelAction = new CancelAction(); cancel.addActionListener(cancelAction); lower.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); ButtonBarBuilder buttonBarBuilder = new ButtonBarBuilder(lower); buttonBarBuilder.addGlue(); buttonBarBuilder.addButton(ok); buttonBarBuilder.addButton(cancel); buttonBarBuilder.addGlue(); // Key bindings: KeyBinder.bindCloseDialogKeyToCancelAction(this.getRootPane(), cancelAction); // Import and export actions: exportPreferences.setToolTipText(Localization.lang("Export preferences to file")); exportPreferences.addActionListener(e -> { String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), Collections.singletonList(".xml"), JFileChooser.SAVE_DIALOG, false); if (filename == null) { return; } File file = new File(filename); if (!file.exists() || (JOptionPane.showConfirmDialog(PreferencesDialog.this, Localization.lang("'%0' exists. Overwrite file?", file.getName()), Localization.lang("Export preferences"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)) { try { prefs.exportPreferences(filename); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(), Localization.lang("Export preferences"), JOptionPane.ERROR_MESSAGE); } } }); importPreferences.setToolTipText(Localization.lang("Import preferences from file")); importPreferences.addActionListener(e -> { String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")), Collections.singletonList(".xml"), JFileChooser.OPEN_DIALOG, false); if (filename != null) { try { prefs.importPreferences(filename); updateAfterPreferenceChanges(); JOptionPane.showMessageDialog(PreferencesDialog.this, Localization.lang("You must restart JabRef for this to come into effect."), Localization.lang("Import preferences"), JOptionPane.WARNING_MESSAGE); } catch (JabRefException ex) { LOGGER.warn(ex.getMessage(), ex); JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(), Localization.lang("Import preferences"), JOptionPane.ERROR_MESSAGE); } } }); showPreferences.addActionListener( e -> new PreferencesFilterDialog(new JabRefPreferencesFilter(Globals.prefs), frame) .setVisible(true)); resetPreferences.addActionListener(e -> { if (JOptionPane.showConfirmDialog(PreferencesDialog.this, Localization.lang("Are you sure you want to reset all settings to default values?"), Localization.lang("Reset preferences"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { try { prefs.clear(); JOptionPane.showMessageDialog(PreferencesDialog.this, Localization.lang("You must restart JabRef for this to come into effect."), Localization.lang("Reset preferences"), JOptionPane.WARNING_MESSAGE); } catch (BackingStoreException ex) { LOGGER.warn(ex.getMessage(), ex); JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(), Localization.lang("Reset preferences"), JOptionPane.ERROR_MESSAGE); } updateAfterPreferenceChanges(); } }); setValues(); pack(); }