List of usage examples for javax.swing JOptionPane showMessageDialog
public static void showMessageDialog(Component parentComponent, Object message, String title, int messageType) throws HeadlessException
messageType
parameter. From source file:geocodingsql.Main.java
/** * @param args the command line arguments *//*w w w . ja v a 2s . c om*/ public static void main(String[] args) throws JSONException { Main x = new Main(); ResultSet rs = null; String string = ""; x.establishConnection(); rs = x.giveName(); try { while (rs.next()) { string += rs.getString(1) + " "; } JOptionPane.showMessageDialog(null, string, "authors", 1); } catch (Exception e) { System.out.println("Problem when printing the database."); } x.closeConnection(); // Now do Geocoding String req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=41.3166662867211,-72.9062497615814&result_type=point_of_interest&key=" + key; try { URL url = new URL(req + "&sensor=false"); URLConnection conn = url.openConnection(); ByteArrayOutputStream output = new ByteArrayOutputStream(1024); IOUtils.copy(conn.getInputStream(), output); output.close(); req = output.toString(); } catch (Exception e) { System.out.println("Geocoding Error"); } JSONObject jObject = new JSONObject(req); JSONArray resultArray = jObject.getJSONArray("results"); //this prints out the neighborhood of the provided coordinates System.out.println(resultArray.getJSONObject(0).getJSONArray("address_components") .getJSONObject("neighborhood").getString("long_name")); }
From source file:com.sec.ose.osi.UIMain.java
public static void main(String[] args) { log.debug("Start GUI Application : " + Version.getApplicationVersionInfo()); // check java version final double MINIMUM_VERSION = 1.6; // SwingWorker is since 1.6 log.debug("Checking Java version."); double cur_version = getJavaVersion(); Properties prop = System.getProperties(); String msg = "You need the latest JVM version to execute " + Version.getApplicationVersionInfo() + "\nYou can download JVM(JRE or JDK) at http://java.sun.com" + "\n -Minimun JVM to execute: Java " + MINIMUM_VERSION + "\n -Current version: Java " + prop.getProperty("java.version") + "\n -Local java home directory: " + prop.getProperty("java.home"); if (cur_version < MINIMUM_VERSION) { JOptionPane.showMessageDialog(null, msg, "Incompatible JVM", JOptionPane.ERROR_MESSAGE); log.debug(msg);/*from w ww. ja v a 2 s . co m*/ System.exit(0); } // App Initialize BackgroundJobManager.getInstance().startBeforeLoginTaskThread(); log.debug("Loading \"Login Frame\""); // login JFrame frmLogin = new JFrmLogin(); UISharedData.getInstance().setCurrentFrame(frmLogin); frmLogin.setVisible(true); // check for only one OSI if (isRunning()) { JOptionPane.showMessageDialog(null, "OSI already has started. The program will be closed.", "Error", JOptionPane.ERROR_MESSAGE); System.exit(-1); } // tray icon create new JTrayIconApp("OSIT", frmLogin); }
From source file:edu.cmu.cs.diamond.pathfind.main.PathFindDjango.java
public static void main(String[] args) { if (args.length != 4 && args.length != 5) { System.out.println("usage: " + PathFindDjango.class.getName() + " predicate_dir interface_map slide_map annotation_uri"); return;/*from w w w .j a v a 2s .c o m*/ } final String predicateDir = args[0]; final String interfaceMap = args[1]; final String slideMap = args[2]; final String annotationUri = args[3]; final File slide; if (args.length == 5) { slide = new File(args[4]); } else { slide = null; } final AnnotationStore annotationStore = new DjangoAnnotationStore(new HttpClient(), annotationUri); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { new PathFindFrame(predicateDir, annotationStore, interfaceMap, slideMap, slide, false); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE); } } }); }
From source file:net.openbyte.Launch.java
/** * This is the main method that allows Java to initiate the program. * * @param args the arguments to the Java program, which are ignored *//*w w w . jav a2 s . c o m*/ public static void main(String[] args) { logger.info("Checking for a new version..."); try { GitHub gitHub = new GitHubBuilder().withOAuthToken("e5b60cea047a3e44d4fc83adb86ea35bda131744 ").build(); GHRepository repository = gitHub.getUser("PizzaCrust").getRepository("OpenByte"); for (GHRelease release : repository.listReleases()) { double releaseTag = Double.parseDouble(release.getTagName()); if (CURRENT_VERSION < releaseTag) { logger.info("Version " + releaseTag + " has been released."); JOptionPane.showMessageDialog(null, "Please update OpenByte to " + releaseTag + " at https://github.com/PizzaCrust/OpenByte.", "Update", JOptionPane.WARNING_MESSAGE); } else { logger.info("OpenByte is at the latest version."); } } } catch (Exception e) { logger.error("Failed to connect to GitHub."); e.printStackTrace(); } logger.info("Checking for a workspace folder..."); if (!Files.WORKSPACE_DIRECTORY.exists()) { logger.info("Workspace directory not found, creating one."); Files.WORKSPACE_DIRECTORY.mkdir(); } logger.info("Checking for a plugins folder..."); if (!Files.PLUGINS_DIRECTORY.exists()) { logger.info("Plugins directory not found, creating one."); Files.PLUGINS_DIRECTORY.mkdir(); } try { logger.info("Grabbing and applying system look and feel..."); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { logger.info("Something went wrong when applying the look and feel, using the default one..."); e.printStackTrace(); } logger.info("Starting event manager..."); EventManager.init(); logger.info("Detecting plugin files..."); File[] pluginFiles = PluginManager.getPluginFiles(Files.PLUGINS_DIRECTORY); logger.info("Detected " + pluginFiles.length + " plugin files in the plugins directory!"); logger.info("Beginning load/register plugin process..."); for (File pluginFile : pluginFiles) { logger.info("Loading file " + FilenameUtils.removeExtension(pluginFile.getName()) + "..."); try { PluginManager.registerAndLoadPlugin(pluginFile); } catch (Exception e) { logger.error("Failed to load file " + FilenameUtils.removeExtension(pluginFile.getName()) + "!"); e.printStackTrace(); } } logger.info("All plugin files were loaded/registered to OpenByte."); logger.info("Showing graphical interface to user..."); WelcomeFrame welcomeFrame = new WelcomeFrame(); welcomeFrame.setVisible(true); }
From source file:JTextFieldSample.java
public static void main(String args[]) { String title = (args.length == 0 ? "TextField Listener Example" : args[0]); JFrame frame = new JFrame(title); Container content = frame.getContentPane(); JPanel namePanel = new JPanel(new BorderLayout()); JLabel nameLabel = new JLabel("Name: "); nameLabel.setDisplayedMnemonic(KeyEvent.VK_N); JTextField nameTextField = new JTextField(); nameLabel.setLabelFor(nameTextField); namePanel.add(nameLabel, BorderLayout.WEST); namePanel.add(nameTextField, BorderLayout.CENTER); content.add(namePanel, BorderLayout.NORTH); JPanel cityPanel = new JPanel(new BorderLayout()); JLabel cityLabel = new JLabel("City: "); cityLabel.setDisplayedMnemonic(KeyEvent.VK_C); JTextField cityTextField = new JTextField(); cityLabel.setLabelFor(cityTextField); cityPanel.add(cityLabel, BorderLayout.WEST); cityPanel.add(cityTextField, BorderLayout.CENTER); content.add(cityPanel, BorderLayout.SOUTH); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { System.out.println("Command: " + actionEvent.getActionCommand()); }//from w ww . j a va 2 s . c om }; nameTextField.setActionCommand("Yo"); nameTextField.addActionListener(actionListener); cityTextField.addActionListener(actionListener); KeyListener keyListener = new KeyListener() { public void keyPressed(KeyEvent keyEvent) { printIt("Pressed", keyEvent); } public void keyReleased(KeyEvent keyEvent) { printIt("Released", keyEvent); } public void keyTyped(KeyEvent keyEvent) { printIt("Typed", keyEvent); } private void printIt(String title, KeyEvent keyEvent) { int keyCode = keyEvent.getKeyCode(); String keyText = KeyEvent.getKeyText(keyCode); System.out.println(title + " : " + keyText + " / " + keyEvent.getKeyChar()); } }; nameTextField.addKeyListener(keyListener); cityTextField.addKeyListener(keyListener); InputVerifier verifier = new InputVerifier() { public boolean verify(JComponent input) { final JTextComponent source = (JTextComponent) input; String text = source.getText(); if ((text.length() != 0) && !(text.equals("Exit"))) { Runnable runnable = new Runnable() { public void run() { JOptionPane.showMessageDialog(source, "Can't leave.", "Error Dialog", JOptionPane.ERROR_MESSAGE); } }; SwingUtilities.invokeLater(runnable); return false; } else { return true; } } }; nameTextField.setInputVerifier(verifier); cityTextField.setInputVerifier(verifier); DocumentListener documentListener = new DocumentListener() { public void changedUpdate(DocumentEvent documentEvent) { printIt(documentEvent); } public void insertUpdate(DocumentEvent documentEvent) { printIt(documentEvent); } public void removeUpdate(DocumentEvent documentEvent) { printIt(documentEvent); } private void printIt(DocumentEvent documentEvent) { DocumentEvent.EventType type = documentEvent.getType(); String typeString = null; if (type.equals(DocumentEvent.EventType.CHANGE)) { typeString = "Change"; } else if (type.equals(DocumentEvent.EventType.INSERT)) { typeString = "Insert"; } else if (type.equals(DocumentEvent.EventType.REMOVE)) { typeString = "Remove"; } System.out.print("Type : " + typeString + " / "); Document source = documentEvent.getDocument(); int length = source.getLength(); try { System.out.println("Contents: " + source.getText(0, length)); } catch (BadLocationException badLocationException) { System.out.println("Contents: Unknown"); } } }; nameTextField.getDocument().addDocumentListener(documentListener); cityTextField.getDocument().addDocumentListener(documentListener); frame.setSize(250, 150); frame.setVisible(true); }
From source file:ch.tatool.app.App.java
/** * Main method. Loads the application through an application context. * Requires two arguments: module ID (integer) and code (String). These are used to * set which module will be loaded. /*from w w w . j a va 2s .c om*/ * * The main class App itself then performs the final initialization by loading the * module and displaying the GUI. */ public static void main(String[] args) { // TODO localize error messages if (args.length < 2) { JOptionPane.showMessageDialog(null, "Please provide module ID number and code.", "Error: missing module data", JOptionPane.ERROR_MESSAGE); return; } // load the application ApplicationContext ctx = new ClassPathXmlApplicationContext("/tatool/application-context.xml"); // Set the module that should be loaded GuiController controller = (GuiController) ctx.getBean("GuiController"); try { controller.setModuleID(Integer.parseInt(args[0])); controller.setCode(args[1]); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, args[0] + " is not a valid module ID number.", "Error: invalid module ID", JOptionPane.ERROR_MESSAGE); return; } }
From source file:ListProperties.java
public static void main(String args[]) { final JFrame frame = new JFrame("List Properties"); final CustomTableModel model = new CustomTableModel(); model.uiDefaultsUpdate(UIManager.getDefaults()); TableSorter sorter = new TableSorter(model); JTable table = new JTable(sorter); TableHeaderSorter.install(sorter, table); table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); UIManager.LookAndFeelInfo looks[] = UIManager.getInstalledLookAndFeels(); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { final String lafClassName = actionEvent.getActionCommand(); Runnable runnable = new Runnable() { public void run() { try { UIManager.setLookAndFeel(lafClassName); SwingUtilities.updateComponentTreeUI(frame); // Added model.uiDefaultsUpdate(UIManager.getDefaults()); } catch (Exception exception) { JOptionPane.showMessageDialog(frame, "Can't change look and feel", "Invalid PLAF", JOptionPane.ERROR_MESSAGE); }// w ww . jav a2s . c o m } }; SwingUtilities.invokeLater(runnable); } }; JToolBar toolbar = new JToolBar(); for (int i = 0, n = looks.length; i < n; i++) { JButton button = new JButton(looks[i].getName()); button.setActionCommand(looks[i].getClassName()); button.addActionListener(actionListener); toolbar.add(button); } Container content = frame.getContentPane(); content.add(toolbar, BorderLayout.NORTH); JScrollPane scrollPane = new JScrollPane(table); content.add(scrollPane, BorderLayout.CENTER); frame.setSize(400, 400); frame.setVisible(true); }
From source file:com.novadart.silencedetect.SilenceDetect.java
public static void main(String[] args) { // create the parser CommandLineParser parser = new BasicParser(); try {//ww w . j a va 2 s .c om // parse the command line arguments CommandLine line = parser.parse(OPTIONS, args); if (line.hasOption("h")) { printHelp(); } else { String decibels = "-10"; if (line.hasOption("b")) { decibels = "-" + line.getOptionValue("b"); } else { throw new RuntimeException(); } String videoFile = null; if (line.hasOption("i")) { videoFile = line.getOptionValue("i"); Boolean debug = line.hasOption("d"); if (line.hasOption("t")) { System.out.println(printAudioTracksList(videoFile, debug)); } else if (line.hasOption("s")) { int trackNumber = Integer.parseInt(line.getOptionValue("s")); System.out.println(printAudioTrackSilenceDuration(videoFile, trackNumber, decibels, debug)); } else { printHelp(); } } else if (line.hasOption("-j")) { // choose file final JFileChooser fc = new JFileChooser(); fc.setVisible(true); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { videoFile = fc.getSelectedFile().getAbsolutePath(); } else { return; } JTextArea tracks = new JTextArea(); tracks.setText(printAudioTracksList(videoFile, true)); JSpinner trackNumber = new JSpinner(); trackNumber.setValue(1); final JComponent[] inputs = new JComponent[] { new JLabel("Audio Tracks"), tracks, new JLabel("Track to analyze"), trackNumber }; JOptionPane.showMessageDialog(null, inputs, "Select Audio Track", JOptionPane.PLAIN_MESSAGE); JTextArea results = new JTextArea(); results.setText(printAudioTrackSilenceDuration(videoFile, (int) trackNumber.getValue(), decibels, false)); final JComponent[] resultsInputs = new JComponent[] { new JLabel("Results"), results }; JOptionPane.showMessageDialog(null, resultsInputs, "RESULTS!", JOptionPane.PLAIN_MESSAGE); } else { printHelp(); return; } } } catch (ParseException | IOException | InterruptedException exp) { // oops, something went wrong System.out.println("There was a problem :(\nReason: " + exp.getMessage()); } }
From source file:com.edduarte.protbox.Protbox.java
public static void main(String... args) { // activate debug / verbose mode if (args.length != 0) { List<String> argsList = Arrays.asList(args); if (argsList.contains("-v")) { Constants.verbose = true;//from w w w . jav a 2s . c o m } } // use System's look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // If the System's look and feel is not obtainable, continue execution with JRE look and feel } // check this is a single instance try { new ServerSocket(1882); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Another instance of Protbox is already running.\n" + "Please close the other instance first.", "Protbox already running", JOptionPane.ERROR_MESSAGE); System.exit(1); } // check if System Tray is supported by this operative system if (!SystemTray.isSupported()) { JOptionPane.showMessageDialog(null, "Your operative system does not support system tray functionality.\n" + "Please try running Protbox on another operative system.", "System tray not supported", JOptionPane.ERROR_MESSAGE); System.exit(1); } // add PKCS11 providers FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")), HiddenFileFilter.VISIBLE); File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter); if (providersConfigFiles != null) { for (File f : providersConfigFiles) { try { List<String> lines = FileUtils.readLines(f); String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get(); lines.remove(aliasLine); String alias = aliasLine.split("=")[1].trim(); StringBuilder sb = new StringBuilder(); for (String s : lines) { sb.append(s); sb.append("\n"); } Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString()))); Security.addProvider(p); pkcs11Providers.put(p.getName(), alias); } catch (IOException | ProviderException ex) { if (ex.getMessage().equals("Initialization failed")) { ex.printStackTrace(); String s = "The following error occurred:\n" + ex.getCause().getMessage() + "\n\nIn addition, make sure you have " + "an available smart card reader connected before opening the application."; JTextArea textArea = new JTextArea(s); textArea.setColumns(60); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setSize(textArea.getPreferredSize().width, 1); JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); System.exit(1); } else { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while setting up PKCS11 provider from configuration file " + f.getName() + ".\n" + ex.getMessage(), "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); } } } } // adds a shutdown hook to save instantiated directories into files when the application is being closed Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit)); // get system tray and run tray applet tray = SystemTray.getSystemTray(); SwingUtilities.invokeLater(() -> { if (Constants.verbose) { logger.info("Starting application"); } //Start a new TrayApplet object trayApplet = TrayApplet.getInstance(); }); // prompts the user to choose which provider to use ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> { // loads eID token eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> { user = returnedUser; certificateData = returnedCertificateData; // gets a password to use on the saved registry files (for loading and saving) final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null); consumerHolder.set(password -> { registriesPasswordKey = password; try { // if there are serialized files, load them if they can be decoded by this user's private key final List<SavedRegistry> serializedDirectories = new ArrayList<>(); if (Constants.verbose) { logger.info("Reading serialized registry files..."); } File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles(); if (registryFileList != null) { for (File f : registryFileList) { if (f.isFile()) { byte[] data = FileUtils.readFileToByteArray(f); try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey); byte[] registryDecryptedData = cipher.doFinal(data); serializedDirectories.add(new SavedRegistry(f, registryDecryptedData)); } catch (GeneralSecurityException ex) { if (Constants.verbose) { logger.info("Inserted Password does not correspond to " + f.getName()); } } } } } // if there were no serialized directories, show NewDirectory window to configure the first folder if (serializedDirectories.isEmpty() || registryFileList == null) { if (Constants.verbose) { logger.info("No registry files were found: running app as first time!"); } NewRegistryWindow.start(true); } else { // there were serialized directories loadRegistry(serializedDirectories); trayApplet.repaint(); showTrayApplet(); } } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException | ProtboxException ex) { JOptionPane.showMessageDialog(null, "The inserted password was invalid! Please try another one!", "Invalid password!", JOptionPane.ERROR_MESSAGE); insertPassword(consumerHolder.get()); } }); insertPassword(consumerHolder.get()); }); }); }
From source file:es.tunelator.Start.java
/** * Bootstraps the application, creates and shows the user interface * @param args/* w w w. j a v a 2 s. c o m*/ */ public static void main(String[] args) { MainFrame frame = null; try { // LogFactory.getFactory().setAttribute(LogFactoryImpl.LOG_PROPERTY, // Log4JLogger.class.getName()); // PropertyConfigurator.configure(Start.class.getClassLoader(). // getResource("log4j.properties")); // Set log level as configured at the application parameters Logger.setLogThreshold(AppParameters.getParams().getProperty("log.threshold", AppParameters.LOG_ERROR)); // If the language of the default locale is not supported revert to english if (!isLocaleSupported()) { Locale.setDefault(new Locale("en", "", "")); } else { Locale.setDefault(new Locale(Locale.getDefault().getLanguage(), "", "")); } // Log application startup Logger.logInfo(Start.class, Resourcer.getString(null, "log.info.startup")); // To set up the Look and Feel UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows." + "WindowsLookAndFeel"); frame = new MainFrame(); frame.setVisible(true); frame.correctTabStatus(); // To change the Look and Feel. To be included as an option some day... // UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk."+ // "GTKLookAndFeel"); // SwingUtilities.updateComponentTreeUI(frame); // frame.pack(); } catch (Exception e) { Logger.logFatal(Start.class, e); if (frame != null) { frame.showErrorMessage(Resourcer.getString(null, "error.internal")); frame.dispose(); } else { try { JOptionPane.showMessageDialog(null, Resourcer.getString(Start.class, "error.internal"), Resourcer.getString(Start.class, "error.title"), JOptionPane.ERROR_MESSAGE); } catch (Exception e2) { String message = ""; // This is the last resort to give a localized message // As I'm spanish :-), we give a spanish message if it's // the default language, and an english one otherwise. if (Locale.getDefault().getLanguage().equals(new Locale("es", "", "").getLanguage())) { message = message_es; } else { message = message_en; } JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE); } } System.exit(1); } catch (InternalError e) { Logger.logFatal(Start.class, e); if (frame != null) { frame.showErrorMessage(Resourcer.getString(null, "error.internal")); frame.dispose(); } else { try { JOptionPane.showMessageDialog(null, Resourcer.getString(Start.class, "error.internal"), Resourcer.getString(Start.class, "error.title"), JOptionPane.ERROR_MESSAGE); } catch (Exception e2) { String message = ""; // This is the last resort to give a localized message // As I'm spanish :-), we give a spanish message if it's // the default language, and an english one otherwise. if (Locale.getDefault().getLanguage().equals(new Locale("es", "", "").getLanguage())) { message = message_es; } else { message = message_en; } JOptionPane.showMessageDialog(null, message, title, JOptionPane.ERROR_MESSAGE); } } System.exit(1); } }