Example usage for javax.swing JComboBox getSelectedItem

List of usage examples for javax.swing JComboBox getSelectedItem

Introduction

In this page you can find the example usage for javax.swing JComboBox getSelectedItem.

Prototype

public Object getSelectedItem() 

Source Link

Document

Returns the current selected item.

Usage

From source file:com.entertailion.java.fling.FlingFrame.java

public FlingFrame(String appId) {
    super();/*from  w  w  w . j  a  va 2  s.  c o m*/
    this.appId = appId;
    rampClient = new RampClient(this);

    addWindowListener(this);

    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Locale locale = Locale.getDefault();
    resourceBundle = ResourceBundle.getBundle("com/entertailion/java/fling/resources/resources", locale);
    setTitle(MessageFormat.format(resourceBundle.getString("fling.title"), Fling.VERSION));

    JPanel listPane = new JPanel();
    // show list of ChromeCast devices detected on the local network
    listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS));
    JPanel devicePane = new JPanel();
    devicePane.setLayout(new BoxLayout(devicePane, BoxLayout.LINE_AXIS));
    deviceList = new JComboBox();
    deviceList.addActionListener(this);
    devicePane.add(deviceList);
    URL url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/refresh.png");
    ImageIcon icon = new ImageIcon(url, resourceBundle.getString("button.refresh"));
    refreshButton = new JButton(icon);
    refreshButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // refresh the list of devices
            if (deviceList.getItemCount() > 0) {
                deviceList.setSelectedIndex(0);
            }
            discoverDevices();
        }
    });
    refreshButton.setToolTipText(resourceBundle.getString("button.refresh"));
    devicePane.add(refreshButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/settings.png");
    icon = new ImageIcon(url, resourceBundle.getString("settings.title"));
    settingsButton = new JButton(icon);
    settingsButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JTextField transcodingExtensions = new JTextField(50);
            transcodingExtensions.setText(transcodingExtensionValues);
            JTextField transcodingParameters = new JTextField(50);
            transcodingParameters.setText(transcodingParameterValues);

            JPanel myPanel = new JPanel(new BorderLayout());
            JPanel labelPanel = new JPanel(new GridLayout(3, 1));
            JPanel fieldPanel = new JPanel(new GridLayout(3, 1));
            myPanel.add(labelPanel, BorderLayout.WEST);
            myPanel.add(fieldPanel, BorderLayout.CENTER);
            labelPanel.add(new JLabel(resourceBundle.getString("transcoding.extensions"), JLabel.RIGHT));
            fieldPanel.add(transcodingExtensions);
            labelPanel.add(new JLabel(resourceBundle.getString("transcoding.parameters"), JLabel.RIGHT));
            fieldPanel.add(transcodingParameters);
            labelPanel.add(new JLabel(resourceBundle.getString("device.manual"), JLabel.RIGHT));
            JPanel devicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
            final JComboBox manualDeviceList = new JComboBox();
            if (manualServers.size() == 0) {
                manualDeviceList.setVisible(false);
            } else {
                for (DialServer dialServer : manualServers) {
                    manualDeviceList.addItem(dialServer);
                }
            }
            devicePanel.add(manualDeviceList);
            JButton addButton = new JButton(resourceBundle.getString("device.manual.add"));
            addButton.setToolTipText(resourceBundle.getString("device.manual.add.tooltip"));
            addButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    JTextField name = new JTextField();
                    JTextField ipAddress = new JTextField();
                    Object[] message = { resourceBundle.getString("device.manual.name") + ":", name,
                            resourceBundle.getString("device.manual.ipaddress") + ":", ipAddress };

                    int option = JOptionPane.showConfirmDialog(null, message,
                            resourceBundle.getString("device.manual"), JOptionPane.OK_CANCEL_OPTION);
                    if (option == JOptionPane.OK_OPTION) {
                        try {
                            manualServers.add(
                                    new DialServer(name.getText(), InetAddress.getByName(ipAddress.getText())));

                            Object selected = deviceList.getSelectedItem();
                            int selectedIndex = deviceList.getSelectedIndex();
                            deviceList.removeAllItems();
                            deviceList.addItem(resourceBundle.getString("devices.select"));
                            for (DialServer dialServer : servers) {
                                deviceList.addItem(dialServer);
                            }
                            for (DialServer dialServer : manualServers) {
                                deviceList.addItem(dialServer);
                            }
                            deviceList.invalidate();
                            if (selectedIndex > 0) {
                                deviceList.setSelectedItem(selected);
                            } else {
                                if (deviceList.getItemCount() == 2) {
                                    // Automatically select single device
                                    deviceList.setSelectedIndex(1);
                                }
                            }

                            manualDeviceList.removeAllItems();
                            for (DialServer dialServer : manualServers) {
                                manualDeviceList.addItem(dialServer);
                            }
                            manualDeviceList.setVisible(true);
                            storeProperties();
                        } catch (UnknownHostException e1) {
                            Log.e(LOG_TAG, "manual IP address", e1);

                            JOptionPane.showMessageDialog(FlingFrame.this,
                                    resourceBundle.getString("device.manual.invalidip"));
                        }
                    }
                }
            });
            devicePanel.add(addButton);
            JButton removeButton = new JButton(resourceBundle.getString("device.manual.remove"));
            removeButton.setToolTipText(resourceBundle.getString("device.manual.remove.tooltip"));
            removeButton.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    Object selected = manualDeviceList.getSelectedItem();
                    manualDeviceList.removeItem(selected);
                    if (manualDeviceList.getItemCount() == 0) {
                        manualDeviceList.setVisible(false);
                    }
                    deviceList.removeItem(selected);
                    deviceList.invalidate();
                    manualServers.remove(selected);
                    storeProperties();
                }
            });
            devicePanel.add(removeButton);
            fieldPanel.add(devicePanel);
            int result = JOptionPane.showConfirmDialog(FlingFrame.this, myPanel,
                    resourceBundle.getString("settings.title"), JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                transcodingParameterValues = transcodingParameters.getText();
                transcodingExtensionValues = transcodingExtensions.getText();
                storeProperties();
            }
        }
    });
    settingsButton.setToolTipText(resourceBundle.getString("settings.title"));
    devicePane.add(settingsButton);
    listPane.add(devicePane);

    // TODO
    volume = new JSlider(JSlider.VERTICAL, 0, 100, 0);
    volume.setUI(new MySliderUI(volume));
    volume.setMajorTickSpacing(25);
    // volume.setMinorTickSpacing(5);
    volume.setPaintTicks(true);
    volume.setEnabled(true);
    volume.setValue(100);
    volume.setToolTipText(resourceBundle.getString("volume.title"));
    volume.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider source = (JSlider) e.getSource();
            if (!source.getValueIsAdjusting()) {
                int position = (int) source.getValue();
                rampClient.volume(position / 100.0f);
            }
        }

    });
    JPanel centerPanel = new JPanel(new BorderLayout());
    // centerPanel.add(volume, BorderLayout.WEST);

    centerPanel.add(DragHereIcon.makeUI(this), BorderLayout.CENTER);
    listPane.add(centerPanel);

    scrubber = new JSlider(JSlider.HORIZONTAL, 0, 100, 0);
    scrubber.addChangeListener(this);
    scrubber.setMajorTickSpacing(25);
    scrubber.setMinorTickSpacing(5);
    scrubber.setPaintTicks(true);
    scrubber.setEnabled(false);
    listPane.add(scrubber);

    // panel of playback buttons
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    label = new JLabel("00:00:00");
    buttonPane.add(label);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/play.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.play"));
    playButton = new JButton(icon);
    playButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.play();
        }
    });
    buttonPane.add(playButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/pause.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.pause"));
    pauseButton = new JButton(icon);
    pauseButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.pause();
        }
    });
    buttonPane.add(pauseButton);
    url = ClassLoader.getSystemResource("com/entertailion/java/fling/resources/stop.png");
    icon = new ImageIcon(url, resourceBundle.getString("button.stop"));
    stopButton = new JButton(icon);
    stopButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            rampClient.stop();
            setDuration(0);
            scrubber.setValue(0);
            scrubber.setEnabled(false);
        }
    });
    buttonPane.add(stopButton);
    listPane.add(buttonPane);
    getContentPane().add(listPane);

    createProgressDialog();
    startWebserver();
    discoverDevices();
}

