Example usage for javax.swing JComboBox getSelectedIndex

List of usage examples for javax.swing JComboBox getSelectedIndex

Introduction

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

Prototype

@Transient
public int getSelectedIndex() 

Source Link

Document

Returns the first item in the list that matches the given item.

Usage

From source file:edu.ku.brc.specify.datamodel.busrules.AgentBusRules.java

/**
 * Clears the values and hides somAttachmentOwnere UI depending on what type is selected
 * @param cbx the type cbx/*from   w  w  w .  ja  v a 2 s  .  c o  m*/
 */
protected void fixUpTypeCBX(final JComboBox<?> cbx) {
    if (formViewObj != null) {
        Agent agent = (Agent) formViewObj.getDataObj();
        if (agent != null) {
            final Component addrSubView = formViewObj.getCompById("9");

            boolean isVisible = addrSubView.isVisible();

            byte agentType = (byte) cbx.getSelectedIndex();
            if (agentType != Agent.PERSON) {
                agent.setMiddleInitial(null);
                agent.setFirstName(null);
                agent.setTitle(null);

                boolean enable = agentType == Agent.ORG;
                addrSubView.setVisible(enable);

            } else {
                if (!isVisible) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            Component topComp = UIHelper.getWindow(addrSubView);
                            Component topMost = UIRegistry.getTopWindow();
                            if (topComp != topMost && topComp != null) {
                                ((Window) topComp).pack();
                            }
                        }
                    });
                }
                addrSubView.setVisible(true);
            }
            agent.setAgentType(agentType);
            fixUpFormForAgentType(agent, true);
        }
    }
}

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

/**
 * Event handler for device dropdown list selection
 * //from   ww  w.  ja v a  2  s .c o m
 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox) e.getSource();
    int pos = cb.getSelectedIndex();
    // when device is selected, attempt to connect
    if (servers != null && pos > 0) {
        selectedDialServer = (DialServer) cb.getSelectedItem();
    }
}

From source file:main.UIController.java

/******** FROM GREGORIAN **********/

public void updateDayComboGregorian() {
    UI window = this.getUi();

    JTextField year = window.getYear();
    JComboBox month = window.getMonth();
    JComboBox day = window.getDay();
    JButton convert = window.getToImladris();
    JTextPane result = window.getResImladris();
    String value = year.getText();
    if (!value.isEmpty()) {
        try {/* www . j a va 2 s.  co  m*/
            int yearNum = Integer.parseInt(value);
            if (yearNum > 0 && yearNum <= GregorianInfo.MAX_SUPPORTED_YEAR) {
                int monthNum = month.getSelectedIndex() + 1;
                int daySel = 0;
                if (day.isEnabled()) {
                    daySel = day.getSelectedIndex() + 1;
                }
                ArrayList<Integer> days = GregorianInfo.getInstance().getDaysArray(yearNum, monthNum);
                day.setModel(new DefaultComboBoxModel(days.toArray()));
                if (daySel > 0 && daySel <= days.size()) {
                    day.setSelectedIndex(daySel - 1);
                }
                day.setEnabled(true);
                convert.setEnabled(true);
                result.setText("");
            } else {
                day.setEnabled(false);
                convert.setEnabled(false);
                day.setModel(new DefaultComboBoxModel());
                result.setText("");
            }
        } catch (NumberFormatException e) {
            day.setEnabled(false);
            convert.setEnabled(false);
            day.setModel(new DefaultComboBoxModel());
            result.setText("");
        }
    } else {
        day.setEnabled(false);
        convert.setEnabled(false);
        day.setModel(new DefaultComboBoxModel());
        result.setText("");
    }
}

From source file:edu.ku.brc.specify.plugins.PartialDateUI.java

/**
 * Creates the UI.//  w  ww  .  j ava  2s .  c o m
 */
