Example usage for javax.swing JComboBox setEnabled

List of usage examples for javax.swing JComboBox setEnabled

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "The enabled state of the component.")
public void setEnabled(boolean b) 

Source Link

Document

Enables the combo box so that items can be selected.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);

    cb.setEnabled(true);
}

From source file:Graph_with_jframe_and_arduino.java

public static void main(String[] args) {

    // create and configure the window
    JFrame window = new JFrame();
    window.setTitle("Sensor Graph GUI");
    window.setSize(600, 400);/*from  ww w  . ja  v a2  s  .co  m*/
    window.setLayout(new BorderLayout());
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // create a drop-down box and connect button, then place them at the top of the window
    JComboBox<String> portList_combobox = new JComboBox<String>();
    Dimension d = new Dimension(300, 100);
    portList_combobox.setSize(d);
    JButton connectButton = new JButton("Connect");
    JPanel topPanel = new JPanel();
    topPanel.add(portList_combobox);
    topPanel.add(connectButton);
    window.add(topPanel, BorderLayout.NORTH);
    //pause button
    JButton Pause_btn = new JButton("Start");

    // populate the drop-down box
    SerialPort[] portNames;
    portNames = SerialPort.getCommPorts();
    //check for new port available
    Thread thread_port = new Thread() {
        @Override
        public void run() {
            while (true) {
                SerialPort[] sp = SerialPort.getCommPorts();
                if (sp.length > 0) {
                    for (SerialPort sp_name : sp) {
                        int l = portList_combobox.getItemCount(), i;
                        for (i = 0; i < l; i++) {
                            //check port name already exist or not
                            if (sp_name.getSystemPortName().equalsIgnoreCase(portList_combobox.getItemAt(i))) {
                                break;
                            }
                        }
                        if (i == l) {
                            portList_combobox.addItem(sp_name.getSystemPortName());
                        }

                    }

                } else {
                    portList_combobox.removeAllItems();

                }
                portList_combobox.repaint();

            }

        }

    };
    thread_port.start();
    for (SerialPort sp_name : portNames)
        portList_combobox.addItem(sp_name.getSystemPortName());

    //for(int i = 0; i < portNames.length; i++)
    //   portList.addItem(portNames[i].getSystemPortName());

    // create the line graph
    XYSeries series = new XYSeries("line 1");
    XYSeries series2 = new XYSeries("line 2");
    XYSeries series3 = new XYSeries("line 3");
    XYSeries series4 = new XYSeries("line 4");
    for (int i = 0; i < 100; i++) {
        series.add(x, 0);
        series2.add(x, 0);
        series3.add(x, 0);
        series4.add(x, 10);
        x++;
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);
    dataset.addSeries(series2);
    XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(series3);
    dataset2.addSeries(series4);

    //create jfree chart
    JFreeChart chart = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading",
            dataset);
    JFreeChart chart2 = ChartFactory.createXYLineChart("Sensor Readings", "Time (seconds)", "Arduino Reading 2",
            dataset2);

    //color render for chart 1
    XYLineAndShapeRenderer r1 = new XYLineAndShapeRenderer();
    r1.setSeriesPaint(0, Color.RED);
    r1.setSeriesPaint(1, Color.GREEN);
    r1.setSeriesShapesVisible(0, false);
    r1.setSeriesShapesVisible(1, false);

    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(0, r1);
    plot.setRenderer(1, r1);

    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.DARK_GRAY);
    plot.setRangeGridlinePaint(Color.blue);

    //color render for chart 2
    XYLineAndShapeRenderer r2 = new XYLineAndShapeRenderer();
    r2.setSeriesPaint(0, Color.BLUE);
    r2.setSeriesPaint(1, Color.ORANGE);
    r2.setSeriesShapesVisible(0, false);
    r2.setSeriesShapesVisible(1, false);

    XYPlot plot2 = chart2.getXYPlot();
    plot2.setRenderer(0, r2);
    plot2.setRenderer(1, r2);

    ChartPanel cp = new ChartPanel(chart);
    ChartPanel cp2 = new ChartPanel(chart2);

    //multiple graph container
    JPanel graph_container = new JPanel();
    graph_container.setLayout(new BoxLayout(graph_container, BoxLayout.X_AXIS));
    graph_container.add(cp);
    graph_container.add(cp2);

    //add chart panel in main window
    window.add(graph_container, BorderLayout.CENTER);
    //window.add(cp2, BorderLayout.WEST);

    window.add(Pause_btn, BorderLayout.AFTER_LAST_LINE);
    Pause_btn.setEnabled(false);
    //pause btn action
    Pause_btn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (Pause_btn.getText().equalsIgnoreCase("Pause")) {

                if (chosenPort.isOpen()) {
                    try {
                        Output.write(0);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Start");
            } else {
                if (chosenPort.isOpen()) {
                    try {
                        Output.write(1);
                    } catch (IOException ex) {
                        Logger.getLogger(Graph_with_jframe_and_arduino.class.getName()).log(Level.SEVERE, null,
                                ex);
                    }
                }

                Pause_btn.setText("Pause");
            }
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });

    // configure the connect button and use another thread to listen for data
    connectButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (connectButton.getText().equals("Connect")) {
                // attempt to connect to the serial port
                chosenPort = SerialPort.getCommPort(portList_combobox.getSelectedItem().toString());
                chosenPort.setComPortTimeouts(SerialPort.TIMEOUT_SCANNER, 0, 0);
                if (chosenPort.openPort()) {
                    Output = chosenPort.getOutputStream();
                    connectButton.setText("Disconnect");
                    Pause_btn.setEnabled(true);
                    portList_combobox.setEnabled(false);
                }

                // create a new thread that listens for incoming text and populates the graph
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        Scanner scanner = new Scanner(chosenPort.getInputStream());
                        while (scanner.hasNextLine()) {
                            try {
                                String line = scanner.nextLine();
                                int number = Integer.parseInt(line);
                                series.add(x, number);
                                series2.add(x, number / 2);
                                series3.add(x, number / 1.5);
                                series4.add(x, number / 5);

                                if (x > 100) {
                                    series.remove(0);
                                    series2.remove(0);
                                    series3.remove(0);
                                    series4.remove(0);
                                }

                                x++;
                                window.repaint();
                            } catch (Exception e) {
                            }
                        }
                        scanner.close();
                    }
                };
                thread.start();
            } else {
                // disconnect from the serial port
                chosenPort.closePort();
                portList_combobox.setEnabled(true);
                Pause_btn.setEnabled(false);
                connectButton.setText("Connect");

            }
        }
    });

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