From source file:ucar.unidata.idv.flythrough.Flythrough.java

/**
 * _more_//from  w  w  w .j a v a2  s .c  o  m
 *
 * @param pt _more_
 *
 * @return _more_
 */
private boolean showProperties(FlythroughPoint pt) {
    try {
        DateTime[] times = viewManager.getAnimationWidget().getTimes();
        JComboBox timeBox = null;
        JLabel timeLabel = GuiUtils.rLabel("Time:");
        Vector timesList = new Vector();
        timesList.add(0, new TwoFacedObject("None", null));
        if ((times != null) && (times.length > 0)) {
            timesList.addAll(Misc.toList(times));
        }
        if ((pt.getDateTime() != null) && !timesList.contains(pt.getDateTime())) {
            timesList.add(pt.getDateTime());
        }
        timeBox = new JComboBox(timesList);
        if (pt.getDateTime() != null) {
            timeBox.setSelectedItem(pt.getDateTime());
        }

        LatLonWidget llw = new LatLonWidget("Latitude: ", "Longitude: ", "Altitude: ", null) {
            protected String formatLatLonString(String latOrLon) {
                return latOrLon;
            }
        };

        EarthLocation el = pt.getEarthLocation();
        llw.setLatLon(el.getLatitude().getValue(CommonUnit.degree),
                el.getLongitude().getValue(CommonUnit.degree));
        llw.setAlt(getAlt(el));

        JTextArea textArea = new JTextArea("", 5, 100);
        if (pt.getDescription() != null) {
            textArea.setText(pt.getDescription());
        }
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(400, 300));
        JComponent contents = GuiUtils.formLayout(new Component[] { GuiUtils.rLabel("Location:"), llw,
                timeLabel, GuiUtils.left(timeBox), GuiUtils.rLabel("Description:"), scrollPane });
        if (!GuiUtils.showOkCancelDialog(frame, "Point Properties", contents, null)) {
            return false;
        }
        pt.setDescription(textArea.getText());
        pt.setEarthLocation(makePoint(llw.getLat(), llw.getLon(), llw.getAlt()));
        Object selectedDate = timeBox.getSelectedItem();
        if (selectedDate instanceof TwoFacedObject) {
            pt.setDateTime(null);
        } else {
            pt.setDateTime((DateTime) selectedDate);
        }

        return true;
    } catch (Exception exc) {
        logException("Showing point properties", exc);
        return false;
    }

}

From source file:com.osparking.osparking.Settings_System.java

private int saveGateDevices(boolean[] majorChange) {
    Connection conn = null;/*from w w w  . j  a v  a2  s  . c  o  m*/
    PreparedStatement updateSettings = null;
    int result = 0;
    int updateRowCount = 0;

    //<editor-fold desc="-- Create update statement">
    StringBuffer sb = new StringBuffer("Update gatedevices SET ");

    sb.append("  gatename = ? ");
    sb.append("  , cameraType = ?");
    sb.append("  , cameraIP = ? ");
    sb.append("  , cameraPort = ?");
    sb.append("  , e_boardType = ? ");
    sb.append("  , e_boardConnType = ? ");
    sb.append("  , e_boardCOM_ID = ? ");
    sb.append("  , e_boardIP = ? ");
    sb.append("  , e_boardPort = ? ");
    sb.append("  , gatebarType = ? ");
    sb.append("  , gatebarConnType = ? ");
    sb.append("  , gatebarCOM_ID = ? ");
    sb.append("  , gatebarIP = ? ");
    sb.append("  , gatebarPort = ? ");
    sb.append("WHERE GateID = ?");
    //</editor-fold>

    for (int gateID = 1; gateID <= gateCount; gateID++) {
        try {
            conn = JDBCMySQL.getConnection();
            updateSettings = conn.prepareStatement(sb.toString());

            int pIndex = 1;
            JComboBox cBox;

            //<editor-fold defaultstate="collapsed" desc="--Provide actual values to the UPDATE">
            updateSettings.setString(pIndex++,
                    ((JTextField) componentMap.get("TextFieldGateName" + gateID)).getText().trim());

            for (DeviceType type : DeviceType.values()) {
                cBox = (JComboBox) componentMap.get(type.toString() + gateID + "_TypeCBox");

                int newSubType = cBox.getSelectedIndex();
                Object newSubTypeObj = cBox.getSelectedItem();

                if (newSubType != deviceType[type.ordinal()][gateID]) {
                    majorChange[0] = true;
                }

                updateSettings.setInt(pIndex++, cBox == null ? 0 : newSubType);
                if (type != Camera) {
                    cBox = (JComboBox) componentMap.get(type.toString() + gateID + "_connTypeCBox");

                    updateSettings.setInt(pIndex++, cBox == null ? 0 : cBox.getSelectedIndex());

                    cBox = (JComboBox) componentMap.get(type.toString() + gateID + "_comID_CBox");
                    updateSettings.setString(pIndex++, cBox == null ? "" : (String) cBox.getSelectedItem());
                }
                String ipAddrStr = ((JTextField) componentMap.get(type.toString() + gateID + "_IP_TextField"))
                        .getText().trim();
                updateSettings.setString(pIndex++, ipAddrStr);

                giveWarningForRealDevice(gateID, type, newSubTypeObj, ipAddrStr);

                String portStr = "";
                if (newSubType == SIMULATOR) {
                    // Simulator port number is determined programmatically. So, leave the original value alone.
                    portStr = devicePort[type.ordinal()][gateID];
                } else {
                    portStr = ((JTextField) componentMap.get(type.toString() + gateID + "_Port_TextField"))
                            .getText().trim();
                }
                updateSettings.setString(pIndex++, portStr);
            }
            updateSettings.setInt(pIndex++, gateID);
            // </editor-fold>

            result = updateSettings.executeUpdate();

        } catch (SQLException se) {
            Globals.logParkingException(Level.SEVERE, se, "(Save gate & device settings)");
        } finally {
            // <editor-fold defaultstate="collapsed" desc="--Return resources and display the save result">
            closeDBstuff(conn, updateSettings, null, "(Save gate & device settings)");

            if (result == 1) {
                updateRowCount++;
            }
            // </editor-fold>
        }
    }
    return updateRowCount;
}