protected void createUI() {
    DocumentAdaptor docListener = null;
    if (!isDisplayOnly) {
        docListener = new DocumentAdaptor() {
            @Override
            protected void changed(DocumentEvent e) {
                super.changed(e);

                if (!ignoreDocChanges) {
                    isChanged = true;
                    isDateChanged = true;
                    if (changeListener != null) {
                        changeListener.stateChanged(new ChangeEvent(PartialDateUI.this));
                    }
                }
            }
        };
    }

    List<UIFieldFormatterIFace> partialDateList = UIFieldFormatterMgr.getInstance().getDateFormatterList(true);
    for (UIFieldFormatterIFace uiff : partialDateList) {
        if (uiff.getName().equals("PartialDateMonth")) {
            ValFormattedTextField tf = new ValFormattedTextField(uiff, isDisplayOnly, !isDisplayOnly);
            tf.setRequired(isRequired);

            if (docListener != null)
                tf.addDocumentListener(docListener);
            uivs[1] = tf;
            textFields[1] = tf.getTextField();
            if (isDisplayOnly) {
                ViewFactory.changeTextFieldUIForDisplay(textFields[1], false);
            } else {
                setupPopupMenu(tf);
            }

        } else if (uiff.getName().equals("PartialDateYear")) {
            ValFormattedTextField tf = new ValFormattedTextField(uiff, isDisplayOnly, !isDisplayOnly);
            tf.setRequired(isRequired);

            if (docListener != null)
                tf.addDocumentListener(docListener);
            uivs[2] = tf;
            textFields[2] = tf.getTextField();
            if (isDisplayOnly) {
                ViewFactory.changeTextFieldUIForDisplay(textFields[2], false);
            } else {
                setupPopupMenu(tf);
            }
        }
    }

    List<UIFieldFormatterIFace> dateList = UIFieldFormatterMgr.getInstance().getDateFormatterList(false);
    for (UIFieldFormatterIFace uiff : dateList) {
        if (uiff.getName().equals("Date")) {
            ValFormattedTextFieldSingle tf = new ValFormattedTextFieldSingle(uiff, isDisplayOnly, false);
            tf.setRequired(isRequired);

            if (docListener != null)
                tf.addDocumentListener(docListener);
            uivs[0] = tf;
            textFields[0] = tf;
            if (isDisplayOnly) {
                ViewFactory.changeTextFieldUIForDisplay(textFields[0], false);
            } else {
                ViewFactory.addTextFieldPopup(this, tf, true);
            }
        }
    }

    cardPanel = new JPanel(cardLayout);

    String[] formatKeys = { "PARTIAL_DATE_FULL", "PARTIAL_DATE_MONTH", "PARTIAL_DATE_YEAR" };
    String[] labels = new String[formatKeys.length];
    for (int i = 0; i < formatKeys.length; i++) {
        labels[i] = UIRegistry.getResourceString(formatKeys[i]);
        cardPanel.add(labels[i], (JComponent) uivs[i]);
    }

    formatSelector = createComboBox(labels);
    formatSelector.setSelectedIndex(0);

    JComponent typDisplayComp = null;
    if (!isDisplayOnly) {
        comboBoxAL = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JComboBox cbx = (JComboBox) ae.getSource();
                Object dataValue = ((GetSetValueIFace) currentUIV).getValue();//isDateChanged ? ((GetSetValueIFace)currentUIV).getValue() : Calendar.getInstance();
                currentUIV = uivs[cbx.getSelectedIndex()];

                ignoreDocChanges = true;
                ((GetSetValueIFace) currentUIV).setValue(dataValue, null);
                ignoreDocChanges = false;

                cardLayout.show(cardPanel, formatSelector.getSelectedItem().toString());

                isChanged = true;
                if (changeListener != null) {
                    changeListener.stateChanged(new ChangeEvent(PartialDateUI.this));
                }
            }
        };
        typDisplayComp = formatSelector;
        formatSelector.addActionListener(comboBoxAL);
    }

    PanelBuilder builder = new PanelBuilder(
            new FormLayout((typDisplayComp != null ? "p, 2px, f:p:g" : "f:p:g"), "p"), this);
    CellConstraints cc = new CellConstraints();
    if (typDisplayComp != null) {
        builder.add(typDisplayComp, cc.xy(1, 1));
        builder.add(cardPanel, cc.xy(3, 1));
    } else {
        builder.add(cardPanel, cc.xy(1, 1));
    }
}

From source file:main.UIController.java

