Example usage for javax.swing JOptionPane showOptionDialog

List of usage examples for javax.swing JOptionPane showOptionDialog

Introduction

In this page you can find the example usage for javax.swing JOptionPane showOptionDialog.

Prototype

@SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
        int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException 

Source Link

Document

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Usage

From source file:org.netbeans.jpa.modeler.jcre.wizard.RevEngWizardDescriptor.java

public static EntityMappings generateJPAModel(ProgressReporter reporter, Set<String> entities, Project project,
        FileObject packageFileObject, String fileName, boolean includeReference, boolean softWrite,
        boolean autoOpen) throws IOException, ProcessInterruptedException {
    int progressIndex = 0;
    String progressMsg = NbBundle.getMessage(RevEngWizardDescriptor.class, "MSG_Progress_JPA_Model_Pre"); //NOI18N;
    reporter.progress(progressMsg, progressIndex++);

    String version = getModelerFileVersion();

    final EntityMappings entityMappingsSpec = EntityMappings.getNewInstance(version);
    entityMappingsSpec.setGenerated();/* www.j  a  va2  s  . co  m*/

    if (!entities.isEmpty()) {
        String entity = entities.iterator().next();
        entityMappingsSpec.setPackage(JavaIdentifiers.getPackageName(entity));
    }

    List<String> missingEntities = new ArrayList<>();
    for (String entityClass : entities) {
        progressMsg = NbBundle.getMessage(RevEngWizardDescriptor.class, "MSG_Progress_JPA_Class_Parsing",
                entityClass + ".java");//NOI18N
        reporter.progress(progressMsg, progressIndex++);
        JPAModelGenerator.generateJPAModel(entityMappingsSpec, project, entityClass, packageFileObject,
                missingEntities);
    }

    if (includeReference) {
        List<ManagedClass> classes = new ArrayList<>(entityMappingsSpec.getEntity());
        // manageSiblingAttribute for MappedSuperClass and Embeddable is not required for (DBRE) DB REV ENG CASE
        classes.addAll(entityMappingsSpec.getMappedSuperclass());
        classes.addAll(entityMappingsSpec.getEmbeddable());

        for (ManagedClass<IPersistenceAttributes> managedClass : classes) {
            for (RelationAttribute attribute : new ArrayList<>(
                    managedClass.getAttributes().getRelationAttributes())) {
                String entityClass = StringUtils.isBlank(entityMappingsSpec.getPackage())
                        ? attribute.getTargetEntity()
                        : entityMappingsSpec.getPackage() + '.' + attribute.getTargetEntity();
                if (!entities.contains(entityClass)) {
                    progressMsg = NbBundle.getMessage(RevEngWizardDescriptor.class,
                            "MSG_Progress_JPA_Class_Parsing", entityClass + ".java");//NOI18N
                    reporter.progress(progressMsg, progressIndex++);
                    JPAModelGenerator.generateJPAModel(entityMappingsSpec, project, entityClass,
                            packageFileObject, missingEntities);
                    entities.add(entityClass);
                }
            }
        }
    }

    if (!missingEntities.isEmpty()) {
        final String title, _package;
        StringBuilder message = new StringBuilder();
        if (missingEntities.size() == 1) {
            title = "Conflict detected - Entity not found";
            message.append(JavaSourceParserUtil.simpleClassName(missingEntities.get(0))).append(" Entity is ");
        } else {
            title = "Conflict detected - Entities not found";
            message.append("Entities ").append(missingEntities.stream()
                    .map(e -> JavaSourceParserUtil.simpleClassName(e)).collect(toList())).append(" are ");
        }
        if (StringUtils.isEmpty(entityMappingsSpec.getPackage())) {
            _package = "<default_root_package>";
        } else {
            _package = entityMappingsSpec.getPackage();
        }
        message.append("missing in Project classpath[").append(_package)
                .append("]. \n Would like to cancel the process ?");
        SwingUtilities.invokeLater(() -> {
            JButton cancel = new JButton("Cancel import process (Recommended)");
            JButton procced = new JButton("Procced");
            cancel.addActionListener((ActionEvent e) -> {
                Window w = SwingUtilities.getWindowAncestor(cancel);
                if (w != null) {
                    w.setVisible(false);
                }
                StringBuilder sb = new StringBuilder();
                sb.append('\n').append("You have following option to resolve conflict :").append('\n')
                        .append('\n');
                sb.append(
                        "1- New File > Persistence > JPA Diagram from Reverse Engineering (Manually select entities)")
                        .append('\n');
                sb.append(
                        "2- Recover missing entities manually > Reopen diagram file >  Import entities again");
                NotifyDescriptor nd = new NotifyDescriptor.Message(sb.toString(),
                        NotifyDescriptor.INFORMATION_MESSAGE);
                DialogDisplayer.getDefault().notify(nd);
            });
            procced.addActionListener((ActionEvent e) -> {
                Window w = SwingUtilities.getWindowAncestor(cancel);
                if (w != null) {
                    w.setVisible(false);
                }
                manageEntityMappingspec(entityMappingsSpec);
                JPAModelerUtil.createNewModelerFile(entityMappingsSpec, packageFileObject, fileName, softWrite,
                        autoOpen);
            });

            JOptionPane.showOptionDialog(WindowManager.getDefault().getMainWindow(), message.toString(), title,
                    OK_CANCEL_OPTION, ERROR_MESSAGE, UIManager.getIcon("OptionPane.errorIcon"),
                    new Object[] { cancel, procced }, cancel);
        });

    } else {
        manageEntityMappingspec(entityMappingsSpec);
        JPAModelerUtil.createNewModelerFile(entityMappingsSpec, packageFileObject, fileName, softWrite,
                autoOpen);
        return entityMappingsSpec;
    }

    throw new ProcessInterruptedException();
}