From source file:Main.java

/**
 * Replace the options in a combo box with a new set.
 * nulls are skipped.  Selected value is preserved.
 *
 * @param combob GUI component to update
 * @param values list of values to put into component, or null to erase
 *///from   w ww  .  jav  a  2s. co m
public static void replaceContents(JComboBox combob, List<?> values) {
    Object cur = combob.getSelectedItem();
    DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
    m.removeAllElements();
    if (values != null)
        for (Object v : values)
            if (v != null)
                m.addElement(v);
    combob.setSelectedItem(cur);
    combob.setEnabled(true);
}

From source file:Main.java

/**
 * Replace the options in a combo box with a new set.
 * nulls are skipped.  Selected value is preserved.
 *
 * @param combob GUI component to update
 * @param values list of values to put into component, or null to erase
 *//*from w w  w.ja  v a2  s  . co  m*/
public static void replaceContents(JComboBox combob, Object[] values) {
    Object cur = combob.getSelectedItem();
    DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
    m.removeAllElements();
    if (values != null)
        for (Object v : values)
            if (v != null)
                m.addElement(v);
    combob.setSelectedItem(cur);
    combob.setEnabled(true);
}

From source file:Main.java

/**
 * Replace the options in a combo box with a new set.
 * nulls are skipped.  Selected value is preserved.
 *
 * @param combob GUI component to update
 * @param values list of values to put into component, or null to erase
 *///from   w  w  w  . j  a va2s .  c  o  m