@SuppressWarnings("deprecation")
public void convertToImladris() {
    UI window = this.getUi();

    String errorEmptyYear = "Please insert a year.";
    String errorYearNotNumeric = "Please insert the year as a numeric value.";
    String errorYearNotValid = "Please insert a valid year (from 1 to "
            + Integer.toString(GregorianInfo.MAX_SUPPORTED_YEAR) + ").";
    String errorDayNotRead = "Sorry, the day could not be read.";

    JTextField year = window.getYear();
    JComboBox month = window.getMonth();
    JComboBox day = window.getDay();
    JCheckBox afterSunset = window.getAfterSunset();
    JTextPane result = window.getResImladris();
    String value = year.getText();
    if (!value.isEmpty()) {
        try {//from  ww  w.ja v a 2s  .  c  om
            int yearNum = Integer.parseInt(value);
            if (yearNum > 0 && yearNum <= GregorianInfo.MAX_SUPPORTED_YEAR) {
                int monthNum = month.getSelectedIndex() + 1;
                int dayNum = 0;
                if (day.isEnabled()) {
                    dayNum = day.getSelectedIndex() + 1;
                    ImladrisCalendar cal;
                    if (afterSunset.isSelected()) {
                        GregorianCalendar gcal = new GregorianCalendar(yearNum, monthNum, dayNum);
                        Time time = this.calculateSunsetForActualLocation(gcal, true);
                        cal = new ImladrisCalendar(time, yearNum, monthNum, dayNum, time.getHours(),
                                time.getMinutes(), time.getSeconds());
                    } else {
                        cal = new ImladrisCalendar(yearNum, monthNum, dayNum);
                    }
                    result.setText(cal.toString());
                } else {
                    result.setText(errorDayNotRead);
                }
            } else {
                result.setText(errorYearNotValid);
            }
        } catch (NumberFormatException e) {
            result.setText(errorYearNotNumeric);
        }
    } else {
        result.setText(errorEmptyYear);
    }
}

From source file:DateChooserPanel.java

/**
 * Handles action-events from the date panel.
 *
 * @param e information about the event that occurred.
 *//* w w  w.  j  av  a 2s. c  om*/
public void actionPerformed(final ActionEvent e) {

    if (e.getActionCommand().equals("monthSelectionChanged")) {
        final JComboBox c = (JComboBox) e.getSource();

        // In most cases, changing the month will not change the selected
        // day.  But if the selected day is 29, 30 or 31 and the newly
        // selected month doesn't have that many days, we revert to the 
        // last day of the newly selected month...
        int dayOfMonth = this.chosenDate.get(Calendar.DAY_OF_MONTH);
        this.chosenDate.set(Calendar.DAY_OF_MONTH, 1);
        this.chosenDate.set(Calendar.MONTH, c.getSelectedIndex());
        int maxDayOfMonth = this.chosenDate.getActualMaximum(Calendar.DAY_OF_MONTH);
        this.chosenDate.set(Calendar.DAY_OF_MONTH, Math.min(dayOfMonth, maxDayOfMonth));
        refreshButtons();
    } else if (e.getActionCommand().equals("yearSelectionChanged")) {
        if (!this.refreshing) {
            final JComboBox c = (JComboBox) e.getSource();
            final Integer y = (Integer) c.getSelectedItem();

            // in most cases, changing the year will not change the 
            // selected day.  But if the selected day is Feb 29, and the
            // newly selected year is not a leap year, we revert to 
            // Feb 28...
            int dayOfMonth = this.chosenDate.get(Calendar.DAY_OF_MONTH);
            this.chosenDate.set(Calendar.DAY_OF_MONTH, 1);
            this.chosenDate.set(Calendar.YEAR, y.intValue());
            int maxDayOfMonth = this.chosenDate.getActualMaximum(Calendar.DAY_OF_MONTH);
            this.chosenDate.set(Calendar.DAY_OF_MONTH, Math.min(dayOfMonth, maxDayOfMonth));
            refreshYearSelector();
            refreshButtons();
        }
    } else if (e.getActionCommand().equals("todayButtonClicked")) {
        setDate(new Date());
    } else if (e.getActionCommand().equals("dateButtonClicked")) {
        final JButton b = (JButton) e.getSource();
        final int i = Integer.parseInt(b.getName());
        final Calendar cal = getFirstVisibleDate();
        cal.add(Calendar.DATE, i);
        setDate(cal.getTime());
    }
}

From source file:lu.lippmann.cdb.datasetview.tabs.ScatterPlotTabView.java