From source file:org.nuclos.client.main.MainController.java

private void handleMessage(final Message msg) {
    try {/*from  w  w  w  .  j  a  va 2  s . c om*/
        if ((msg.getJMSCorrelationID() == null
                || msg.getJMSCorrelationID().equals(MainController.this.getUserName()))
                && msg instanceof ObjectMessage) {
            final Object objMessage = ((ObjectMessage) msg).getObject();

            if (objMessage.getClass().equals(ApiMessageImpl.class)) {
                final ApiMessageImpl apiMsg = (ApiMessageImpl) ((ObjectMessage) msg).getObject();
                LOG.info("Handle " + apiMsg);
                Component parent = null;
                if (apiMsg.getReceiverId() != null) {
                    MainFrameTab target = MainFrameTab.getMainFrameTab(apiMsg.getReceiverId());
                    parent = target;
                    if (target != null) {
                        if (apiMsg.getMessage().isOverlay()) {
                            OverlayOptionPane.showMessageDialog(target, apiMsg.getMessage().getMessage(),
                                    apiMsg.getMessage().getTitle(), new OvOpAdapter() {
                                    });
                            return;
                        }
                    } else {
                        LOG.warn(String.format("Receiver with id %s not found!", apiMsg.getReceiverId()));
                    }
                }

                if (parent == null) {
                    parent = Main.getInstance().getMainFrame();
                }
                JOptionPane.showMessageDialog(parent, apiMsg.getMessage().getMessage(),
                        apiMsg.getMessage().getTitle(), JOptionPane.INFORMATION_MESSAGE);
            } else if (objMessage.getClass().equals(RuleNotification.class)) {
                final RuleNotification notification = (RuleNotification) ((ObjectMessage) msg).getObject();
                getNotificationDialog().addMessage(notification);
                switch (notification.getPriority()) {
                case LOW:
                    // just add the message, nothing else.
                    break;
                case NORMAL:
                    getMainFrame().getMessagePanel().startFlashing();
                    break;
                case HIGH:
                    getNotificationDialog().setVisible(true);
                    break;
                default:
                    LOG.warn("Undefined message priority: " + notification.getPriority());
                }
                LOG.info("Handled RuleNotification " + notification.toDescription());
            } else if (objMessage.getClass().equals(CommandMessage.class)) {
                final CommandMessage command = (CommandMessage) ((ObjectMessage) msg).getObject();
                switch (command.getCommand()) {
                case CommandMessage.CMD_SHUTDOWN:
                    getNotificationDialog().addMessage(new RuleNotification(Priority.HIGH,
                            getSpringLocaleDelegate().getMessage("MainController.19",
                                    "Der Client wird auf Anweisung des Administrators in 10 Sekunden beendet."),
                            "Administrator"));
                    getNotificationDialog().setVisible(true);

                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(10000);
                            } catch (InterruptedException e) {
                                // do nothing
                            } finally {
                                MainController.this.cmdExit();
                            }
                        }
                    });
                    break;
                }
                LOG.info("Handled CommandMessage " + command);
            } else if (objMessage.getClass().equals(CommandInformationMessage.class)) {
                final CommandInformationMessage command = (CommandInformationMessage) ((ObjectMessage) msg)
                        .getObject();
                switch (command.getCommand()) {
                case CommandInformationMessage.CMD_INFO_SHUTDOWN:
                    Object[] options = { "OK" };
                    int decision = JOptionPane.showOptionDialog(getMainFrame(), command.getInfo(),
                            getSpringLocaleDelegate().getMessage("MainController.17",
                                    "Administrator - Passwort\u00e4nderung"),
                            JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options,
                            options[0]);
                    if (decision == 0 || decision == JOptionPane.CLOSED_OPTION
                            || decision == JOptionPane.NO_OPTION) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(10000);
                                } catch (InterruptedException e) {
                                    // do nothing
                                } finally {
                                    MainController.this.cmdExit();
                                }
                            }
                        }, "MainController.handleMessage.cmdExit").run();
                    }
                    break;
                }
                LOG.info("Handled CommandInformationMessage " + command);
            }
        } else {
            LOG.warn(getSpringLocaleDelegate().getMessage("MainController.14",
                    "Message of type {0} received, while an ObjectMessage was expected.",
                    msg.getClass().getName()));
        }
    } catch (JMSException ex) {
        LOG.warn("Exception thrown in JMS message listener.", ex);
    }
}