public static void replaceContents(JComboBox combob, Vector<?> values) {
    Object cur = combob.getSelectedItem();
    DefaultComboBoxModel m = (DefaultComboBoxModel) combob.getModel();
    m.removeAllElements();
    if (values != null)
        for (Object v : values)
            if (v != null)
                m.addElement(v);
    combob.setSelectedItem(cur);
    combob.setEnabled(true);
}

From source file:com.eviware.soapui.support.editor.inspectors.auth.ExpirationTimeChooser.java

private JComboBox createTimeUnitCombo(boolean enableManualTimeControls) {
    JComboBox timeUnitCombo = new JComboBox(TIME_UNIT_OPTIONS);
    timeUnitCombo.setName(TIME_UNIT_COMBO_NAME);
    timeUnitCombo.setEnabled(enableManualTimeControls);

    TimeUnitConfig.Enum timeUnit = profile.getManualAccessTokenExpirationTimeUnit();
    timeUnitCombo.setSelectedItem(WordUtils.capitalize(timeUnit.toString().toLowerCase()));

    return timeUnitCombo;
}

From source file:net.sf.jabref.gui.preftabs.AppearancePrefsTab.java

/**
 * Customization of appearance parameters.
 *
 * @param prefs a <code>JabRefPreferences</code> value
 *//*w  w  w.  ja  v a2  s . c  o  m*/
public AppearancePrefsTab(JabRefPreferences prefs) {
    this.prefs = prefs;
    setLayout(new BorderLayout());

    // Font sizes:
    fontSize = new JTextField(5);

    // Row padding size:
    rowPadding = new JTextField(5);

    colorCodes = new JCheckBox(Localization.lang("Color codes for required and optional fields"));

    overrideFonts = new JCheckBox(Localization.lang("Override default font settings"));

    showGrid = new JCheckBox(Localization.lang("Show gridlines"));

    FormLayout layout = new FormLayout(
            "1dlu, 8dlu, left:pref, 4dlu, fill:pref, 4dlu, fill:60dlu, 4dlu, fill:pref", "");
    DefaultFormBuilder builder = new DefaultFormBuilder(layout);

    customLAF = new JCheckBox(Localization.lang("Use other look and feel"));
    // Only list L&F which are available
    List<String> lookAndFeels = LookAndFeel.getAvailableLookAndFeels();
    classNamesLAF = new JComboBox<>(lookAndFeels.toArray(new String[lookAndFeels.size()]));
    classNamesLAF.setEditable(true);
    final JComboBox<String> clName = classNamesLAF;
    customLAF.addChangeListener(e -> clName.setEnabled(((JCheckBox) e.getSource()).isSelected()));

    // only the default L&F shows the the OSX specific first dropdownmenu
    if (!OS.OS_X) {
        JPanel pan = new JPanel();
        builder.appendSeparator(Localization.lang("Look and feel"));
        JLabel lab = new JLabel(
                Localization.lang("Default look and feel") + ": " + UIManager.getSystemLookAndFeelClassName());
        builder.nextLine();
        builder.append(pan);
        builder.append(lab);
        builder.nextLine();
        builder.append(pan);
        builder.append(customLAF);
        builder.nextLine();
        builder.append(pan);
        JPanel pan2 = new JPanel();
        lab = new JLabel(Localization.lang("Class name") + ':');
        pan2.add(lab);
        pan2.add(classNamesLAF);
        builder.append(pan2);
        builder.nextLine();
        builder.append(pan);
        lab = new JLabel(Localization
                .lang("Note that you must specify the fully qualified class name for the look and feel,"));
        builder.append(lab);
        builder.nextLine();
        builder.append(pan);
        lab = new JLabel(Localization
                .lang("and the class must be available in your classpath next time you start JabRef."));
        builder.append(lab);
        builder.nextLine();
    }

    builder.leadingColumnOffset(2);
    JLabel lab;
    builder.appendSeparator(Localization.lang("General"));
    JPanel p1 = new JPanel();
    lab = new JLabel(Localization.lang("Menu and label font size") + ":");
    p1.add(lab);
    p1.add(fontSize);
    builder.append(p1);
    builder.nextLine();
    builder.append(overrideFonts);
    builder.nextLine();
    builder.appendSeparator(Localization.lang("Table appearance"));
    JPanel p2 = new JPanel();
    p2.add(new JLabel(Localization.lang("Table row height padding") + ":"));
    p2.add(rowPadding);
    builder.append(p2);
    builder.nextLine();
    builder.append(colorCodes);
    builder.nextLine();
    builder.append(showGrid);
    builder.nextLine();
    JButton fontButton = new JButton(Localization.lang("Set table font"));
    builder.append(fontButton);
    builder.nextLine();
    builder.appendSeparator(Localization.lang("Table and entry editor colors"));
    builder.append(colorPanel);

    JPanel upper = new JPanel();
    JPanel sort = new JPanel();
    JPanel namesp = new JPanel();
    JPanel iconCol = new JPanel();
    GridBagLayout gbl = new GridBagLayout();
    upper.setLayout(gbl);
    sort.setLayout(gbl);
    namesp.setLayout(gbl);
    iconCol.setLayout(gbl);

    overrideFonts.addActionListener(e -> fontSize.setEnabled(overrideFonts.isSelected()));

    fontButton.addActionListener(e -> new FontSelectorDialog(null, GUIGlobals.currentFont).getSelectedFont()
            .ifPresent(x -> usedFont = x));

    JPanel pan = builder.getPanel();
    pan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    add(pan, BorderLayout.CENTER);
}