From source file:userinterface.graph.Histogram.java

/**
 * Generates the property dialog for a Histogram. Allows the user to select either a new or an exisitng Histogram
 * to plot data on//from w  w w .ja  v a  2  s  .  co  m
 * 
 * @param defaultSeriesName
 * @param handler instance of {@link GUIGraphHandler}
 * @param minVal the min value in data cache
 * @param maxVal the max value in data cache
 * @return Either a new instance of a Histogram or an old one depending on what the user selects
 */

public static Pair<Histogram, SeriesKey> showPropertiesDialog(String defaultSeriesName, GUIGraphHandler handler,
        double minVal, double maxVal) {

    // make sure that the probabilities are valid
    if (maxVal > 1.0)
        maxVal = 1.0;
    if (minVal < 0.0)
        minVal = 0.0;

    // set properties for the dialog
    JDialog dialog = new JDialog(GUIPrism.getGUI(), "Histogram properties", true);
    dialog.setLayout(new BorderLayout());

    JPanel p1 = new JPanel(new FlowLayout());
    p1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
            "Number of buckets"));

    JPanel p2 = new JPanel(new FlowLayout());
    p2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
            "Series name"));

    JSpinner buckets = new JSpinner(new SpinnerNumberModel(10, 5, Integer.MAX_VALUE, 1));
    buckets.setToolTipText("Select the number of buckets for this Histogram");

    // provides the ability to select a new or an old histogram to plot the series on
    JTextField seriesName = new JTextField(defaultSeriesName);
    JRadioButton newSeries = new JRadioButton("New Histogram");
    JRadioButton existing = new JRadioButton("Existing Histogram");
    newSeries.setSelected(true);
    JPanel seriesSelectPanel = new JPanel();
    seriesSelectPanel.setLayout(new BoxLayout(seriesSelectPanel, BoxLayout.Y_AXIS));
    JPanel seriesTypeSelect = new JPanel(new FlowLayout());
    JPanel seriesOptionsPanel = new JPanel(new FlowLayout());
    seriesTypeSelect.add(newSeries);
    seriesTypeSelect.add(existing);
    JComboBox<String> seriesOptions = new JComboBox<>();
    seriesOptionsPanel.add(seriesOptions);
    seriesSelectPanel.add(seriesTypeSelect);
    seriesSelectPanel.add(seriesOptionsPanel);
    seriesSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Add series to"));

    // provides ability to select the min/max range of the plot
    JLabel minValsLabel = new JLabel("Min range:");
    JSpinner minVals = new JSpinner(new SpinnerNumberModel(0.0, 0.0, minVal, 0.01));
    minVals.setToolTipText("Does not allow value more than the min value in the probabilities");
    JLabel maxValsLabel = new JLabel("Max range:");
    JSpinner maxVals = new JSpinner(new SpinnerNumberModel(1.0, maxVal, 1.0, 0.01));
    maxVals.setToolTipText("Does not allow value less than the max value in the probabilities");
    JPanel minMaxPanel = new JPanel();
    minMaxPanel.setLayout(new BoxLayout(minMaxPanel, BoxLayout.X_AXIS));
    JPanel leftValsPanel = new JPanel(new BorderLayout());
    JPanel rightValsPanel = new JPanel(new BorderLayout());
    minMaxPanel.setBorder(
            BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Range"));
    leftValsPanel.add(minValsLabel, BorderLayout.WEST);
    leftValsPanel.add(minVals, BorderLayout.CENTER);
    rightValsPanel.add(maxValsLabel, BorderLayout.WEST);
    rightValsPanel.add(maxVals, BorderLayout.CENTER);
    minMaxPanel.add(leftValsPanel);
    minMaxPanel.add(rightValsPanel);

    // fill the old histograms in the property dialog

    boolean found = false;
    for (int i = 0; i < handler.getNumModels(); i++) {

        if (handler.getModel(i) instanceof Histogram) {

            seriesOptions.addItem(handler.getGraphName(i));
            found = true;
        }

    }

    existing.setEnabled(found);
    seriesOptions.setEnabled(false);

    // the bottom panel
    JPanel options = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    JButton ok = new JButton("Plot");
    JButton cancel = new JButton("Cancel");

    // bind keyboard keys to plot and cancel buttons to improve usability

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        private static final long serialVersionUID = -7324877661936685228L;

        @Override
        public void actionPerformed(ActionEvent e) {

            ok.doClick();

        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "ok");
    cancel.getActionMap().put("ok", new AbstractAction() {

        private static final long serialVersionUID = 2642213543774356676L;

        @Override
        public void actionPerformed(ActionEvent e) {

            cancel.doClick();

        }
    });

    //Action listener for the new series radio button
    newSeries.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (newSeries.isSelected()) {

                existing.setSelected(false);
                seriesOptions.setEnabled(false);
                buckets.setEnabled(true);
                buckets.setToolTipText("Select the number of buckets for this Histogram");
                minVals.setEnabled(true);
                maxVals.setEnabled(true);
            }
        }
    });

    //Action listener for the existing series radio button
    existing.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existing.isSelected()) {

                newSeries.setSelected(false);
                seriesOptions.setEnabled(true);
                buckets.setEnabled(false);
                minVals.setEnabled(false);
                maxVals.setEnabled(false);
                buckets.setToolTipText("Number of buckets can't be changed on an existing Histogram");
            }

        }
    });

    //Action listener for the plot button
    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            dialog.dispose();

            if (newSeries.isSelected()) {

                hist = new Histogram();
                hist.setNumOfBuckets((int) buckets.getValue());
                hist.setIsNew(true);

            } else if (existing.isSelected()) {

                String HistName = (String) seriesOptions.getSelectedItem();
                hist = (Histogram) handler.getModel(HistName);
                hist.setIsNew(false);

            }

            key = hist.addSeries(seriesName.getText());

            if (minVals.isEnabled() && maxVals.isEnabled()) {

                hist.setMinProb((double) minVals.getValue());
                hist.setMaxProb((double) maxVals.getValue());

            }
        }
    });

    //Action listener for the cancel button
    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
            hist = null;
        }
    });

    dialog.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {

            hist = null;
        }
    });

    p1.add(buckets, BorderLayout.CENTER);

    p2.add(seriesName, BorderLayout.CENTER);

    options.add(ok);
    options.add(cancel);

    // add everything to the main panel of the dialog
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.add(seriesSelectPanel);
    mainPanel.add(p1);
    mainPanel.add(p2);
    mainPanel.add(minMaxPanel);

    // add main panel to the dialog
    dialog.add(mainPanel, BorderLayout.CENTER);
    dialog.add(options, BorderLayout.SOUTH);

    // set dialog properties
    dialog.setSize(320, 290);
    dialog.setLocationRelativeTo(GUIPrism.getGUI());
    dialog.setVisible(true);

    // return the user selected Histogram with the properties set
    return new Pair<Histogram, SeriesKey>(hist, key);
}