From source file:org.opendatakit.briefcase.ui.MainClearBriefcasePreferencesWindow.java

/**
 * Launch the application./*from  w  w  w . jav  a 2s.  c om*/
 */
public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                // Set System L&F
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                Image myImage = Toolkit.getDefaultToolkit().getImage(
                        MainClearBriefcasePreferencesWindow.class.getClassLoader().getResource("odk_logo.png"));
                Object[] options = { "Purge", "Cancel" };
                int outcome = JOptionPane.showOptionDialog(null,
                        "Clear all Briefcase preferences.                                            ",
                        CLEAR_PREFERENCES_VERSION, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE,
                        new ImageIcon(myImage), options, options[1]);
                if (outcome == 0) {
                    BriefcasePreferences.setBriefcaseDirectoryProperty(null);
                }
            } catch (Exception e) {
                log.error("failed to launch app", e);
            }
        }
    });
}

From source file:org.opendatakit.briefcase.ui.MainFormUploaderWindow.java

/**
 * Initialize the contents of the frame.
 *//*  w  w w  .j  av  a  2s  .co m*/
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 680, 206);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel lblFormDefinitionFile = new JLabel("Form Definition to upload:");

    txtFormDefinitionFile = new JTextField();
    txtFormDefinitionFile.setFocusable(false);
    txtFormDefinitionFile.setEditable(false);
    txtFormDefinitionFile.setColumns(10);

    btnChoose = new JButton("Choose...");
    btnChoose.addActionListener(new FormDefinitionActionListener());

    txtDestinationName = new JTextField();
    txtDestinationName.setFocusable(false);
    txtDestinationName.setEditable(false);
    txtDestinationName.setColumns(10);

    btnChooseServer = new JButton("Configure...");
    btnChooseServer.addActionListener(new DestinationActionListener());

    lblUploading = new JLabel("");

    btnDetails = new JButton("Details...");
    btnDetails.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (fs != null) {
                ScrollingStatusListDialog.showDialog(MainFormUploaderWindow.this.frame, fs.getFormDefinition(),
                        fs.getStatusHistory());
            }
        }
    });

    btnUploadForm = new JButton("Upload Form");
    btnUploadForm.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            setActiveTransferState(true);
            File formDefn = new File(txtFormDefinitionFile.getText());
            TransferAction.uploadForm(MainFormUploaderWindow.this.frame.getOwner(), destinationServerInfo,
                    terminationFuture, formDefn, fs);
        }
    });

    btnCancel = new JButton("Cancel");
    btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            terminationFuture.markAsCancelled(new TransferAbortEvent("Form upload cancelled by user."));
        }
    });

    btnClose = new JButton("Close");
    btnClose.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (transferStateActive) {
                if (JOptionPane.YES_OPTION != JOptionPane.showOptionDialog(frame,
                        "An upload is in progress. Are you sure you want to abort and exit?",
                        "Confirm Stop Form Upload", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null,
                        null, null)) {
                    return; // no-op
                }
                terminationFuture.markAsCancelled(new TransferAbortEvent("User closes window"));
            }
            frame.setVisible(false);
            frame.dispose();
            System.exit(0);
        }
    });

    JLabel lblUploadToServer = new JLabel("Upload to server:");

    GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
    groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup().addContainerGap()
            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(lblFormDefinitionFile)
                    .addComponent(lblUploadToServer).addComponent(lblUploading))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                    .addComponent(txtFormDefinitionFile, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
                            Short.MAX_VALUE)
                    .addComponent(txtDestinationName, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
                            Short.MAX_VALUE)
                    .addGroup(Alignment.TRAILING,
                            groupLayout.createSequentialGroup().addComponent(btnDetails)
                                    .addPreferredGap(ComponentPlacement.RELATED).addComponent(btnUploadForm)
                                    .addPreferredGap(ComponentPlacement.RELATED).addComponent(btnCancel)))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                            .addComponent(btnChoose, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE,
                                    Short.MAX_VALUE)
                            .addComponent(btnChooseServer, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE))
                    .addComponent(btnClose))
            .addContainerGap());
    groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup().addContainerGap()
                    .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                            .addComponent(txtFormDefinitionFile, GroupLayout.PREFERRED_SIZE,
                                    GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblFormDefinitionFile).addComponent(btnChoose))
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addGroup(
                            groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblUploadToServer)
                                    .addComponent(txtDestinationName, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btnChooseServer))
                    .addPreferredGap(ComponentPlacement.UNRELATED, 10, Short.MAX_VALUE)
                    .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(lblUploading)
                            .addComponent(btnDetails).addComponent(btnUploadForm).addComponent(btnCancel)
                            .addComponent(btnClose))
                    .addContainerGap()));

    frame.getContentPane().setLayout(groupLayout);
    setActiveTransferState(false);
}