From source file:net.sf.mzmine.modules.visualization.spectra.SpectraVisualizerWindow.java

public void loadRawData(Scan scan) {

    logger.finest("Loading scan #" + scan.getScanNumber() + " from " + dataFile + " for spectra visualizer");

    spectrumDataSet = new ScanDataSet(scan);

    this.currentScan = scan;

    // If the plot mode has not been set yet, set it accordingly
    if (spectrumPlot.getPlotMode() == null) {
        if (currentScan.isCentroided()) {
            spectrumPlot.setPlotMode(PlotMode.CENTROID);
            toolBar.setCentroidButton(false);
        } else {//from   w w  w .j a va2  s .c  o  m
            spectrumPlot.setPlotMode(PlotMode.CONTINUOUS);
            toolBar.setCentroidButton(true);
        }
    }

    // Clean up the MS/MS selector combo

    final JComboBox msmsSelector = bottomPanel.getMSMSSelector();

    // We disable the MSMS selector first and then enable it again later
    // after updating the items. If we skip this, the size of the
    // selector may not be adjusted properly (timing issues?)
    msmsSelector.setEnabled(false);

    msmsSelector.removeAllItems();
    boolean msmsVisible = false;

    // Add parent scan to MS/MS selector combo

    NumberFormat rtFormat = MZmineCore.getConfiguration().getRTFormat();
    NumberFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    NumberFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();

    int parentNumber = currentScan.getParentScanNumber();
    if ((currentScan.getMSLevel() > 1) && (parentNumber > 0)) {

        Scan parentScan = dataFile.getScan(parentNumber);
        if (parentScan != null) {
            String itemText = "Parent scan #" + parentNumber + ", RT: "
                    + rtFormat.format(parentScan.getRetentionTime()) + ", precursor m/z: "
                    + mzFormat.format(currentScan.getPrecursorMZ());

            if (currentScan.getPrecursorCharge() > 0)
                itemText += " (chrg " + currentScan.getPrecursorCharge() + ")";

            msmsSelector.addItem(itemText);
            msmsVisible = true;
        }
    }

    // Add all fragment scans to MS/MS selector combo
    int fragmentScans[] = currentScan.getFragmentScanNumbers();
    if (fragmentScans != null) {
        for (int fragment : fragmentScans) {
            Scan fragmentScan = dataFile.getScan(fragment);
            if (fragmentScan == null)
                continue;
            final String itemText = "Fragment scan #" + fragment + ", RT: "
                    + rtFormat.format(fragmentScan.getRetentionTime()) + ", precursor m/z: "
                    + mzFormat.format(fragmentScan.getPrecursorMZ());
            // Updating the combo in other than Swing thread may cause
            // exception
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    msmsSelector.addItem(itemText);
                }
            });
            msmsVisible = true;
        }
    }

    msmsSelector.setEnabled(true);

    // Update the visibility of MS/MS selection combo
    bottomPanel.setMSMSSelectorVisible(msmsVisible);

    // Set window and plot titles

    String title = "[" + dataFile.getName() + "] scan #" + currentScan.getScanNumber();

    String subTitle = "MS" + currentScan.getMSLevel();

    if (currentScan.getMSLevel() > 1) {
        subTitle += " (" + mzFormat.format(currentScan.getPrecursorMZ()) + " precursor m/z)";
    }

    subTitle += ", RT " + rtFormat.format(currentScan.getRetentionTime());

    DataPoint basePeak = currentScan.getHighestDataPoint();
    if (basePeak != null) {
        subTitle += ", base peak: " + mzFormat.format(basePeak.getMZ()) + " m/z ("
                + intensityFormat.format(basePeak.getIntensity()) + ")";
    }

    setTitle(title);
    spectrumPlot.setTitle(title, subTitle);

    // Set plot data set
    spectrumPlot.removeAllDataSets();
    spectrumPlot.addDataSet(spectrumDataSet, scanColor, false);

    // Reload peak list
    bottomPanel.rebuildPeakListSelector();

}