private void update0(final Instances dataSet, int xidx, int yidx, int coloridx, final boolean asSerie) {
    System.out.println(xidx + " " + yidx);

    this.panel.removeAll();

    if (xidx == -1)
        xidx = 0;/* w  ww.j  a v  a 2 s  .  c  o m*/
    if (yidx == -1)
        yidx = 1;
    if (coloridx == -1)
        coloridx = 0;

    final Object[] numericAttrNames = WekaDataStatsUtil.getNumericAttributesNames(dataSet).toArray();

    final JComboBox xCombo = new JComboBox(numericAttrNames);
    xCombo.setBorder(new TitledBorder("x"));
    xCombo.setSelectedIndex(xidx);
    final JComboBox yCombo = new JComboBox(numericAttrNames);
    yCombo.setBorder(new TitledBorder("y"));
    yCombo.setSelectedIndex(yidx);
    final JCheckBox jcb = new JCheckBox("Draw lines");
    jcb.setSelected(asSerie);
    final JComboBox colorCombo = new JComboBox(numericAttrNames);
    colorCombo.setBorder(new TitledBorder("color"));
    colorCombo.setSelectedIndex(coloridx);
    colorCombo.setVisible(dataSet.classIndex() < 0);

    xCombo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            update0(dataSet, xCombo.getSelectedIndex(), yCombo.getSelectedIndex(),
                    colorCombo.getSelectedIndex(), jcb.isSelected());
        }
    });

    yCombo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            update0(dataSet, xCombo.getSelectedIndex(), yCombo.getSelectedIndex(),
                    colorCombo.getSelectedIndex(), jcb.isSelected());
        }
    });

    colorCombo.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            update0(dataSet, xCombo.getSelectedIndex(), yCombo.getSelectedIndex(),
                    colorCombo.getSelectedIndex(), jcb.isSelected());
        }
    });

    jcb.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            update0(dataSet, xCombo.getSelectedIndex(), yCombo.getSelectedIndex(),
                    colorCombo.getSelectedIndex(), jcb.isSelected());
        }
    });

    final JXPanel comboPanel = new JXPanel();
    comboPanel.setLayout(new GridLayout(1, 0));
    comboPanel.add(xCombo);
    comboPanel.add(yCombo);
    comboPanel.add(colorCombo);
    comboPanel.add(jcb);
    this.panel.add(comboPanel, BorderLayout.NORTH);

    final java.util.List<Integer> numericAttrIdx = WekaDataStatsUtil.getNumericAttributesIndexes(dataSet);
    final ChartPanel scatterplotChartPanel = buildChartPanel(dataSet, numericAttrIdx.get(xidx),
            numericAttrIdx.get(yidx), numericAttrIdx.get(coloridx), asSerie);

    this.panel.add(scatterplotChartPanel, BorderLayout.CENTER);

    this.panel.repaint();
    this.panel.updateUI();
}

From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java

private String getFlag(javax.swing.JComboBox comboBox) {
    String result = null;/*from  w  w w.ja  v a2  s.c om*/
    if (comboBox.getSelectedIndex() == 1) {
        result = "RestartJava";
    } else if (comboBox.getSelectedIndex() == 2) {
        result = "RestartLuna";
    } else if (comboBox.getSelectedIndex() == 3) {
        result = "RestartDevice";
    }
    return result;
}

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