From source file:com.osparking.osparking.Settings_System.java

private void prepareComPortControls() {
    E_Board1_comLabel = new javax.swing.JLabel();
    E_Board2_comLabel = new javax.swing.JLabel();
    E_Board3_comLabel = new javax.swing.JLabel();
    E_Board4_comLabel = new javax.swing.JLabel();
    GateBar1_comLabel = new javax.swing.JLabel();
    GateBar2_comLabel = new javax.swing.JLabel();
    GateBar3_comLabel = new javax.swing.JLabel();
    GateBar4_comLabel = new javax.swing.JLabel();

    E_Board1_comLabel.setName("E_Board1_comLabel"); // E_Board1_comLabel
    E_Board2_comLabel.setName("E_Board2_comLabel");
    E_Board3_comLabel.setName("E_Board3_comLabel");
    E_Board4_comLabel.setName("E_Board4_comLabel");
    GateBar1_comLabel.setName("GateBar1_comLabel");
    GateBar2_comLabel.setName("GateBar2_comLabel");
    GateBar3_comLabel.setName("GateBar3_comLabel");
    GateBar4_comLabel.setName("GateBar4_comLabel");

    augmentComponentMap(E_Board1_comLabel, componentMap);
    augmentComponentMap(E_Board2_comLabel, componentMap);
    augmentComponentMap(E_Board3_comLabel, componentMap);
    augmentComponentMap(E_Board4_comLabel, componentMap);
    augmentComponentMap(GateBar1_comLabel, componentMap);
    augmentComponentMap(GateBar2_comLabel, componentMap);
    augmentComponentMap(GateBar3_comLabel, componentMap);
    augmentComponentMap(GateBar4_comLabel, componentMap);

    initComPortIDLabel(E_Board1_comLabel);
    initComPortIDLabel(E_Board2_comLabel);
    initComPortIDLabel(E_Board3_comLabel);
    initComPortIDLabel(E_Board4_comLabel);
    initComPortIDLabel(GateBar1_comLabel);
    initComPortIDLabel(GateBar2_comLabel);
    initComPortIDLabel(GateBar3_comLabel);
    initComPortIDLabel(GateBar4_comLabel);

    E_Board1_comID_CBox = new JComboBox();
    E_Board2_comID_CBox = new JComboBox();
    E_Board3_comID_CBox = new JComboBox();
    E_Board4_comID_CBox = new JComboBox();
    GateBar1_comID_CBox = new JComboBox();
    GateBar2_comID_CBox = new JComboBox();
    GateBar3_comID_CBox = new JComboBox();
    GateBar4_comID_CBox = new JComboBox();

    E_Board1_comID_CBox.setName("E_Board1_comID_CBox");
    E_Board2_comID_CBox.setName("E_Board2_comID_CBox");
    E_Board3_comID_CBox.setName("E_Board3_comID_CBox");
    E_Board4_comID_CBox.setName("E_Board4_comID_CBox");
    GateBar1_comID_CBox.setName("GateBar1_comID_CBox");
    GateBar2_comID_CBox.setName("GateBar2_comID_CBox");
    GateBar3_comID_CBox.setName("GateBar3_comID_CBox");
    GateBar4_comID_CBox.setName("GateBar4_comID_CBox");

    augmentComponentMap(E_Board1_comID_CBox, componentMap);
    augmentComponentMap(E_Board2_comID_CBox, componentMap);
    augmentComponentMap(E_Board3_comID_CBox, componentMap);
    augmentComponentMap(E_Board4_comID_CBox, componentMap);
    augmentComponentMap(GateBar1_comID_CBox, componentMap);
    augmentComponentMap(GateBar2_comID_CBox, componentMap);
    augmentComponentMap(GateBar3_comID_CBox, componentMap);
    augmentComponentMap(GateBar4_comID_CBox, componentMap);

    //<editor-fold desc="-- Initialize other properties of COM ID combobox">
    for (int gate = 1; gate <= gateCount; gate++) {
        for (final DeviceType devType : DeviceType.values()) {
            String name = devType.name() + gate + "_comID_CBox";
            final JComboBox comIDcBox = ((JComboBox) getComponentByName(name));

            if (comIDcBox != null) {
                comIDcBox.setFont(new java.awt.Font(font_Type, font_Style, font_Size));
                comIDcBox.setModel(new javax.swing.DefaultComboBoxModel(
                        new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }));
                comIDcBox.setMinimumSize(new java.awt.Dimension(50, CBOX_HEIGHT));
                comIDcBox.setPreferredSize(new java.awt.Dimension(50, CBOX_HEIGHT));
                final int gateNo = gate;

                comIDcBox.addItemListener(new java.awt.event.ItemListener() {
                    public void itemStateChanged(java.awt.event.ItemEvent evt) {
                        if (evt.getStateChange() == ItemEvent.SELECTED) {
                            String COM_ID = (String) comIDcBox.getSelectedItem();
                            if (COM_ID.equals(deviceComID[devType.ordinal()][gateNo])) {
                                changedControls.remove(comIDcBox);
                            } else {
                                changedControls.add(comIDcBox);
                            }//from   ww w  .  j  av  a  2s  .co m
                        }
                    }
                });
            }
        }
    }
    //</editor-fold>
}

From source file:com.cch.aj.entryrecorder.frame.MainJFrame.java

private int FillEntryComboBox(JComboBox comboBox, int id) {
    int result = -1;
    List<Entry> allEntrys = this.entryService.GetAllEntities();
    if (allEntrys.size() > 0) {
        List<Entry> entrys = allEntrys.stream().filter(x -> x.getInUse().equals("YES"))
                .collect(Collectors.toList());
        if (entrys.size() > 0) {
            List<ComboBoxItem<Entry>> entryNames = entrys.stream().sorted(comparing(x -> x.getCreateDate()))
                    .map(x -> ComboBoxItemConvertor.ConvertToComboBoxItem(x,
                            (x.getMachineId() != null ? x.getMachineId().getMachineNo() : "") + "/"
                                    + (x.getProductId() != null ? x.getProductId().getCode() : ""),
                            x.getId()))//w  w w. ja  v  a  2s . c om
                    .collect(Collectors.toList());
            Entry entry = new Entry();
            entry.setId(0);
            entry.setShift("- Select -");
            entryNames.add(0, new ComboBoxItem<Entry>(entry, entry.getShift(), entry.getId()));
            ComboBoxItem[] entryNamesArray = entryNames.toArray(new ComboBoxItem[entryNames.size()]);
            comboBox.setModel(new DefaultComboBoxModel(entryNamesArray));
            if (id != 0) {
                ComboBoxItem<Entry> currentEntryName = entryNames.stream().filter(x -> x.getId() == id)
                        .findFirst().get();
                result = entryNames.indexOf(currentEntryName);
                this.currentEntry = ((ComboBoxItem<Entry>) comboBox.getSelectedItem()).getItem();
            } else {
                result = 0;
            }
            comboBox.setSelectedIndex(result);

        }
    }
    return result;
}

