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:ste.travian.gui.WorldController.java
/** * Shows the dialog to edit the map URL. */// ww w .j av a2 s . c o m public void updateWorld() { MapUrlPanel mapUrlPanel = new MapUrlPanel(); int result = JOptionPane.showOptionDialog(mainWindow, mapUrlPanel, mainWindow.getTitle(), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[] { "Download", "Cancel" }, null); if (result != JOptionPane.NO_OPTION) { try { load(mapUrlPanel.getUrl()); load(); } catch (Exception e) { mainWindow.error(e.getMessage(), e); } } }
From source file:com._17od.upm.gui.DatabaseActions.java
/** * This method asks the user for the name of a new database and then creates * it. If the file already exists then the user is asked if they'd like to * overwrite it.// w w w .ja v a 2 s .co m * @throws CryptoException * @throws IOException */ public void newDatabase() throws IOException, CryptoException { File newDatabaseFile = getSaveAsFile(Translator.translate("newPasswordDatabase")); if (newDatabaseFile == null) { return; } final JPasswordField masterPassword = new JPasswordField(""); boolean passwordsMatch = false; do { //Get a new master password for this database from the user JPasswordField confirmedMasterPassword = new JPasswordField(""); JOptionPane pane = new JOptionPane( new Object[] { Translator.translate("enterMasterPassword"), masterPassword, Translator.translate("confirmation"), confirmedMasterPassword }, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION); JDialog dialog = pane.createDialog(mainWindow, Translator.translate("masterPassword")); dialog.addWindowFocusListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { masterPassword.requestFocusInWindow(); } }); dialog.show(); if (pane.getValue().equals(new Integer(JOptionPane.OK_OPTION))) { if (!Arrays.equals(masterPassword.getPassword(), confirmedMasterPassword.getPassword())) { JOptionPane.showMessageDialog(mainWindow, Translator.translate("passwordsDontMatch")); } else { passwordsMatch = true; } } else { return; } } while (passwordsMatch == false); if (newDatabaseFile.exists()) { newDatabaseFile.delete(); } database = new PasswordDatabase(newDatabaseFile); dbPers = new PasswordDatabasePersistence(masterPassword.getPassword()); saveDatabase(); accountNames = new ArrayList(); doOpenDatabaseActions(); // If a "Database to Load on Startup" hasn't been set yet then ask the // user if they'd like to open this database on startup. if (Preferences.get(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP) == null || Preferences.get(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP).equals("")) { int option = JOptionPane.showConfirmDialog(mainWindow, Translator.translate("setNewLoadOnStartupDatabase"), Translator.translate("newPasswordDatabase"), JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { Preferences.set(Preferences.ApplicationOptions.DB_TO_LOAD_ON_STARTUP, newDatabaseFile.getAbsolutePath()); Preferences.save(); } } }
From source file:com.bright.json.PGS.java
public static void main(String[] args) throws FileNotFoundException { String fileBasename = null;/*from w w w . j av a 2 s . c o m*/ JFileChooser chooser = new JFileChooser(); try { FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Spreadsheets", "xls", "xlsx"); chooser.setFileFilter(filter); chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home"))); chooser.setDialogTitle("Select the Excel file"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); // String fileBasename = // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf(".")); fileBasename = chooser.getSelectedFile().toString() .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1); System.out.println("Base name: " + fileBasename); } else { System.out.println("No Selection "); } } catch (Exception e) { System.out.println(e.toString()); } String fileName = chooser.getSelectedFile().toString(); InputStream inp = new FileInputStream(fileName); Workbook workbook = null; if (fileName.toLowerCase().endsWith("xlsx")) { try { workbook = new XSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (fileName.toLowerCase().endsWith("xls")) { try { workbook = new HSSFWorkbook(inp); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Sheet nodeSheet = workbook.getSheet("Devices"); Sheet interfaceSheet = workbook.getSheet("Interfaces"); System.out.println("Read nodes sheet."); // Row nodeRow = nodeSheet.getRow(1); // System.out.println(row.getCell(0).toString()); // System.exit(0); JTextField uiHost = new JTextField("demo.brightcomputing.com"); // TextPrompt puiHost = new // TextPrompt("demo.brightcomputing.com",uiHost); JTextField uiUser = new JTextField("root"); // TextPrompt puiUser = new TextPrompt("root", uiUser); JTextField uiPass = new JPasswordField(""); // TextPrompt puiPass = new TextPrompt("x5deix5dei", uiPass); JPanel myPanel = new JPanel(new GridLayout(5, 1)); myPanel.add(new JLabel("Bright HeadNode hostname:")); myPanel.add(uiHost); // myPanel.add(Box.createHorizontalStrut(1)); // a spacer myPanel.add(new JLabel("Username:")); myPanel.add(uiUser); myPanel.add(new JLabel("Password:")); myPanel.add(uiPass); int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.", JOptionPane.OK_CANCEL_OPTION); if (result == JOptionPane.OK_OPTION) { System.out.println("Input received."); } String rhost = uiHost.getText(); String ruser = uiUser.getText(); String rpass = uiPass.getText(); String cmURL = "https://" + rhost + ":8081/json"; List<Cookie> cookies = doLogin(ruser, rpass, cmURL); chkVersion(cmURL, cookies); Map<String, Long> categories = UniqueKeyMap(cmURL, "cmdevice", "getCategories", cookies); Map<String, Long> networks = UniqueKeyMap(cmURL, "cmnet", "getNetworks", cookies); Map<String, Long> partitions = UniqueKeyMap(cmURL, "cmpart", "getPartitions", cookies); Map<String, Long> racks = UniqueKeyMap(cmURL, "cmpart", "getRacks", cookies); Map<String, Long> switches = UniqueKeyMap(cmURL, "cmdevice", "getEthernetSwitches", cookies); // System.out.println(switches.get("switch01")); // System.out.println("Size of the map: "+ switches.size()); // System.exit(0); cmDevice newnode = new cmDevice(); cmDevice.deviceObject devObj = new cmDevice.deviceObject(); cmDevice.switchObject switchObj = new cmDevice.switchObject(); // cmDevice.netObject netObj = new cmDevice.netObject(); List<String> emptyslist = new ArrayList<String>(); // Row nodeRow = nodeSheet.getRow(1); // Row ifRow = interfaceSheet.getRow(1); // System.out.println(nodeRow.getCell(0).toString()); // nodeRow.getCell(3).getStringCellValue() Map<String, ArrayList<cmDevice.netObject>> ifmap = new HashMap<String, ArrayList<cmDevice.netObject>>(); // Map<String,netObject> helperMap = new HashMap<String,netObject>(); // Iterator<Row> rows = interfaceSheet.rowIterator (); // while (rows. < interfaceSheet.getPhysicalNumberOfRows()) { // List<netObject> netList = new ArrayList<netObject>(); for (int i = 0; i < interfaceSheet.getPhysicalNumberOfRows(); i++) { Row ifRow = interfaceSheet.getRow(i); if (ifRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } System.out.println("Row nr: " + ifRow.getRowNum()); cmDevice.netObject netObj = new cmDevice.netObject(); ArrayList<cmDevice.netObject> helperList = new ArrayList<cmDevice.netObject>(); netObj.setBaseType("NetworkInterface"); netObj.setCardType(ifRow.getCell(3).getStringCellValue()); netObj.setChildType(ifRow.getCell(4).getStringCellValue()); netObj.setDhcp((ifRow.getCell(5).getNumericCellValue() > 0.1) ? true : false); netObj.setIp(ifRow.getCell(7).getStringCellValue()); // netObj.setMac(ifRow.getCell(0).toString()); //netObj.setModified(true); netObj.setName(ifRow.getCell(1).getStringCellValue()); netObj.setNetwork(networks.get(ifRow.getCell(6).getStringCellValue())); //netObj.setOldLocalUniqueKey(0L); netObj.setRevision(""); netObj.setSpeed(ifRow.getCell(8, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setStartIf("ALWAYS"); netObj.setToBeRemoved(false); netObj.setUniqueKey((long) ifRow.getCell(2).getNumericCellValue()); //netObj.setAdditionalHostnames(new ArrayList<String>(Arrays.asList(ifRow.getCell(9, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); //netObj.setMac(ifRow.getCell(10, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMode((int) ifRow.getCell(11, Row.CREATE_NULL_AS_BLANK).getNumericCellValue()); netObj.setOptions(ifRow.getCell(12, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); netObj.setMembers(new ArrayList<String>(Arrays .asList(ifRow.getCell(13, Row.CREATE_NULL_AS_BLANK).getStringCellValue().split("\\s*,\\s*")))); // ifmap.put(ifRow.getCell(0).getStringCellValue(), new // HashMap<String, cmDevice.netObject>()); // helperMap.put(ifRow.getCell(1).getStringCellValue(), netObj) ; // ifmap.get(ifRow.getCell(0).getStringCellValue()).putIfAbsent(ifRow.getCell(1).getStringCellValue(), // netObj); // ifmap.put(ifRow.getCell(0).getStringCellValue(), helperMap); if (!ifmap.containsKey(ifRow.getCell(0).getStringCellValue())) { ifmap.put(ifRow.getCell(0).getStringCellValue(), new ArrayList<cmDevice.netObject>()); } helperList = ifmap.get(ifRow.getCell(0).getStringCellValue()); helperList.add(netObj); ifmap.put(ifRow.getCell(0).getStringCellValue(), helperList); continue; } for (int i = 0; i < nodeSheet.getPhysicalNumberOfRows(); i++) { Row nodeRow = nodeSheet.getRow(i); if (nodeRow.getRowNum() == 0) { continue; // just skip the rows if row number is 0 } newnode.setService("cmdevice"); newnode.setCall("addDevice"); Map<String, Long> ifmap2 = new HashMap<String, Long>(); for (cmDevice.netObject j : ifmap.get(nodeRow.getCell(0).getStringCellValue())) ifmap2.put(j.getName(), j.getUniqueKey()); switchObj.setEthernetSwitch(switches.get(nodeRow.getCell(8).getStringCellValue())); System.out.println(nodeRow.getCell(8).getStringCellValue()); System.out.println(switches.get(nodeRow.getCell(8).getStringCellValue())); switchObj.setPrt((int) nodeRow.getCell(9).getNumericCellValue()); switchObj.setBaseType("SwitchPort"); devObj.setBaseType("Device"); // devObj.setCreationTime(0L); devObj.setCustomPingScript(""); devObj.setCustomPingScriptArgument(""); devObj.setCustomPowerScript(""); devObj.setCustomPowerScriptArgument(""); devObj.setCustomRemoteConsoleScript(""); devObj.setCustomRemoteConsoleScriptArgument(""); devObj.setDisksetup(""); devObj.setBmcPowerResetDelay(0L); devObj.setBurning(false); devObj.setEthernetSwitch(switchObj); devObj.setExcludeListFull(""); devObj.setExcludeListGrab(""); devObj.setExcludeListGrabnew(""); devObj.setExcludeListManipulateScript(""); devObj.setExcludeListSync(""); devObj.setExcludeListUpdate(""); devObj.setFinalize(""); devObj.setRack(racks.get(nodeRow.getCell(10).getStringCellValue())); devObj.setRackHeight((long) nodeRow.getCell(11).getNumericCellValue()); devObj.setRackPosition((long) nodeRow.getCell(12).getNumericCellValue()); devObj.setIndexInsideContainer(0L); devObj.setInitialize(""); devObj.setInstallBootRecord(false); devObj.setInstallMode(""); devObj.setIoScheduler(""); devObj.setLastProvisioningNode(0L); devObj.setMac(nodeRow.getCell(6).getStringCellValue()); devObj.setModified(true); devObj.setCategory(categories.get(nodeRow.getCell(1).getStringCellValue())); devObj.setChildType("PhysicalNode"); //devObj.setDatanode((nodeRow.getCell(5).getNumericCellValue() > 0.1) ? true // : false); devObj.setHostname(nodeRow.getCell(0).getStringCellValue()); devObj.setModified(true); devObj.setPartition(partitions.get(nodeRow.getCell(2).getStringCellValue())); devObj.setUseExclusivelyFor("Category"); devObj.setNextBootInstallMode(""); devObj.setNotes(""); devObj.setOldLocalUniqueKey(0L); devObj.setPowerControl(nodeRow.getCell(7).getStringCellValue()); // System.out.println(ifmap.get("excelnode001").size()); // System.out.println(ifmap.get(nodeRow.getCell(0).getStringCellValue()).get(nodeRow.getCell(3).getStringCellValue()).getUniqueKey()); devObj.setManagementNetwork(networks.get(nodeRow.getCell(3).getStringCellValue())); devObj.setProvisioningNetwork(ifmap2.get(nodeRow.getCell(4).getStringCellValue())); devObj.setProvisioningTransport("RSYNCDAEMON"); devObj.setPxelabel(""); // "rack": 90194313218, // "rackHeight": 1, // "rackPosition": 4, devObj.setRaidconf(""); devObj.setRevision(""); devObj.setSoftwareImageProxy(null); devObj.setStartNewBurn(false); devObj.setTag("00000000a000"); devObj.setToBeRemoved(false); // devObj.setUcsInfoConfigured(null); // devObj.setUniqueKey(12345L); devObj.setUserdefined1(""); devObj.setUserdefined2(""); ArrayList<Object> mylist = new ArrayList<Object>(); ArrayList<cmDevice.netObject> mylist2 = new ArrayList<cmDevice.netObject>(); ArrayList<Object> emptylist = new ArrayList<Object>(); devObj.setFsexports(emptylist); devObj.setFsmounts(emptylist); devObj.setGpuSettings(emptylist); devObj.setFspartAssociations(emptylist); devObj.setPowerDistributionUnits(emptyslist); devObj.setRoles(emptylist); devObj.setServices(emptylist); devObj.setStaticRoutes(emptylist); mylist2 = ifmap.get(nodeRow.getCell(0).getStringCellValue()); devObj.setNetworks(mylist2); mylist.add(devObj); mylist.add(1); newnode.setArgs(mylist); GsonBuilder builder = new GsonBuilder(); builder.enableComplexMapKeySerialization(); // Gson g = new Gson(); Gson g = builder.create(); String json2 = g.toJson(newnode); // To be used from a real console and not Eclipse String message = JSonRequestor.doRequest(json2, cmURL, cookies); continue; } JOptionPane optionPaneF = new JOptionPane("The nodes have been added!"); JDialog myDialogF = optionPaneF.createDialog(null, "Complete: "); myDialogF.setModal(false); myDialogF.setVisible(true); doLogout(cmURL, cookies); // System.exit(0); }
From source file:com.hexidec.ekit.component.PropertiesDialog.java
public PropertiesDialog(Window parent, String[] fields, String[] types, String[] values, String title, boolean bModal) { super(parent, title); setModal(bModal);/*from ww w.j a v a 2 s.c om*/ htInputFields = new Hashtable<String, JComponent>(); final Object[] buttonLabels = { Translatrix.getTranslationString("DialogAccept"), Translatrix.getTranslationString("DialogCancel") }; List<Object> panelContents = new ArrayList<Object>(); for (int iter = 0; iter < fields.length; iter++) { String fieldName = fields[iter]; String fieldType = types[iter]; JComponent fieldComponent; JComponent panelComponent = null; if (fieldType.equals("text") || fieldType.equals("integer")) { fieldComponent = new JTextField(3); if (values[iter] != null && values[iter].length() > 0) { ((JTextField) (fieldComponent)).setText(values[iter]); } if (fieldType.equals("integer")) { ((AbstractDocument) ((JTextField) (fieldComponent)).getDocument()) .setDocumentFilter(new DocumentFilter() { @Override public void insertString(FilterBypass fb, int offset, String text, AttributeSet attrs) throws BadLocationException { replace(fb, offset, 0, text, attrs); } @Override public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { if (StringUtils.isNumeric(text)) { super.replace(fb, offset, length, text, attrs); } } }); } } else if (fieldType.equals("bool")) { fieldComponent = new JCheckBox(fieldName); if (values[iter] != null) { ((JCheckBox) (fieldComponent)).setSelected(values[iter] == "true"); } panelComponent = fieldComponent; } else if (fieldType.equals("combo")) { fieldComponent = new JComboBox(); if (values[iter] != null) { StringTokenizer stParse = new StringTokenizer(values[iter], ",", false); while (stParse.hasMoreTokens()) { ((JComboBox) (fieldComponent)).addItem(stParse.nextToken()); } } } else { fieldComponent = new JTextField(3); } htInputFields.put(fieldName, fieldComponent); if (panelComponent == null) { panelContents.add(fieldName); panelContents.add(fieldComponent); } else { panelContents.add(panelComponent); } } jOptionPane = new JOptionPane(panelContents.toArray(), JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, buttonLabels, buttonLabels[0]); setContentPane(jOptionPane); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); jOptionPane.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (isVisible() && (e.getSource() == jOptionPane) && (prop.equals(JOptionPane.VALUE_PROPERTY) || prop.equals(JOptionPane.INPUT_VALUE_PROPERTY))) { Object value = jOptionPane.getValue(); if (value == JOptionPane.UNINITIALIZED_VALUE) { return; } if (value.equals(buttonLabels[0])) { setVisible(false); } else { setVisible(false); } } } }); this.pack(); setLocation(SwingUtilities.getPointForCentering(this, parent)); }
From source file:net.sf.clichart.main.ChartFrame.java
private void saveChart() { JFileChooser chooser = new JFileChooser("."); chooser.addChoosableFileFilter(new ExtensionFileFilter(".jpg", "JPEG files")); chooser.addChoosableFileFilter(new ExtensionFileFilter(".png", "PNG files")); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File outputFile = chooser.getSelectedFile(); if (outputFile.exists()) { int result = JOptionPane.showConfirmDialog(this, "File exists - overwrite?", "File exists", JOptionPane.OK_CANCEL_OPTION); if (result != JOptionPane.OK_OPTION) { return; }/*from w w w .j a va2 s . com*/ } System.err.println("Saving chart to " + outputFile.getPath()); try { new ChartSaver(m_chart, m_initialWidth, m_initialHeight).saveChart(outputFile); } catch (ChartSaverException e) { JOptionPane.showMessageDialog(this, "Failed to save chart: " + e.getMessage()); } } }
From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java
public static void newActivityTemplateManager() throws IOException, InterruptedException { String[] cmd = null;// www .j a va 2 s . co m String templatePath = URLDecoder .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8"); templatePath = templatePath.replace("/", File.separator); templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib")); templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator; templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities" + File.separator; String[] env = null; if (!new File(templatePath + mobileServicesTemplateName).exists()) { String tmpdir = getTempLocation(); BufferedInputStream bufferedInputStream = new BufferedInputStream( ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip")); unZip(bufferedInputStream, tmpdir); if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { try { copyFolder(new File(tmpdir + mobileServicesTemplateName), new File(templatePath + mobileServicesTemplateName)); copyFolder(new File(tmpdir + officeTemplateName), new File(templatePath + officeTemplateName)); } catch (IOException ex) { PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat"); printWriter.println("@echo off"); printWriter.println("md \"" + templatePath + mobileServicesTemplateName + "\""); printWriter.println("md \"" + templatePath + officeTemplateName + "\""); printWriter.println("xcopy \"" + tmpdir + mobileServicesTemplateName + "\" \"" + templatePath + mobileServicesTemplateName + "\" /s /i /Y"); printWriter.println("xcopy \"" + tmpdir + officeTemplateName + "\" \"" + templatePath + officeTemplateName + "\" /s /i /Y"); printWriter.flush(); printWriter.close(); String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" }; cmd = tmpcmd; ArrayList<String> tempenvlist = new ArrayList<String>(); for (String envval : System.getenv().keySet()) tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval))); tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1"); env = new String[tempenvlist.size()]; tempenvlist.toArray(env); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd, env, new File(tmpdir)); proc.waitFor(); //wait for elevate command to finish Thread.sleep(3000); if (!new File(templatePath + mobileServicesTemplateName).exists()) UIHelper.showException( "Error copying template files. Please refer to documentation to copy manually.", new Exception()); } } else { if (System.getProperty("os.name").toLowerCase().startsWith("mac")) { String[] strings = { "osascript", // "-e", // "do shell script \"mkdir -p \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"", // "-e", // "do shell script \"mkdir -p \\\"/" + templatePath + officeTemplateName + "\\\"\"", "-e", "do shell script \"cp -Rp \\\"" + tmpdir + mobileServicesTemplateName + "\\\" \\\"/" + templatePath + "\\\"\"", "-e", "do shell script \"cp -Rp \\\"" + tmpdir + officeTemplateName + "\\\" \\\"/" + templatePath + "\\\"\"" }; exec(strings, tmpdir); } else { try { copyFolder(new File(tmpdir + mobileServicesTemplateName), new File(templatePath + mobileServicesTemplateName)); copyFolder(new File(tmpdir + officeTemplateName), new File(templatePath + officeTemplateName)); } catch (IOException ex) { JPasswordField pf = new JPasswordField(); int okCxl = JOptionPane.showConfirmDialog(null, pf, "To copy Microsoft Services templates, the plugin needs your password:", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (okCxl == JOptionPane.OK_OPTION) { String password = new String(pf.getPassword()); exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp", tmpdir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName }, tmpdir); exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp", tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir); } } } } } }
From source file:net.sf.jabref.openoffice.AutoDetectPaths.java
private boolean autoDetectPaths() { if (OS.WINDOWS) { List<File> progFiles = findProgramFilesDir(); File sOffice = null;/*from ww w .j av a 2 s . co m*/ List<File> sofficeFiles = new ArrayList<>(); for (File dir : progFiles) { if (fileSearchCancelled) { return false; } sOffice = findFileDir(dir, "soffice.exe"); if (sOffice != null) { sofficeFiles.add(sOffice); } } if (sOffice == null) { JOptionPane.showMessageDialog(parent, Localization.lang( "Unable to autodetect OpenOffice/LibreOffice installation. Please choose the installation directory manually."), Localization.lang("Could not find OpenOffice/LibreOffice installation"), JOptionPane.INFORMATION_MESSAGE); JFileChooser jfc = new JFileChooser(new File("C:\\")); jfc.setDialogType(JFileChooser.OPEN_DIALOG); jfc.setFileFilter(new javax.swing.filechooser.FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } @Override public String getDescription() { return Localization.lang("Directories"); } }); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jfc.showOpenDialog(parent); if (jfc.getSelectedFile() != null) { sOffice = jfc.getSelectedFile(); } } if (sOffice == null) { return false; } if (sofficeFiles.size() > 1) { // More than one file found DefaultListModel<File> mod = new DefaultListModel<>(); for (File tmpfile : sofficeFiles) { mod.addElement(tmpfile); } JList<File> fileList = new JList<>(mod); fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fileList.setSelectedIndex(0); FormBuilder b = FormBuilder.create() .layout(new FormLayout("left:pref", "pref, 2dlu, pref, 4dlu, pref")); b.add(Localization.lang("Found more than one OpenOffice/LibreOffice executable.")).xy(1, 1); b.add(Localization.lang("Please choose which one to connect to:")).xy(1, 3); b.add(fileList).xy(1, 5); int answer = JOptionPane.showConfirmDialog(null, b.getPanel(), Localization.lang("Choose OpenOffice/LibreOffice executable"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.CANCEL_OPTION) { return false; } else { sOffice = fileList.getSelectedValue(); } } else { sOffice = sofficeFiles.get(0); } return setupPreferencesForOO(sOffice.getParentFile(), sOffice, "soffice.exe"); } else if (OS.OS_X) { File rootDir = new File("/Applications"); File[] files = rootDir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory() && ("OpenOffice.org.app".equals(file.getName()) || "LibreOffice.app".equals(file.getName()))) { rootDir = file; break; } } } File sOffice = findFileDir(rootDir, SOFFICE_BIN); if (fileSearchCancelled) { return false; } if (sOffice == null) { return false; } else { return setupPreferencesForOO(rootDir, sOffice, SOFFICE_BIN); } } else { // Linux: String usrRoot = "/usr/lib"; File inUsr = findFileDir(new File(usrRoot), SOFFICE); if (fileSearchCancelled) { return false; } if (inUsr == null) { inUsr = findFileDir(new File("/usr/lib64"), SOFFICE); if (inUsr != null) { usrRoot = "/usr/lib64"; } } if (fileSearchCancelled) { return false; } File inOpt = findFileDir(new File("/opt"), SOFFICE); if (fileSearchCancelled) { return false; } if ((inUsr != null) && (inOpt == null)) { return setupPreferencesForOO(usrRoot, inUsr, SOFFICE_BIN); } else if (inOpt != null) { if (inUsr == null) { return setupPreferencesForOO("/opt", inOpt, SOFFICE_BIN); } else { // Found both JRadioButton optRB = new JRadioButton(inOpt.getPath(), true); JRadioButton usrRB = new JRadioButton(inUsr.getPath(), false); ButtonGroup bg = new ButtonGroup(); bg.add(optRB); bg.add(usrRB); FormBuilder b = FormBuilder.create() .layout(new FormLayout("left:pref", "pref, 2dlu, pref, 2dlu, pref ")); b.add(Localization.lang( "Found more than one OpenOffice/LibreOffice executable. Please choose which one to connect to:")) .xy(1, 1); b.add(optRB).xy(1, 3); b.add(usrRB).xy(1, 5); int answer = JOptionPane.showConfirmDialog(null, b.getPanel(), Localization.lang("Choose OpenOffice/LibreOffice executable"), JOptionPane.OK_CANCEL_OPTION); if (answer == JOptionPane.CANCEL_OPTION) { return false; } if (optRB.isSelected()) { return setupPreferencesForOO("/opt", inOpt, SOFFICE_BIN); } else { return setupPreferencesForOO(usrRoot, inUsr, SOFFICE_BIN); } } } } return false; }
From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java
public RecursoDialog(final Recurso rec, final AdminResources adminResources) { super();// w w w . java 2s . c o m setAlwaysOnTop(true); setSize(600, 400); setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); if (cambios) { int res = JOptionPane.showConfirmDialog(RecursoDialog.this, "Existen cambios sin guardar. Seguro que desea cerrar la ventana?", "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION); if (res != JOptionPane.CANCEL_OPTION) { e.getWindow().dispose(); } } else { e.getWindow().dispose(); } } }); final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId()); if (r != null) { setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador()); } else { setTitle(i18n.getString("Resources.summary.titleWindow.new")); } setIconImage(getBasicWindow().getFrame().getIconImage()); JPanel base = new JPanel(); base.setBackground(Color.WHITE); base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS)); // Icono del titulo JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING)); title.setOpaque(false); JLabel labelTitulo = null; if (r != null) { labelTitulo = new JLabel(i18n.getString("Resources.summary"), LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT); } else { labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"), LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT); } labelTitulo.setFont(LogicConstants.deriveBoldFont(12f)); title.add(labelTitulo); base.add(title); // Nombre JPanel mid = new JPanel(new SpringLayout()); mid.setOpaque(false); mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT)); final JTextField name = new JTextField(25); if (r != null) { name.setText(r.getNombre()); } name.getDocument().addDocumentListener(changeListener); name.setEditable(r == null); mid.add(name); // patrullas final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT); mid.add(labelSquads); List<Patrulla> pl = PatrullaConsultas.getAll(); pl.add(0, null); final JComboBox squads = new JComboBox(pl.toArray()); squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX"); squads.addActionListener(changeSelectionListener); squads.setOpaque(false); labelSquads.setLabelFor(squads); if (r != null) { squads.setSelectedItem(r.getPatrullas()); } else { squads.setSelectedItem(null); } squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true); mid.add(squads); // // Identificador // mid.setOpaque(false); // mid.add(new JLabel(i18n.getString("Resources.identificador"), // JLabel.RIGHT)); // final JTextField identificador = new JTextField(""); // if (r != null) { // identificador.setText(r.getIdentificador()); // } // identificador.getDocument().addDocumentListener(changeListener); // identificador.setEditable(r == null); // mid.add(identificador); // Espacio en blanco // mid.add(Box.createHorizontalGlue()); // mid.add(Box.createHorizontalGlue()); // Tipo final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT); mid.add(labelTipoRecursos); final JComboBox types = new JComboBox(RecursoConsultas.getTipos()); labelTipoRecursos.setLabelFor(types); types.addActionListener(changeSelectionListener); if (r != null) { types.setSelectedItem(r.getTipo()); } else { types.setSelectedItem(0); } // types.setEditable(true); types.setEnabled(true); mid.add(types); // Estado Eurocop mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT)); final JTextField status = new JTextField(); if (r != null && r.getEstadoEurocop() != null) { status.setText(r.getEstadoEurocop().getIdentificador()); } status.setEditable(false); mid.add(status); // Subflota y patrulla mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT)); final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas()); subfleets.addActionListener(changeSelectionListener); if (r != null) { subfleets.setSelectedItem(r.getFlotas()); } else { subfleets.setSelectedIndex(0); } subfleets.setEnabled(true); subfleets.setOpaque(false); mid.add(subfleets); // Referencia humana mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT)); final JTextField rhumana = new JTextField(); // if (r != null && r.getIncidencias() != null) { // rhumana.setText(r.getIncidencias().getReferenciaHumana()); // } rhumana.setEditable(false); mid.add(rhumana); // dispositivo mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT)); final PlainDocument plainDocument = new PlainDocument() { private static final long serialVersionUID = 4929271093724956016L; @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) { super.insertString(offs, str, a); } } }; final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI); plainDocument.addDocumentListener(changeListener); issi.setEditable(true); mid.add(issi); mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT)); final JCheckBox enabled = new JCheckBox("", true); enabled.addActionListener(changeSelectionListener); enabled.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (enabled.isSelected()) { squads.setSelectedIndex(0); } squads.setEnabled(enabled.isSelected()); } }); enabled.setEnabled(true); enabled.setOpaque(false); if (r != null) { enabled.setSelected(r.getHabilitado()); } else { enabled.setSelected(true); } if (r != null && r.getDispositivo() != null) { issi.setText( StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0')); } mid.add(enabled); // Fecha ultimo gps mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT)); JTextField lastGPS = new JTextField(); final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r); if (lastGPSDateForRecurso != null) { lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso)); } lastGPS.setEditable(false); mid.add(lastGPS); // Espacio en blanco mid.add(Box.createHorizontalGlue()); mid.add(Box.createHorizontalGlue()); // informacion adicional JPanel infoPanel = new JPanel(new SpringLayout()); final JTextField info = new JTextField(25); info.getDocument().addDocumentListener(changeListener); infoPanel.add(new JLabel(i18n.getString("Resources.info"))); infoPanel.add(info); infoPanel.setOpaque(false); info.setOpaque(false); SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18); if (r != null) { info.setText(r.getInfoAdicional()); } else { info.setText(""); } info.setEditable(true); // Espacio en blanco mid.add(Box.createHorizontalGlue()); mid.add(Box.createHorizontalGlue()); SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18); base.add(mid); base.add(infoPanel); JPanel buttons = new JPanel(); buttons.setOpaque(false); JButton accept = null; if (r == null) { accept = new JButton("Crear", LogicConstants.getIcon("button_crear")); } else { accept = new JButton("Guardar", LogicConstants.getIcon("button_save")); } accept.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { if (cambios || r == null || r.getId() == null) { boolean shithappens = true; if ((r == null || r.getId() == null)) { // Estamos // creando // uno nuevo if (RecursoConsultas.alreadyExists(name.getText())) { shithappens = false; JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.nombreUnico")); } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT, "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI)); shithappens = false; } else if (issi.getText() != null && issi.getText().length() > 0 && LogicConstants.isNumeric(issi.getText()) && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) { shithappens = false; JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.dispositivoUnico")); } } if (shithappens) { if (name.getText().isEmpty()) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.nombreNulo")); } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT, "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI)); } else if (issi.getText() != null && issi.getText().length() > 0 && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.issiUnico")); } else if (issi.getText() != null && issi.getText().length() > 0 && !LogicConstants.isNumeric(issi.getText())) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.noNumerico")); // } else if (identificador.getText().isEmpty()) // { // JOptionPane // .showMessageDialog( // RecursoDialog.this, // i18n.getString("admin.recursos.popup.error.identificadorNulo")); } else if (subfleets.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.noSubflota")); } else if (types.getSelectedItem() == null || types.getSelectedItem().toString().trim().isEmpty()) { JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.error.noTipo")); } else { int i = JOptionPane.showConfirmDialog(RecursoDialog.this, i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"), i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"), JOptionPane.YES_NO_CANCEL_OPTION); if (i == JOptionPane.YES_OPTION) { Recurso recurso = r; if (r == null) { recurso = new Recurso(); } recurso.setInfoAdicional(info.getText()); if (issi.getText() != null && issi.getText().length() > 0) { recurso.setDispositivo(new Integer(issi.getText())); } else { recurso.setDispositivo(null); } recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString())); if (squads.getSelectedItem() != null && enabled.isSelected()) { recurso.setPatrullas( PatrullaConsultas.find(squads.getSelectedItem().toString())); } else { recurso.setPatrullas(null); } recurso.setNombre(name.getText()); recurso.setHabilitado(enabled.isSelected()); // recurso.setIdentificador(identificador // .getText()); recurso.setTipo(types.getSelectedItem().toString()); dispose(); RecursoAdmin.saveOrUpdate(recurso); adminResources.refresh(null); PluginEventHandler.fireChange(adminResources); } else if (i == JOptionPane.NO_OPTION) { dispose(); } } } } else { log.debug("No hay cambios"); dispose(); } } catch (Throwable t) { log.error("Error guardando un recurso", t); } } }); buttons.add(accept); JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel")); cancelar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (cambios) { if (JOptionPane.showConfirmDialog(RecursoDialog.this, "Existen cambios sin guardar. Seguro que desea cerrar la ventana?", "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) { dispose(); } } else { dispose(); } } }); buttons.add(cancelar); base.add(buttons); getContentPane().add(base); setLocationRelativeTo(null); cambios = false; if (r == null) { cambios = true; } pack(); int x; int y; Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0); Point topLeft = myParent.getLocationOnScreen(); Dimension parentSize = myParent.getSize(); Dimension mySize = getSize(); if (parentSize.width > mySize.width) { x = ((parentSize.width - mySize.width) / 2) + topLeft.x; } else { x = topLeft.x; } if (parentSize.height > mySize.height) { y = ((parentSize.height - mySize.height) / 2) + topLeft.y; } else { y = topLeft.y; } setLocation(x, y); cambios = false; }
From source file:ca.uviccscu.lp.server.main.ShutdownListener.java
@Override public void windowClosing(WindowEvent e) { if (Shared.hashInProgress) { JOptionPane.showMessageDialog(null, "Closing not allowed - stop or finish hashing first!", "Hash in progress!", JOptionPane.WARNING_MESSAGE); } else {/*from w ww.j a v a2 s .c o m*/ SwingWorker worker = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { try { int ans1 = JOptionPane.showConfirmDialog(null, "Are you sure you want to shutdown? " + "Clients will switch to passive mode until restarted.", "Confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (ans1 == JOptionPane.OK_OPTION) { l.debug("MainFrame window closing requested"); MainFrame.lockInterface(); MainFrame.setReportingActive(); MainFrame.updateTask("Shutting down", true); MainFrame.updateProgressBar(0, 0, 0, "Shutting down settings manager!", true, true); l.trace("Shutting down settings manager and saving session"); int ans2 = JOptionPane.showConfirmDialog(null, "Do you want to save the games list", "Save confirmation", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); if (ans2 == JOptionPane.OK_OPTION) { SettingsManager.showSaveSettingsDialog(); } SettingsManager.shutdown(); l.trace("OK"); l.trace("Stopping net manager"); MainFrame.updateProgressBar(0, 0, 0, "Shutting down net manager!", true, true); ServerNetManager.shutdown(); l.trace("OK"); l.trace("Shutting down tracker manager - might have errors here!"); MainFrame.updateProgressBar(0, 0, 0, "Shutting down azureus - might take a while!", true, true); //Errors due to Azureus stupid shutdown thread killing routine(see AzureusCoreImpl) //Basically it kills all other threads it doesnt recognise on JVM and then terminates //Not designed to work with other application, and so it also kills the shutdown thread = BAD //Library modified to prevent system shutdown, but exceptions still coming - irrelevant TrackerManager.shutdown(); Thread.yield(); l.trace("OK"); Thread.yield(); Thread.sleep(5000); while (!Shared.azShutdownDone) { try { l.trace("Awaiting az shutdown"); Thread.sleep(500); } catch (InterruptedException ex) { l.error("Az shutdown monitor interrupted", ex); } } MainFrame.updateProgressBar(0, 0, 0, "Cleaning temporary files - might take a while!", true, true); File f = new File(Shared.workingDirectory); /* //delete until files unlocked or timeout if (!deleteFolder(f, true, 3000, 15000)) { l.trace("Advanced file deletion measures required"); releaseLocks(); deleteFolder(f, false, 0, 0); //Advanced thread killing, stolen from azureus...except now it kills itself l.error("Delete timeout - attempting threadicide"); l.trace("Starting thread killing"); //First kill azureus SM - allows to do whatever we want with threads l.trace("Removed SM"); System.setSecurityManager(null); // ThreadGroup tg = Thread.currentThread().getThreadGroup(); while (tg.getParent() != null) { tg = tg.getParent(); } Thread[] threads = new Thread[tg.activeCount() + 1024]; tg.enumerate(threads, true); //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks for (int i = 0; i < threads.length; i++) { Thread th = threads[i]; if (th != null && th != Thread.currentThread() && AEThread2.isOurThread(th)) { l.trace("Stopping " + th.getName()); try { th.stop(); l.trace("ok"); } catch (SecurityException e) { l.trace("Stop vetoed by SM", e); } } } // deleteFolder(f, false, 0, 0); l.error("Trying to stop more threads, list:"); //List remaining threads ThreadGroup tg2 = Thread.currentThread().getThreadGroup(); while (tg2.getParent() != null) { tg2 = tg2.getParent(); } //Object o = new Object(); //o.notifyAll(); Thread[] threads2 = new Thread[tg2.activeCount() + 1024]; tg2.enumerate(threads2, true); //VERY BAD WAY TO STOP THREAD BUT NO CHOICE - need to release the file locks for (int i = 0; i < threads2.length; i++) { Thread th = threads2[i]; if (th != null) { l.trace("Have thread: " + th.getName()); if (th != null && th != Thread.currentThread() && (AEThread2.isOurThread(th) || isAzThread(th))) { l.trace("Stopping " + th.getName()); try { th.stop(); l.trace("ok"); } catch (SecurityException e) { l.trace("Stop vetoed by SM", e); } } } } try { Utils.cleanupDir(); l.trace("OK"); } catch (IOException e) { l.trace("Cleaning failed after more thread cleanup", e); Thread.yield(); } threadCleanup(f); l.error("Last resort - scheduling delete on JVM exit - might FAIL, CHECK MANUALLY"); try { FileUtils.forceDeleteOnExit(f); } catch (IOException iOException) { l.fatal("All delete attempts failed - clean manually"); } } File test = new File("C:\\AZTest\\AZ\\logs\\debug_1.log"); test.deleteOnExit(); try { Thread.sleep(30000); } catch (InterruptedException ex) { java.util.logging.Logger.getLogger(ShutdownListener.class.getName()).log(Level.SEVERE, null, ex); } * */ threadReadout(); try { Utils.cleanupDir(); l.trace("OK"); } catch (IOException e) { l.trace("Cleaning failed - expected due to stupid Azureus file lock", e); Thread.yield(); } System.exit(0); return null; } else { return null; } } catch (Exception ex) { l.fatal("Exception during shutdown!!!", ex); //just end it System.exit(4); return null; } } }; worker.execute(); } }
From source file:com.igormaznitsa.sciareto.ui.UiUtils.java
public static boolean msgOkCancel(@Nonnull final String title, @Nonnull final Object component) { return JOptionPane.showConfirmDialog(Main.getApplicationFrame(), component, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null) == JOptionPane.OK_OPTION; }