From source file:org.openuat.apps.IPSecConnectorAdmin.java

/**
 * dialog to set up the dongle configuration.
 *//*from w  w w.  j  a va 2 s  . c om*/
private static Configuration configureDialog(String[] ports, String[] sides, String[] types) {
    JTextField username = new JTextField();
    JComboBox cport = new JComboBox(ports);
    JComboBox csides = new JComboBox(sides);
    JComboBox ctypes = new JComboBox(types);
    int option = JOptionPane.showOptionDialog(null,
            new Object[] { "User Name:", username, "Choose your port", cport,
                    "On which side of your Device is the Dongle plugged into:", csides, " What type of Device:",
                    ctypes, },
            " Relate Dongle Configuration", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null,
            null);
    if ((option == JOptionPane.CLOSED_OPTION) || (option == JOptionPane.CANCEL_OPTION)) {
        System.exit(0);
    }
    Configuration config = new Configuration(cport.getSelectedItem() + "");
    config.setType(ctypes.getSelectedIndex());
    config.setSide(csides.getSelectedIndex());
    config.setUserName(username.getText());
    config.setDeviceType(Configuration.DEVICE_TYPE_DONGLE);
    //      logger.finer(config);
    return config;
}

From source file:org.orbisgis.mapeditor.map.MapEditor.java