From source file:de.whiledo.iliasdownloader2.swing.service.MainController.java

protected void chooseServer() {
    final TwoObjectsX<String, String> serverAndClientId = new TwoObjectsX<String, String>(
            iliasProperties.getIliasServerURL(), iliasProperties.getIliasClient());
    final boolean noConfigDoneYet = serverAndClientId.getObjectA() == null
            || serverAndClientId.getObjectA().trim().isEmpty();

    final JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());

    final JLabel labelServer = new JLabel("Server: " + serverAndClientId.getObjectA());
    final JLabel labelClientId = new JLabel("Client Id: " + serverAndClientId.getObjectB());

    JComboBox<LoginType> comboboxLoginType = null;
    JComboBox<DownloadMethod> comboboxDownloadMethod = null;

    final Runnable findOutClientId = new Runnable() {

        @Override/*  w w  w .java2  s  . c  om*/
        public void run() {
            try {
                String s = IliasUtil.findClientByLoginPageOrWebserviceURL(serverAndClientId.getObjectA());
                serverAndClientId.setObjectB(s);
                labelClientId.setText("Client Id: " + s);
            } catch (Exception e1) {
                showError("Client Id konnte nicht ermittelt werden", e1);
            }
        }
    };

    final Runnable promptInputServer = new Runnable() {

        @Override
        public void run() {

            String s = JOptionPane.showInputDialog(panel,
                    "Geben Sie die Ilias Loginseitenadresse oder Webserviceadresse ein",
                    serverAndClientId.getObjectA());
            if (s != null) {
                try {
                    s = IliasUtil.findSOAPWebserviceByLoginPage(s.trim());

                    if (!s.toLowerCase().startsWith("https://")) {
                        JOptionPane.showMessageDialog(mainFrame,
                                "Achtung! Die von Ihnen angegebene Adresse beginnt nicht mit 'https://'.\nDie Verbindung ist daher nicht ausreichend gesichert. Ein Angreifer knnte Ihre Ilias Daten und Ihr Passwort abgreifen",
                                "Achtung, nicht geschtzt", JOptionPane.WARNING_MESSAGE);
                    }

                    serverAndClientId.setObjectA(s);
                    labelServer.setText("Server: " + serverAndClientId.getObjectA());

                    if (noConfigDoneYet) {
                        findOutClientId.run();
                    }
                } catch (IliasException e1) {
                    showError(
                            "Bitte geben Sie die Adresse der Ilias Loginseite oder die des Webservice an. Die Adresse der Loginseite muss 'login.php' enthalten",
                            e1);
                }
            }
        }
    };

    {
        JPanel panel2 = new JPanel(new BorderLayout());

        panel2.add(labelServer, BorderLayout.NORTH);
        panel2.add(labelClientId, BorderLayout.SOUTH);

        panel.add(panel2, BorderLayout.NORTH);
    }
    {
        JPanel panel2 = new JPanel(new BorderLayout());

        JPanel panel3 = new JPanel(new GridLayout());
        {
            JButton b = new JButton("Server ndern");
            b.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    promptInputServer.run();
                }
            });
            panel3.add(b);

            b = new JButton("Client Id ndern");
            b.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    String s = JOptionPane.showInputDialog(panel, "Client Id eingeben",
                            serverAndClientId.getObjectB());
                    if (s != null) {
                        serverAndClientId.setObjectB(s);
                        labelClientId.setText("Client Id: " + serverAndClientId.getObjectB());
                    }

                }
            });
            panel3.add(b);

            b = new JButton("Client Id automatisch ermitteln");
            b.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    findOutClientId.run();
                }
            });
            panel3.add(b);
        }
        panel2.add(panel3, BorderLayout.NORTH);

        panel3 = new JPanel(new GridLayout(0, 2, 5, 2));
        {
            panel3.add(new JLabel("Loginmethode: "));
            comboboxLoginType = new JComboBox<LoginType>();
            FunctionsX.setComboBoxLayoutString(comboboxLoginType, new ObjectDoInterface<LoginType, String>() {

                @Override
                public String doSomething(LoginType loginType) {
                    switch (loginType) {
                    case DEFAULT:
                        return "Standard";
                    case LDAP:
                        return "LDAP";
                    case CAS:
                        return "CAS";
                    default:
                        return "<Fehler>";
                    }
                }

            });
            val model = ((DefaultComboBoxModel<LoginType>) comboboxLoginType.getModel());
            for (LoginType loginType : LoginType.values()) {
                model.addElement(loginType);
            }
            model.setSelectedItem(iliasProperties.getLoginType());
            panel3.add(comboboxLoginType);

            JLabel label = new JLabel("Dateien herunterladen ber:");
            label.setToolTipText("Die restliche Kommunikation luft immer ber den SOAP Webservice");
            panel3.add(label);
            comboboxDownloadMethod = new JComboBox<DownloadMethod>();
            FunctionsX.setComboBoxLayoutString(comboboxDownloadMethod,
                    new ObjectDoInterface<DownloadMethod, String>() {

                        @Override
                        public String doSomething(DownloadMethod downloadMethod) {
                            switch (downloadMethod) {
                            case WEBSERVICE:
                                return "SOAP Webservice (Standard)";
                            case WEBDAV:
                                return "WEBDAV";
                            default:
                                return "<Fehler>";
                            }
                        }

                    });
            val model2 = ((DefaultComboBoxModel<DownloadMethod>) comboboxDownloadMethod.getModel());
            for (DownloadMethod downloadMethod : DownloadMethod.values()) {
                model2.addElement(downloadMethod);
            }
            model2.setSelectedItem(iliasProperties.getDownloadMethod());
            panel3.add(comboboxDownloadMethod);
        }
        panel2.add(panel3, BorderLayout.WEST);

        panel.add(panel2, BorderLayout.SOUTH);
    }

    if (noConfigDoneYet) {
        promptInputServer.run();
    }

    if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(mainFrame, panel, "Server konfigurieren",
            JOptionPane.OK_CANCEL_OPTION)) {
        if (syncService != null) {
            syncService.logoutIfLoggedIn();
        }
        iliasProperties.setIliasServerURL(serverAndClientId.getObjectA());
        iliasProperties.setIliasClient(serverAndClientId.getObjectB());
        iliasProperties.setLoginType((LoginType) comboboxLoginType.getSelectedItem());
        iliasProperties.setDownloadMethod((DownloadMethod) comboboxDownloadMethod.getSelectedItem());
        saveProperties(iliasProperties);
        updateTitleCaption();
    }

}