public PreferencesDialog(final DownloaderGUI owner, Properties config) {
    super(owner, "Preferences", true);

    HttpClientParams params = new HttpClientParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    params.setSoTimeout(30000);/*from w ww.  j a  va  2  s  .c om*/
    client = new HttpClient(params);
    setProxy(ProxyCfg.parseConfig(config));

    sample = new Deviation();
    sample.setId(15972367L);
    sample.setTitle("Fella Promo");
    sample.setArtist("devart");
    sample.setImageDownloadUrl(DOWNLOAD_URL);
    sample.setImageFilename(Deviation.extractFilename(DOWNLOAD_URL));
    sample.setCollection(new Collection(1L, "MyCollect"));
    setLayout(new BorderLayout());
    panes = new JTabbedPane(JTabbedPane.TOP);

    JPanel genPanel = new JPanel();
    BoxLayout genLayout = new BoxLayout(genPanel, BoxLayout.Y_AXIS);
    genPanel.setLayout(genLayout);
    panes.add("General", genPanel);

    JLabel userLabel = new JLabel("Username");

    userLabel.setToolTipText("The username the account you want to download the favorites from.");

    userField = new JTextField(config.getProperty(Constants.USERNAME));

    userLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    userField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userField.setMaximumSize(new Dimension(Integer.MAX_VALUE, userField.getFont().getSize() * 2));

    genPanel.add(userLabel);
    genPanel.add(userField);

    JPanel radioPanel = new JPanel();
    BoxLayout radioLayout = new BoxLayout(radioPanel, BoxLayout.X_AXIS);
    radioPanel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    radioPanel.setBorder(new EmptyBorder(0, 5, 0, 5));

    radioPanel.setLayout(radioLayout);

    JLabel searchLabel = new JLabel("Search for");
    searchLabel
            .setToolTipText("Select what you want to download from that user: it favorites or it galleries.");
    searchLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searchLabel.setBorder(new EmptyBorder(0, 5, 0, 5));

    selectedSearch = SEARCH.lookup(config.getProperty(Constants.SEARCH, SEARCH.getDefault().getId()));
    buttonGroup = new ButtonGroup();

    for (final SEARCH search : SEARCH.values()) {
        JRadioButton radio = new JRadioButton(search.getLabel());
        radio.setAlignmentX(JLabel.LEFT_ALIGNMENT);
        radio.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                selectedSearch = search;
            }
        });

        buttonGroup.add(radio);
        radioPanel.add(radio);
        if (search.equals(selectedSearch)) {
            radio.setSelected(true);
        }
    }

    genPanel.add(radioPanel);

    final JTextField sampleField = new JTextField("");
    sampleField.setEditable(false);

    JLabel locationLabel = new JLabel("Download location");
    locationLabel.setToolTipText("The folder pattern where you want the file to be downloaded in.");

    JLabel legendsLabel = new JLabel(
            "<html><body>Field names: %user%, %artist%, %title%, %id%, %filename%, %collection%, %ext%<br></br>Example:</body></html>");
    legendsLabel.setToolTipText("An example of where a file will be downloaded to.");

    locationString = new StringBuilder();
    locationField = new JTextField(config.getProperty(Constants.LOCATION));
    locationField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationString.setLength(0);
            locationString.append(dest.getAbsolutePath());
            sampleField.setText(locationString.toString());
            if (useSameForMatureBox.isSelected()) {
                locationMatureString.setLength(0);
                locationMatureString.append(sampleField.getText());
                locationMatureField.setText(locationField.getText());
            }
        }

        public void keyTyped(KeyEvent e) {
        }

    });
    locationField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });
    JLabel locationMatureLabel = new JLabel("Mature download location");
    locationMatureLabel.setToolTipText(
            "The folder pattern where you want the file marked as 'Mature' to be downloaded in.");

    locationMatureString = new StringBuilder();
    locationMatureField = new JTextField(config.getProperty(Constants.MATURE));
    locationMatureField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationMatureString.setLength(0);
            locationMatureString.append(dest.getAbsolutePath());
            sampleField.setText(locationMatureString.toString());
        }

        public void keyTyped(KeyEvent e) {
        }

    });

    locationMatureField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationMatureString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });

    useSameForMatureBox = new JCheckBox("Use same location for mature deviation?");
    useSameForMatureBox.setSelected(locationLabel.getText().equals(locationMatureField.getText()));
    useSameForMatureBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (useSameForMatureBox.isSelected()) {
                locationMatureField.setEditable(false);
                locationMatureField.setText(locationField.getText());
                locationMatureString.setLength(0);
                locationMatureString.append(locationString);
            } else {
                locationMatureField.setEditable(true);
            }

        }
    });

    File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    sampleField.setText(dest.getAbsolutePath());
    locationString.append(sampleField.getText());

    dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    locationMatureString.append(dest.getAbsolutePath());

    locationLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationField.setMaximumSize(new Dimension(Integer.MAX_VALUE, locationField.getFont().getSize() * 2));
    locationMatureLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationMatureField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureField
            .setMaximumSize(new Dimension(Integer.MAX_VALUE, locationMatureField.getFont().getSize() * 2));
    useSameForMatureBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    legendsLabel.setMaximumSize(new Dimension(Integer.MAX_VALUE, legendsLabel.getFont().getSize() * 2));
    sampleField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    sampleField.setMaximumSize(new Dimension(Integer.MAX_VALUE, sampleField.getFont().getSize() * 2));

    genPanel.add(locationLabel);
    genPanel.add(locationField);

    genPanel.add(locationMatureLabel);
    genPanel.add(locationMatureField);
    genPanel.add(useSameForMatureBox);

    genPanel.add(legendsLabel);
    genPanel.add(sampleField);
    genPanel.add(Box.createVerticalBox());

    final KeyListener prxChangeListener = new KeyListener() {

        public void keyTyped(KeyEvent e) {
            proxyChangeState = true;
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
        }
    };

    JPanel prxPanel = new JPanel();
    BoxLayout prxLayout = new BoxLayout(prxPanel, BoxLayout.Y_AXIS);
    prxPanel.setLayout(prxLayout);
    panes.add("Proxy", prxPanel);

    JLabel prxHostLabel = new JLabel("Proxy Host");
    prxHostLabel.setToolTipText("The hostname of the proxy server");
    prxHostField = new JTextField(config.getProperty(Constants.PROXY_HOST));
    prxHostLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxHostField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxHostField.getFont().getSize() * 2));

    JLabel prxPortLabel = new JLabel("Proxy Port");
    prxPortLabel.setToolTipText("The port of the proxy server (Default 80).");

    prxPortSpinner = new JSpinner();
    prxPortSpinner.setModel(new SpinnerNumberModel(
            Integer.parseInt(config.getProperty(Constants.PROXY_PORT, "80")), 1, 65535, 1));

    prxPortLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPortSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPortSpinner.getFont().getSize() * 2));

    JLabel prxUserLabel = new JLabel("Proxy username");
    prxUserLabel.setToolTipText("The username used for authentication, if applicable.");
    prxUserField = new JTextField(config.getProperty(Constants.PROXY_USERNAME));
    prxUserLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxUserField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxUserField.getFont().getSize() * 2));

    JLabel prxPassLabel = new JLabel("Proxy username");
    prxPassLabel.setToolTipText("The username used for authentication, if applicable.");
    prxPassField = new JPasswordField(config.getProperty(Constants.PROXY_PASSWORD));
    prxPassLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPassField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPassField.getFont().getSize() * 2));

    prxUseBox = new JCheckBox("Use a proxy?");
    prxUseBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            prxChangeListener.keyTyped(null);

            if (prxUseBox.isSelected()) {
                prxHostField.setEditable(true);
                prxPortSpinner.setEnabled(true);
                prxUserField.setEditable(true);
                prxPassField.setEditable(true);

            } else {
                prxHostField.setEditable(false);
                prxPortSpinner.setEnabled(false);
                prxUserField.setEditable(false);
                prxPassField.setEditable(false);
            }
        }
    });

    prxUseBox.setSelected(!Boolean.parseBoolean(config.getProperty(Constants.PROXY_USE)));
    prxUseBox.doClick();
    proxyChangeState = false;

    prxHostField.addKeyListener(prxChangeListener);
    prxUserField.addKeyListener(prxChangeListener);
    prxPassField.addKeyListener(prxChangeListener);
    prxPortSpinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            proxyChangeState = true;
        }
    });
    prxPanel.add(prxUseBox);

    prxPanel.add(prxHostLabel);
    prxPanel.add(prxHostField);

    prxPanel.add(prxPortLabel);
    prxPanel.add(prxPortSpinner);

    prxPanel.add(prxUserLabel);
    prxPanel.add(prxUserField);

    prxPanel.add(prxPassLabel);
    prxPanel.add(prxPassField);
    prxPanel.add(Box.createVerticalBox());

    final JPanel advPanel = new JPanel();
    BoxLayout advLayout = new BoxLayout(advPanel, BoxLayout.Y_AXIS);
    advPanel.setLayout(advLayout);
    panes.add("Advanced", advPanel);
    panes.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            JTabbedPane pane = (JTabbedPane) e.getSource();

            if (proxyChangeState && pane.getSelectedComponent() == advPanel) {
                Properties properties = new Properties();
                properties.setProperty(Constants.PROXY_USERNAME, prxUserField.getText().trim());
                properties.setProperty(Constants.PROXY_PASSWORD, new String(prxPassField.getPassword()).trim());
                properties.setProperty(Constants.PROXY_HOST, prxHostField.getText().trim());
                properties.setProperty(Constants.PROXY_PORT, prxPortSpinner.getValue().toString());
                properties.setProperty(Constants.PROXY_USE, Boolean.toString(prxUseBox.isSelected()));
                ProxyCfg prx = ProxyCfg.parseConfig(properties);
                setProxy(prx);
                revalidateSearcher(null);
            }
        }
    });
    JLabel domainLabel = new JLabel("Deviant Art domain name");
    domainLabel.setToolTipText("The deviantART main domain, should it ever change.");

    domainField = new JTextField(config.getProperty(Constants.DOMAIN));
    domainLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    domainField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainField.setMaximumSize(new Dimension(Integer.MAX_VALUE, domainField.getFont().getSize() * 2));

    advPanel.add(domainLabel);
    advPanel.add(domainField);

    JLabel throttleLabel = new JLabel("Throttle search delay");
    throttleLabel.setToolTipText(
            "Slow down search query by inserting a pause between them. This help prevent abuse when doing a massive download.");

    throttleSpinner = new JSpinner();
    throttleSpinner.setModel(
            new SpinnerNumberModel(Integer.parseInt(config.getProperty(Constants.THROTTLE, "0")), 5, 60, 1));

    throttleLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    throttleSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, throttleSpinner.getFont().getSize() * 2));

    advPanel.add(throttleLabel);
    advPanel.add(throttleSpinner);

    JLabel searcherLabel = new JLabel("Searcher");
    searcherLabel.setToolTipText("Select a searcher that will look for your favorites.");

    searcherBox = new JComboBox();
    searcherBox.setRenderer(new TogglingRenderer());

    final AtomicInteger index = new AtomicInteger(0);
    searcherBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox) e.getSource();
            Object selectedItem = combo.getSelectedItem();
            if (selectedItem instanceof SearchItem) {
                SearchItem item = (SearchItem) selectedItem;
                if (item.isValid) {
                    index.set(combo.getSelectedIndex());
                } else {
                    combo.setSelectedIndex(index.get());
                }
            }
        }
    });

    try {
        for (Class<Search> clazz : SearcherClassCache.getInstance().getClasses()) {

            Search searcher = clazz.newInstance();
            String name = searcher.getName();

            SearchItem item = new SearchItem(name, clazz.getName(), true);
            searcherBox.addItem(item);
        }
        String selectedClazz = config.getProperty(Constants.SEARCHER,
                com.dragoniade.deviantart.deviation.SearchRss.class.getName());
        revalidateSearcher(selectedClazz);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    searcherLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    searcherBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, searcherBox.getFont().getSize() * 2));

    advPanel.add(searcherLabel);
    advPanel.add(searcherBox);

    advPanel.add(Box.createVerticalBox());

    add(panes, BorderLayout.CENTER);

    JButton saveBut = new JButton("Save");

    userField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            if (field.getText().trim().length() == 0) {
                JOptionPane.showMessageDialog(input, "The user musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The location must contains at least a %filename% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationMatureField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The Mature location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The Mature location must contains at least a %username% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    domainField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String domain = field.getText().trim();
            if (domain.length() == 0) {
                JOptionPane.showMessageDialog(input, "You must specify the deviantART main domain.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (domain.toLowerCase().startsWith("http://")) {
                JOptionPane.showMessageDialog(input,
                        "You must specify the deviantART main domain, not the full URL (aka www.deviantart.com).",
                        "Warning", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            return true;
        }
    });
    locationField.setVerifyInputWhenFocusTarget(true);

    final JDialog parent = this;
    saveBut.addActionListener(new ActionListener() {

        String errorMsg = "The location is invalid or cannot be written to.";

        public void actionPerformed(ActionEvent e) {

            String username = userField.getText().trim();
            String location = locationField.getText().trim();
            String locationMature = locationMatureField.getText().trim();
            String domain = domainField.getText().trim();
            String throttle = throttleSpinner.getValue().toString();
            String searcher = searcherBox.getSelectedItem().toString();

            String prxUse = Boolean.toString(prxUseBox.isSelected());
            String prxHost = prxHostField.getText().trim();
            String prxPort = prxPortSpinner.getValue().toString();
            String prxUsername = prxUserField.getText().trim();
            String prxPassword = new String(prxPassField.getPassword()).trim();

            if (!testPath(location, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (!testPath(locationMature, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }

            Properties p = new Properties();
            p.setProperty(Constants.USERNAME, username);
            p.setProperty(Constants.LOCATION, location);
            p.setProperty(Constants.MATURE, locationMature);
            p.setProperty(Constants.DOMAIN, domain);
            p.setProperty(Constants.THROTTLE, throttle);
            p.setProperty(Constants.SEARCHER, searcher);
            p.setProperty(Constants.SEARCH, selectedSearch.getId());

            p.setProperty(Constants.PROXY_USE, prxUse);
            p.setProperty(Constants.PROXY_HOST, prxHost);
            p.setProperty(Constants.PROXY_PORT, prxPort);
            p.setProperty(Constants.PROXY_USERNAME, prxUsername);
            p.setProperty(Constants.PROXY_PASSWORD, prxPassword);

            owner.savePreferences(p);
            parent.dispose();
        }
    });

    JButton cancelBut = new JButton("Cancel");
    cancelBut.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            parent.dispose();
        }
    });

    JPanel buttonPanel = new JPanel();
    BoxLayout butLayout = new BoxLayout(buttonPanel, BoxLayout.X_AXIS);
    buttonPanel.setLayout(butLayout);

    buttonPanel.add(saveBut);
    buttonPanel.add(cancelBut);
    add(buttonPanel, BorderLayout.SOUTH);

    pack();
    setResizable(false);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);
    setVisible(true);
}