/**
 * The use want to export the rendering into a file.
 */// w  w  w  .ja va 2  s.c o m
public void onExportMapRendering() {
    // Show Dialog to select image size
    final String WIDTH_T = "width";
    final String HEIGHT_T = "height";
    final String RATIO_CHECKBOX_T = "ratio checkbox";
    final String TRANSPARENT_BACKGROUND_T = "background";
    final String DPI_T = "dpi";
    final int textWidth = 8;
    final MultiInputPanel inputPanel = new MultiInputPanel(I18N.tr("Export parameters"));

    inputPanel.addInput(TRANSPARENT_BACKGROUND_T, "", "True",
            new CheckBoxChoice(true, "<html>" + I18N.tr("Transparent\nbackground") + "</html>"));

    inputPanel.addInput(DPI_T, I18N.tr("DPI"),
            String.valueOf((int) (MapImageWriter.MILLIMETERS_BY_INCH / MapImageWriter.DEFAULT_PIXEL_SIZE)),
            new TextBoxType(textWidth));

    TextBoxType tbWidth = new TextBoxType(textWidth);
    inputPanel.addInput(WIDTH_T, I18N.tr("Width (pixels)"), String.valueOf(mapControl.getImage().getWidth()),
            tbWidth);
    TextBoxType tbHeight = new TextBoxType(textWidth);
    inputPanel.addInput(HEIGHT_T, I18N.tr("Height (pixels)"), String.valueOf(mapControl.getImage().getHeight()),
            tbHeight);

    tbHeight.getComponent().addFocusListener(new FocusAdapter() {

        @Override
        public void focusGained(FocusEvent e) {
            userChangedHeight = true;
        }

        @Override
        public void focusLost(FocusEvent e) {
            updateWidth();
        }

        private void updateWidth() {
            if (userChangedHeight) {
                if (inputPanel.getInput(RATIO_CHECKBOX_T).equals("true")) {
                    // Change image width to keep ratio
                    final String heightString = inputPanel.getInput(HEIGHT_T);
                    if (!heightString.isEmpty()) {
                        try {
                            final Envelope adjExtent = mapControl.getMapTransform().getAdjustedExtent();
                            final double ratio = adjExtent.getWidth() / adjExtent.getHeight();
                            final int height = Integer.parseInt(heightString);
                            final long newWidth = Math.round(height * ratio);
                            inputPanel.setValue(WIDTH_T, String.valueOf(newWidth));
                        } catch (NumberFormatException e) {
                        }
                    }
                }
            }
            userChangedWidth = false;
        }
    });

    tbWidth.getComponent().addFocusListener(new FocusAdapter() {

        @Override
        public void focusGained(FocusEvent e) {
            userChangedWidth = true;
        }

        @Override
        public void focusLost(FocusEvent e) {
            updateHeight();
        }

        private void updateHeight() {
            if (userChangedWidth) {
                if (inputPanel.getInput(RATIO_CHECKBOX_T).equals("true")) {
                    // Change image height to keep ratio
                    final String widthString = inputPanel.getInput(WIDTH_T);
                    if (!widthString.isEmpty()) {
                        try {
                            final Envelope adjExtent = mapControl.getMapTransform().getAdjustedExtent();
                            final double ratio = adjExtent.getHeight() / adjExtent.getWidth();
                            final int width = Integer.parseInt(widthString);
                            final long newHeight = Math.round(width * ratio);
                            inputPanel.setValue(HEIGHT_T, String.valueOf(newHeight));
                        } catch (NumberFormatException e) {
                        }
                    }
                }
            }
            userChangedHeight = false;
        }
    });

    inputPanel.addInput(RATIO_CHECKBOX_T, "", new CheckBoxChoice(true, I18N.tr("Keep ratio")));

    inputPanel.addValidation(new MIPValidationInteger(WIDTH_T, I18N.tr("Width (pixels)")));
    inputPanel.addValidation(new MIPValidationInteger(HEIGHT_T, I18N.tr("Height (pixels)")));
    inputPanel.addValidation(new MIPValidationInteger(DPI_T, I18N.tr("DPI")));

    JButton refreshButton = new JButton(I18N.tr("Reset extent"));
    refreshButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            inputPanel.setValue(WIDTH_T, String.valueOf(mapControl.getImage().getWidth()));
            inputPanel.setValue(HEIGHT_T, String.valueOf(mapControl.getImage().getHeight()));
        }
    });

    // Show the dialog and get the user's choice.
    int userChoice = JOptionPane.showOptionDialog(this, inputPanel.getComponent(),
            I18N.tr("Export map as image"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
            MapEditorIcons.getIcon("map_catalog"),
            new Object[] { I18N.tr("OK"), I18N.tr("Cancel"), refreshButton }, null);

    // If the user clicked OK, then show the save image dialog.
    if (userChoice == JOptionPane.OK_OPTION) {
        MapImageWriter mapImageWriter = new MapImageWriter(mapContext.getLayerModel());
        mapImageWriter
                .setPixelSize(MapImageWriter.MILLIMETERS_BY_INCH / Double.valueOf(inputPanel.getInput(DPI_T)));
        // If the user want a background color, let him choose one
        if (!Boolean.valueOf(inputPanel.getInput(TRANSPARENT_BACKGROUND_T))) {
            ColorPicker colorPicker = new ColorPicker(Color.white);
            if (!UIFactory.showDialog(colorPicker, true, true)) {
                return;
            }
            mapImageWriter.setBackgroundColor(colorPicker.getColor());
        }
        // Save the picture in which location
        final SaveFilePanel outfilePanel = new SaveFilePanel("MapEditor.ExportInFile",
                I18N.tr("Save the map as image : " + mapContext.getTitle()));
        outfilePanel.addFilter("png", I18N.tr("Portable Network Graphics"));
        outfilePanel.addFilter("tiff", I18N.tr("Tagged Image File Format"));
        outfilePanel.addFilter("jpg", I18N.tr("Joint Photographic Experts Group"));
        outfilePanel.addFilter("pdf", I18N.tr("Portable Document Format"));
        outfilePanel.loadState(); // Load last use path
        // Show save into dialog
        if (UIFactory.showDialog(outfilePanel, true, true)) {
            File outFile = outfilePanel.getSelectedFile();
            String fileName = FilenameUtils.getExtension(outFile.getName());
            if (fileName.equalsIgnoreCase("png")) {
                mapImageWriter.setFormat(MapImageWriter.Format.PNG);
            } else if (fileName.equalsIgnoreCase("jpg")) {
                mapImageWriter.setFormat(MapImageWriter.Format.JPEG);
            } else if (fileName.equalsIgnoreCase("pdf")) {
                mapImageWriter.setFormat(MapImageWriter.Format.PDF);
            } else {
                mapImageWriter.setFormat(MapImageWriter.Format.TIFF);
            }
            mapImageWriter.setBoundingBox(mapContext.getBoundingBox());
            int width = Integer.valueOf(inputPanel.getInput(WIDTH_T));
            int height = Integer.valueOf(inputPanel.getInput(HEIGHT_T));

            mapImageWriter.setWidth(width);
            mapImageWriter.setHeight(height);
            execute(new ExportRenderingIntoFile(mapImageWriter, outFile));
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.drilldown.devtools.DrillDownProfileEditor.java

public void create() {
    final int retval = JOptionPane.showOptionDialog(this, "Select link customizer type",
            "Select Link Customizer Type", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null,
            new Class[] { FormulaLinkCustomizer.class, PatternLinkCustomizer.class },
            FormulaLinkCustomizer.class);
    if (retval == 0) {
        drillDownProfiles.addElement(new DrillDownProfile(FormulaLinkCustomizer.class));
    } else if (retval == 1) {
        drillDownProfiles.addElement(new DrillDownProfile(PatternLinkCustomizer.class));
    }/*from  w  ww .  j  a va  2s.  c o  m*/
}

From source file:org.pgptool.gui.ui.tools.UiUtils.java

/**
 * @param messageType//w w w . j  a  v a  2s .  c  o m
 *            one of the JOptionPane ERROR_MESSAGE, INFORMATION_MESSAGE,
 *            WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE
 */
public static void messageBox(Component parent, String msg, String title, int messageType) {
    Object content = buildMessageContentDependingOnLength(msg);

    if (messageType != JOptionPane.ERROR_MESSAGE) {
        JOptionPane.showMessageDialog(parent, content, title, messageType);
        return;
    }

    Object[] options = { text("action.ok"), text("phrase.saveMsgToFile") };
    if ("action.ok".equals(options[0])) {
        // if app context wasn't started MessageSource wont be available
        options = new String[] { "OK", "Save message to file" };
    }

    int result = JOptionPane.showOptionDialog(parent, content, title, JOptionPane.YES_NO_OPTION, messageType,
            null, options, JOptionPane.YES_OPTION);
    if (result == JOptionPane.YES_OPTION || result == JOptionPane.CLOSED_OPTION) {
        return;
    }

    // Save to file
    saveMessageToFile(parent, msg);
}

From source file:org.photovault.swingui.Photovault.java

private void login(LoginDlg ld) throws PhotovaultException {
    boolean success = false;
    String user = ld.getUsername();
    String passwd = ld.getPassword();
    String dbName = ld.getDb();//  ww w  . j  a  v  a 2s .c om
    log.debug("Using configuration " + dbName);
    settings.setConfiguration(dbName);
    PVDatabase db = settings.getDatabase(dbName);

    HibernateUtil.init(user, passwd, db);

    // TODO: Hack...
    currentSession = HibernateUtil.getSessionFactory().openSession();
    ManagedSessionContext.bind((org.hibernate.classic.Session) currentSession);
    log.debug("Connection succesful!!!");
    // Login is succesfull
    // ld.setVisible( false );
    success = true;

    int schemaVersion = db.getSchemaVersion();
    if (schemaVersion < PVDatabase.CURRENT_SCHEMA_VERSION) {
        String options[] = { "Proceed", "Exit Photovault" };
        if (JOptionPane.YES_OPTION == JOptionPane.showOptionDialog(ld,
                "The database was created with an older version of Photovault\n"
                        + "Photovault will upgrade the database format before starting.",
                "Upgrade database", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                null)) {
            final SchemaUpdateAction updater = new SchemaUpdateAction(db);
            SchemaUpdateStatusDlg statusDlg = new SchemaUpdateStatusDlg(null, true);
            updater.addSchemaUpdateListener(statusDlg);
            Thread upgradeThread = new Thread() {

                @Override
                public void run() {
                    updater.upgradeDatabase();
                }
            };
            upgradeThread.start();
            statusDlg.setVisible(true);
            success = true;
        } else {
            System.exit(0);
        }
    }
}

From source file:org.qcc.modules.learningpalette.OptionsPlugin.LearningPalettePanel.java

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

    //First validate the input:
    //Palette Item name does not already exist, for one
    for (int i = 0; i < pItemCombo.getItemCount(); i++) {
        PaletteItem compare = (PaletteItem) pItemCombo.getItemAt(i);
        if (compare != selectedPaletteItem
                && compare.getItemName().trim().equals(this.itemNameText.getText().trim())) {
            JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(this),
                    "A palette item already exists with that name, choose a new name.");
            return;
        }/*from  ww w.j  a  v  a  2 s.  c o m*/
    }
    //That user has not started to type a customizer in and failed ot add it.
    //Custom button text
    if (customizerLabel.getText().trim().length() > 0 || customizerReplace.getText().trim().length() > 0) {
        Object[] options = { "Yes", "No" };
        int n = JOptionPane.showOptionDialog(SwingUtilities.getWindowAncestor(this),
                "You have started to add a customizer, but \n" + "have not clicked save, continue?",
                "Are you sure?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[1]);

        if (n != 0) {
            return;
        }
    }

    try {
        //Generate XML Document
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        org.w3c.dom.Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("PaletteItem");
        doc.appendChild(rootElement);

        Element category = doc.createElement("Category");
        category.setTextContent("User Defined");
        rootElement.appendChild(category);

        Element displayName = doc.createElement("DisplayName");
        displayName.setTextContent(this.itemNameText.getText().trim());
        rootElement.appendChild(displayName);

        Element toolTip = doc.createElement("Tooltip");
        toolTip.setTextContent(this.descriptionText.getText());
        rootElement.appendChild(toolTip);

        Element languagesParent = doc.createElement("Languages");

        for (String language : languageList) {
            String outputMapping;
            if (codeMapping.containsKey(language) == false) {
                outputMapping = "";
            } else {
                outputMapping = codeMapping.get(language);
            }

            Element languageParent = doc.createElement("Language");
            languageParent.setAttribute("id", language);
            Element codeTemplate = doc.createElement("codeTemplate");
            codeTemplate.setTextContent(outputMapping);
            languageParent.appendChild(codeTemplate);
            languagesParent.appendChild(languageParent);

        }
        rootElement.appendChild(languagesParent);

        //org.qcc.modules.learningpalette.LP_BasicInput.java
        Element paletteClass = doc.createElement("PaletteLogicClass");
        paletteClass.setTextContent("org.qcc.modules.learningpalette.LP_BasicInput");
        rootElement.appendChild(paletteClass);

        //Create Customizer (For later use)
        Element customizerParent = doc.createElement("Customizer");
        rootElement.appendChild(customizerParent);

        for (CustomizerControl control : customizerControls) {
            Element customizerItem = doc.createElement("Item");
            customizerItem.setAttribute("type", control.getType());
            customizerItem.setAttribute("name", control.getName());
            customizerItem.setAttribute("label", control.getLabel());
            customizerItem.setAttribute("value", "");
            customizerParent.appendChild(customizerItem);
        }

        //Create file name 
        if (currentFileName == null) {
            String fileName = "UserDefined_";

            //Random number
            int uniqueID = randInt(0, 9999999);
            //Random letter
            char c = (char) randInt(65, 90);

            currentFileName = fileName + uniqueID + c + ".xml";
        }

        //Get the directory to save to.
        String saveDirectory = System.getProperty("user.dir") + "\\LearningPaletteXML";

        //Make the directory if necessary
        File newDirectory = new File(saveDirectory);
        if (!newDirectory.exists()) {
            if (newDirectory.mkdir()) {
                System.out.println("Directory is created!");
            } else {
                System.out.println("Failed to create directory!");
            }
        }

        //Save the file
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        Result output = new StreamResult(new File(saveDirectory + "\\" + currentFileName));
        Source input = new DOMSource(doc);
        transformer.transform(input, output);

        loadPaletteItems((this.itemNameText.getText()));

        //Now reload the form with the saved list of palette items.
        //pItemCombo.revalidate();
        //pItemCombo.repaint();
    } catch (Exception ex) {
        //TODO: Exception handling.
        System.out.println(ex.getMessage());
    }

}