From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java

public RecursoDialog(final Recurso rec, final AdminResources adminResources) {
    super();/*from  www  .j  av a  2 s.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:App.java

/**
 * Initialize the contents of the frame.
 *///from   w  w  w.j ava  2 s  . c  om
private void initialize() {

    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1000, 750);
    frame.getContentPane().setLayout(null);

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "png");
    fc = new JFileChooser();
    fc.setFileFilter(filter);
    frame.getContentPane().add(fc);

    stepOne = new JLabel("");
    stepOne.setToolTipText("here comes something");
    stepOne.setIcon(new ImageIcon("img/stepOne.png"));
    stepOne.setBounds(266, -4, 67, 49);
    frame.getContentPane().add(stepOne);

    btnBrowse = new JButton("Browse");
    btnBrowse.setBounds(66, 6, 117, 29);
    frame.getContentPane().add(btnBrowse);

    btnTurnWebcamOn = new JButton("Take a picture with webcam");
    btnTurnWebcamOn.setBounds(66, 34, 212, 29);
    frame.getContentPane().add(btnTurnWebcamOn);

    JButton btnTakePictureWithWebcam = new JButton("Take a picture");
    btnTakePictureWithWebcam.setBounds(430, 324, 117, 29);
    frame.getContentPane().add(btnTakePictureWithWebcam);
    btnTakePictureWithWebcam.setVisible(false);

    JButton btnCancel = new JButton("Cancel");
    btnCancel.setBounds(542, 324, 117, 29);
    frame.getContentPane().add(btnCancel);
    btnCancel.setVisible(false);

    JButton btnSaveImage = new JButton("Save image");
    btnSaveImage.setBounds(497, 357, 117, 29);
    frame.getContentPane().add(btnSaveImage);
    btnSaveImage.setVisible(false);

    urlField = new JTextField();
    urlField.setBounds(66, 67, 220, 26);
    frame.getContentPane().add(urlField);
    urlField.setColumns(10);

    originalImageLabel = new JLabel();
    originalImageLabel.setHorizontalAlignment(SwingConstants.CENTER);
    originalImageLabel.setBounds(33, 98, 300, 300);
    frame.getContentPane().add(originalImageLabel);

    stepTwo = new JLabel("");
    stepTwo.setToolTipText("here comes something else");
    stepTwo.setIcon(new ImageIcon("img/stepTwo.png"));
    stepTwo.setBounds(266, 413, 67, 49);
    frame.getContentPane().add(stepTwo);

    btnAnalyse = new JButton("Analyse image");
    btnAnalyse.setBounds(68, 423, 196, 29);
    frame.getContentPane().add(btnAnalyse);

    tagsField = new JTextArea();
    tagsField.setBounds(23, 479, 102, 89);
    tagsField.setLineWrap(true);
    tagsField.setWrapStyleWord(true);
    frame.getContentPane().add(tagsField);
    tagsField.setColumns(10);

    lblTags = new JLabel("Tags:");
    lblTags.setBounds(46, 451, 61, 16);
    frame.getContentPane().add(lblTags);

    descriptionField = new JTextArea();
    descriptionField.setLineWrap(true);
    descriptionField.setWrapStyleWord(true);
    descriptionField.setBounds(137, 479, 187, 89);
    frame.getContentPane().add(descriptionField);
    descriptionField.setColumns(10);

    lblDescription = new JLabel("Description:");
    lblDescription.setBounds(163, 451, 77, 16);
    frame.getContentPane().add(lblDescription);

    stepThree = new JLabel("");
    stepThree.setToolTipText("here comes something different");
    stepThree.setIcon(new ImageIcon("img/stepThree.png"));
    stepThree.setBounds(266, 685, 67, 49);
    frame.getContentPane().add(stepThree);

    JLabel lblImageType = new JLabel("Image type");
    lblImageType.setBounds(23, 580, 102, 16);
    frame.getContentPane().add(lblImageType);

    String[] imageTypes = { "unspecified", "AnimategGif", "Clipart", "Line", "Photo" };
    JComboBox imageTypeBox = new JComboBox(imageTypes);
    imageTypeBox.setBounds(137, 580, 187, 23);
    frame.getContentPane().add(imageTypeBox);

    JLabel lblSizeType = new JLabel("Size");
    lblSizeType.setBounds(23, 608, 102, 16);
    frame.getContentPane().add(lblSizeType);

    String[] sizeTypes = { "unspecified", "Small", "Medium", "Large", "Wallpaper" };
    JComboBox sizeBox = new JComboBox(sizeTypes);
    sizeBox.setBounds(137, 608, 187, 23);
    frame.getContentPane().add(sizeBox);

    JLabel lblLicenseType = new JLabel("License");
    lblLicenseType.setBounds(23, 636, 102, 16);
    frame.getContentPane().add(lblLicenseType);

    String[] licenseTypes = { "unspecified", "Public", "Share", "ShareCommercially", "Modify" };
    JComboBox licenseBox = new JComboBox(licenseTypes);
    licenseBox.setBounds(137, 636, 187, 23);
    frame.getContentPane().add(licenseBox);

    JLabel lblSafeSearchType = new JLabel("Safe search");
    lblSafeSearchType.setBounds(23, 664, 102, 16);
    frame.getContentPane().add(lblSafeSearchType);

    String[] safeSearchTypes = { "Strict", "Moderate", "Off" };
    JComboBox safeSearchBox = new JComboBox(safeSearchTypes);
    safeSearchBox.setBounds(137, 664, 187, 23);
    frame.getContentPane().add(safeSearchBox);

    btnSearchForSimilar = new JButton("Search for similar images");
    btnSearchForSimilar.setVisible(true);
    btnSearchForSimilar.setBounds(66, 695, 189, 29);
    frame.getContentPane().add(btnSearchForSimilar);

    // label to try urls to display images, not shown on the main frame
    labelTryLinks = new JLabel();
    labelTryLinks.setBounds(0, 0, 100, 100);

    foundImagesLabel1 = new JLabel();
    foundImagesLabel1.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel1.setBounds(400, 49, 250, 250);
    frame.getContentPane().add(foundImagesLabel1);

    foundImagesLabel2 = new JLabel();
    foundImagesLabel2.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel2.setBounds(400, 313, 250, 250);
    frame.getContentPane().add(foundImagesLabel2);

    foundImagesLabel3 = new JLabel();
    foundImagesLabel3.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel3.setBounds(673, 49, 250, 250);
    frame.getContentPane().add(foundImagesLabel3);

    foundImagesLabel4 = new JLabel();
    foundImagesLabel4.setHorizontalAlignment(SwingConstants.CENTER);
    foundImagesLabel4.setBounds(673, 313, 250, 250);
    frame.getContentPane().add(foundImagesLabel4);

    progressBar = new JProgressBar();
    progressBar.setIndeterminate(true);
    progressBar.setStringPainted(true);
    progressBar.setBounds(440, 602, 440, 29);

    Border border = BorderFactory
            .createTitledBorder("We are checking every image, pixel by pixel, it may take a while...");
    progressBar.setBorder(border);
    frame.getContentPane().add(progressBar);
    progressBar.setVisible(false);

    btnHelp = new JButton("");
    btnHelp.setBorderPainted(false);
    ImageIcon btnIcon = new ImageIcon("img/helpRed.png");
    btnHelp.setIcon(btnIcon);
    btnHelp.setBounds(917, 4, 77, 59);
    frame.getContentPane().add(btnHelp);

    // all action listeners
    btnBrowse.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
                openFilechooser();
            }
        }
    });

    btnTurnWebcamOn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            setAllFoundImagesLabelsAndPreviewsToNull();
            btnTakePictureWithWebcam.setVisible(true);
            btnCancel.setVisible(true);
            turnCameraOn();
        }
    });

    btnTakePictureWithWebcam.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            btnSaveImage.setVisible(true);
            // take a photo with web camera
            imageWebcam = webcam.getImage();
            originalImage = imageWebcam;

            // to mirror the image we create a temporary file, flip it
            // horizontally and then delete

            // get user's name to store file in the user directory
            String user = System.getProperty("user.home");
            String fileName = user + "/webCamPhoto.jpg";
            File newFile = new File(fileName);

            try {
                ImageIO.write(originalImage, "jpg", newFile);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                originalImage = (BufferedImage) ImageIO.read(newFile);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            newFile.delete();
            originalImage = mirrorImage(originalImage);
            icon = scaleBufferedImage(originalImage, originalImageLabel);
            originalImageLabel.setIcon(icon);
        }
    });

    btnSaveImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                try {

                    file = fc.getSelectedFile();
                    File output = new File(file.toString());
                    // check if image already exists
                    if (output.exists()) {
                        int response = JOptionPane.showConfirmDialog(null, //
                                "Do you want to replace the existing file?", //
                                "Confirm", JOptionPane.YES_NO_OPTION, //
                                JOptionPane.QUESTION_MESSAGE);
                        if (response != JOptionPane.YES_OPTION) {
                            return;
                        }
                    }
                    ImageIO.write(toBufferedImage(originalImage), "jpg", output);
                    System.out.println("Your image has been saved in the folder " + file.getPath());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });

    btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            btnTakePictureWithWebcam.setVisible(false);
            btnCancel.setVisible(false);
            btnSaveImage.setVisible(false);
            webcam.close();
            panel.setVisible(false);
        }
    });

    urlField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (urlField.getText().length() > 0) {
                String linkNew = urlField.getText();
                getImageFromHttp(linkNew, originalImageLabel);
                originalImage = imageResponses;
            }
        }
    });

    btnAnalyse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            Token computerVisionToken = new Token();
            String computerVisionTokenFileName = "APIToken.txt";

            try {
                computerVisionImageToken = computerVisionToken.getApiToken(computerVisionTokenFileName);
                try {
                    analyse();
                } catch (NullPointerException e1) {
                    // if user clicks on "analyze" button without uploading
                    // image or posts a broken link
                    JOptionPane.showMessageDialog(null, "Please choose an image");
                    e1.printStackTrace();
                }
            } catch (NullPointerException e1) {
                e1.printStackTrace();
            }
        }
    });

    btnSearchForSimilar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            // clear labels in case there were results of previous search
            setAllFoundImagesLabelsAndPreviewsToNull();

            System.out.println("==========================================");
            System.out.println("new search");
            System.out.println("==========================================");

            Token bingImageToken = new Token();
            String bingImageTokenFileName = "SearchApiToken.txt";

            bingToken = bingImageToken.getApiToken(bingImageTokenFileName);

            // in case user edited description or tags, update it and
            // replace new line character, spaces and breaks with %20
            text = descriptionField.getText().replace(" ", "%20").replace("\r", "%20").replace("\n", "%20");
            String tagsString = tagsField.getText().replace(" ", "%20").replace("\r", "%20").replace("\n",
                    "%20");

            imageTypeString = imageTypeBox.getSelectedItem().toString();
            sizeTypeString = sizeBox.getSelectedItem().toString();
            licenseTypeString = licenseBox.getSelectedItem().toString();
            safeSearchTypeString = safeSearchBox.getSelectedItem().toString();

            searchParameters = tagsString + text;
            System.out.println("search parameters: " + searchParameters);

            if (searchParameters.length() != 0) {

                // add new thread for searching, so that progress bar and
                // searching could run simultaneously
                Thread t1 = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        progressBar.setVisible(true);
                        searchForSimilarImages(searchParameters, imageTypeString, sizeTypeString,
                                licenseTypeString, safeSearchTypeString);
                    }

                });
                // start searching for similar images in a separate thread
                t1.start();
            } else {
                JOptionPane.showMessageDialog(null,
                        "Please choose first an image to analyse or insert search parameters");
            }
        }
    });

    foundImagesLabel1.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel1.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(firstImageUrl);
                }
            }
        }
    });

    foundImagesLabel2.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel2.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(secondImageUrl);
                }
            }
        }
    });

    foundImagesLabel3.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel3.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(thirdImageUrl);
                }
            }
        }
    });

    foundImagesLabel4.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (foundImagesLabel4.getIcon() != null) {
                if (fc.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
                    saveFileChooser(fourthImageUrl);
                }
            }
        }
    });

    btnHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // TODO write help
            HelpFrame help = new HelpFrame();
        }
    });
}