From source file:edu.virginia.iath.oxygenplugins.juel.JUELPluginMenu.java

public JUELPluginMenu(StandalonePluginWorkspace spw, LocalOptions ops) {
    super(name, true);
    ws = spw;//from w ww .  j  a  va  2  s .  c o m
    options = ops;

    // setup the options
    //options.readStorage();

    // Find names
    JMenuItem search = new JMenuItem("Find Name");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Name";

            final JTextField lastName = new JTextField("", 30);
            lastName.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL("http://juel.iath.virginia.edu/academical_db/people/find_people?term="
                                + lastName.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String name = cur.getString("label");
                            String id = String.format("P%05d", cur.getInt("value"));
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for last name, then choose a full name from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Last Name: "));
            addPanelInner.add(lastName);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);

    // Find places
    search = new JMenuItem("Find Place");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Place";

            final JTextField searchText = new JTextField("", 30);
            searchText.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL(
                                "http://academical.village.virginia.edu/academical_db/places/find_places?term="
                                        + searchText.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String id = String.format("PL%04d", cur.getInt("value"));
                            String name = cur.getString("label") + " (" + id + ")";
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for a place name, then choose one from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Keyword: "));
            addPanelInner.add(searchText);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);

    // Find corporate bodies
    search = new JMenuItem("Find Corporate Body");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Corporate Body";

            final JTextField searchText = new JTextField("", 30);
            searchText.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL(
                                "http://academical.village.virginia.edu/academical_db/corporate_bodies/find?term="
                                        + searchText.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String id = String.format("CB%04d", cur.getInt("value"));
                            String name = cur.getString("label") + " (" + id + ")";
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for a corporate body, then one from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Keyword: "));
            addPanelInner.add(searchText);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);

    // Find Courses
    search = new JMenuItem("Find Course");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Course";

            final JTextField searchText = new JTextField("", 30);
            searchText.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL(
                                "http://academical.village.virginia.edu/academical_db/courses/find?term="
                                        + searchText.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String id = String.format("C%04d", cur.getInt("value"));
                            String name = cur.getString("label") + " (" + id + ")";
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for a course, then choose one from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Keyword: "));
            addPanelInner.add(searchText);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);
}

From source file:com.alvermont.terraj.stargen.ui.StargenFrame.java

/**
 * Update a linked checkbox and combo box. The combo box will be enabled
 * if the checkbox is selected/*from w  ww. j a  va  2 s .  co  m*/
 * 
 * @param component1 The checkbox that controls the combobox
 * @param component2 The combobox
 * @param state The new state to set the checkbox to
 * @param value The value to store in the combo box
 */
protected void updateCombo(JCheckBox component1, JComboBox<String> component2, boolean state, String value) {
    component1.setSelected(state);
    component2.setEnabled(state);
    component2.getModel().setSelectedItem(value);
}