From source file:de.dmarcini.submatix.pclogger.gui.spx42LogGraphPanel.java

@Override
public void actionPerformed(ActionEvent ev) {
    String cmd = ev.getActionCommand();
    String entry = null;//from w  ww.ja v a2 s.com
    int dbId;
    String device;
    //
    // /////////////////////////////////////////////////////////////////////////
    // Button
    if (ev.getSource() instanceof JButton) {
        // JButton srcButton = ( JButton )ev.getSource();
        // /////////////////////////////////////////////////////////////////////////
        // Anzeigebutton?
        if (cmd.equals("show_log_graph")) {
            lg.debug("show log graph initiated.");
            // welches Device ?
            if (deviceComboBox.getSelectedIndex() < 0) {
                // kein Gert ausgewhlt
                lg.warn("no device selected.");
                return;
            }
            // welchen Tauchgang?
            if (diveSelectComboBox.getSelectedIndex() < 0) {
                lg.warn("no dive selected.");
                return;
            }
            device = ((DeviceComboBoxModel) deviceComboBox.getModel())
                    .getDeviceSerialAt(deviceComboBox.getSelectedIndex());
            dbId = ((LogListComboBoxModel) diveSelectComboBox.getModel())
                    .getDatabaseIdAt(diveSelectComboBox.getSelectedIndex());
            lg.debug("Select Device-Serial: " + device + ", DBID: " + dbId);
            if (dbId < 0) {
                lg.error("can't find database id for dive.");
                return;
            }
            makeGraphForLog(dbId, device);
            return;
        } else if (cmd.equals("set_detail_for_show_graph")) {
            lg.debug("select details for log selected.");
            SelectGraphDetailsDialog sgd = new SelectGraphDetailsDialog();
            if (sgd.showModal()) {
                lg.debug("dialog returned 'true' => change propertys...");
                computeGraphButton.doClick();
            }
        } else if (cmd.equals("edit_notes_for_dive")) {
            if (chartPanel == null || showingDbIdForDiveWasShowing == -1) {
                lg.warn("it was not showing a dive! do nothing!");
                return;
            }
            lg.debug("edit a note for this dive...");
            showNotesEditForm(showingDbIdForDiveWasShowing);
        } else {
            lg.warn("unknown button command <" + cmd + "> recived.");
        }
        return;
    }
    // /////////////////////////////////////////////////////////////////////////
    // Combobox
    else if (ev.getSource() instanceof JComboBox<?>) {
        @SuppressWarnings("unchecked")
        JComboBox<String> srcBox = (JComboBox<String>) ev.getSource();
        // /////////////////////////////////////////////////////////////////////////
        // Gert zur Grafischen Darstellung auswhlen
        if (cmd.equals("change_device_to_display")) {
            if (srcBox.getModel() instanceof DeviceComboBoxModel) {
                entry = ((DeviceComboBoxModel) srcBox.getModel()).getDeviceSerialAt(srcBox.getSelectedIndex());
                lg.debug("device <" + entry + ">...Index: <" + srcBox.getSelectedIndex() + ">");
                fillDiveComboBox(entry);
            }
        }
        // /////////////////////////////////////////////////////////////////////////
        // Dive zur Grafischen Darstellung auswhlen
        else if (cmd.equals("change_dive_to_display")) {
            entry = (String) srcBox.getSelectedItem();
            lg.debug("dive <" + entry + ">...Index: <" + srcBox.getSelectedIndex() + ">");
            // fillDiveComboBox( entry );
        } else {
            lg.warn("unknown combobox command <" + cmd + "> recived.");
        }
        return;
    } else {
        lg.warn("unknown action command <" + cmd + "> recived.");
    }
}