From source file:userinterface.properties.GUIGraphHandler.java

public void plotNewFunction() {

    JDialog dialog;//w  w w.  j  a v a 2 s .c  o m
    JRadioButton radio2d, radio3d, newGraph, existingGraph;
    JTextField functionField, seriesName;
    JButton ok, cancel;
    JComboBox<String> chartOptions;
    JLabel example;

    //init all the fields of the dialog
    dialog = new JDialog(GUIPrism.getGUI());
    radio2d = new JRadioButton("2D");
    radio3d = new JRadioButton("3D");
    newGraph = new JRadioButton("New Graph");
    existingGraph = new JRadioButton("Exisiting");
    chartOptions = new JComboBox<String>();
    functionField = new JTextField();
    ok = new JButton("Plot");
    cancel = new JButton("Cancel");
    seriesName = new JTextField();
    example = new JLabel("<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
    example.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseEntered(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.HAND_CURSOR));
            example.setForeground(Color.BLUE);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            example.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            example.setForeground(Color.BLACK);
        }

        @Override
        public void mouseClicked(MouseEvent e) {

            if (e.getButton() == MouseEvent.BUTTON1) {

                if (radio2d.isSelected()) {
                    functionField.setText("x/2 + 5");
                } else {
                    functionField.setText("x+y+5");
                }

                functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
                functionField.setForeground(Color.BLACK);

            }
        }

    });

    //set dialog properties
    dialog.setSize(400, 350);
    dialog.setTitle("Plot a new function");
    dialog.setModal(true);
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setLocationRelativeTo(GUIPrism.getGUI());

    //add every component to their dedicated panels
    JPanel graphTypePanel = new JPanel(new FlowLayout());
    graphTypePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function type"));
    graphTypePanel.add(radio2d);
    graphTypePanel.add(radio3d);

    JPanel functionFieldPanel = new JPanel(new BorderLayout());
    functionFieldPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function"));
    functionFieldPanel.add(functionField, BorderLayout.CENTER);
    functionFieldPanel.add(example, BorderLayout.SOUTH);

    JPanel chartSelectPanel = new JPanel();
    chartSelectPanel.setLayout(new BoxLayout(chartSelectPanel, BoxLayout.Y_AXIS));
    chartSelectPanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Plot function to"));
    JPanel radioPlotPanel = new JPanel(new FlowLayout());
    radioPlotPanel.add(newGraph);
    radioPlotPanel.add(existingGraph);
    JPanel chartOptionsPanel = new JPanel(new FlowLayout());
    chartOptionsPanel.add(chartOptions);
    chartSelectPanel.add(radioPlotPanel);
    chartSelectPanel.add(chartOptionsPanel);

    JPanel bottomControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomControlPanel.add(ok);
    bottomControlPanel.add(cancel);

    JPanel seriesNamePanel = new JPanel(new BorderLayout());
    seriesNamePanel.setBorder(BorderFactory
            .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Series name"));
    seriesNamePanel.add(seriesName, BorderLayout.CENTER);

    // add all the panels to the dialog

    dialog.add(graphTypePanel);
    dialog.add(functionFieldPanel);
    dialog.add(chartSelectPanel);
    dialog.add(seriesNamePanel);
    dialog.add(bottomControlPanel);

    // do all the enables and set properties

    radio2d.setSelected(true);
    newGraph.setSelected(true);
    chartOptions.setEnabled(false);
    functionField.setText("Add function expression here....");
    functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
    functionField.setForeground(Color.GRAY);
    seriesName.setText("New function");
    ok.setMnemonic('P');
    cancel.setMnemonic('C');
    example.setToolTipText("click to try out");

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    boolean found = false;

    for (int i = 0; i < theTabs.getTabCount(); i++) {

        if (theTabs.getComponentAt(i) instanceof Graph) {
            chartOptions.addItem(getGraphName(i));
            found = true;
        }
    }

    if (!found) {

        existingGraph.setEnabled(false);
        chartOptions.setEnabled(false);
    }

    //add all the action listeners

    radio2d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio2d.isSelected()) {

                radio3d.setSelected(false);

                if (chartOptions.getItemCount() > 0) {
                    existingGraph.setEnabled(true);
                    chartOptions.setEnabled(true);
                }

                example.setText(
                        "<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>");
            }
        }
    });

    radio3d.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (radio3d.isSelected()) {

                radio2d.setSelected(false);
                newGraph.setSelected(true);
                existingGraph.setEnabled(false);
                chartOptions.setEnabled(false);
                example.setText("<html><font size=3 color=red>Example:</font><font size=3>x+y+5</font></html>");

            }

        }
    });

    newGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (newGraph.isSelected()) {
                existingGraph.setSelected(false);
                chartOptions.setEnabled(false);
            }
        }
    });

    existingGraph.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (existingGraph.isSelected()) {

                newGraph.setSelected(false);
                chartOptions.setEnabled(true);
            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String function = functionField.getText();

            Expression expr = null;

            try {

                expr = GUIPrism.getGUI().getPrism().parseSingleExpressionString(function);
                expr = (Expression) expr.accept(new ASTTraverseModify() {

                    @Override
                    public Object visit(ExpressionIdent e) throws PrismLangException {
                        return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                    }

                });

                expr.typeCheck();
                expr.semanticCheck();

            } catch (PrismLangException e1) {

                // for copying style
                JLabel label = new JLabel();

                // html content in our case the error we want to show
                JEditorPane ep = new JEditorPane("text/html",
                        "<html> There was an error parsing the function. To read about what built-in"
                                + " functions are supported <br>and some more information on the functions, visit "
                                + "<a href='http://www.prismmodelchecker.org/manual/ThePRISMLanguage/Expressions'>Prism expressions site</a>."
                                + "<br><br><font color=red>Error: </font>" + e1.getMessage() + " </html>");

                // handle link events
                ep.addHyperlinkListener(new HyperlinkListener() {
                    @Override
                    public void hyperlinkUpdate(HyperlinkEvent e) {
                        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                            try {
                                Desktop.getDesktop().browse(e.getURL().toURI());
                            } catch (IOException | URISyntaxException e1) {

                                e1.printStackTrace();
                            }
                        }
                    }
                });
                ep.setEditable(false);
                ep.setBackground(label.getBackground());

                // show the error dialog
                JOptionPane.showMessageDialog(dialog, ep, "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (radio2d.isSelected()) {

                ParametricGraph graph = null;

                if (newGraph.isSelected()) {

                    graph = new ParametricGraph("");
                } else {

                    for (int i = 0; i < theTabs.getComponentCount(); i++) {

                        if (theTabs.getTitleAt(i).equals(chartOptions.getSelectedItem())) {

                            graph = (ParametricGraph) theTabs.getComponent(i);
                        }
                    }

                }

                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), newGraph.isSelected(), true);

            } else if (radio3d.isSelected()) {

                try {

                    expr = (Expression) expr.accept(new ASTTraverseModify() {
                        @Override
                        public Object visit(ExpressionIdent e) throws PrismLangException {
                            return new ExpressionConstant(e.getName(), TypeDouble.getInstance());
                        }

                    });

                    expr.semanticCheck();
                    expr.typeCheck();

                } catch (PrismLangException e1) {
                    e1.printStackTrace();
                }

                if (expr.getAllConstants().size() < 2) {

                    JOptionPane.showMessageDialog(dialog,
                            "There are not enough variables in the function to plot a 3D chart!", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // its always a new graph
                ParametricGraph3D graph = new ParametricGraph3D(expr);
                dialog.dispose();
                defineConstantsAndPlot(expr, graph, seriesName.getText(), true, false);
            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    // we will show info about the function when field is out of focus
    functionField.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {

            if (!functionField.getText().equals("")) {
                return;
            }

            functionField.setText("Add function expression here....");
            functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15));
            functionField.setForeground(Color.GRAY);
        }

        @Override
        public void focusGained(FocusEvent e) {

            if (!functionField.getText().equals("Add function expression here....")) {
                return;
            }

            functionField.setForeground(Color.BLACK);
            functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
            functionField.setText("");
        }
    });

    // show the dialog
    dialog.setVisible(true);
}