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:Main.java

public static void main(String[] args) {
    String[] weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
    final JComboBox<String> combo = new JComboBox<>(weekdays);

    String[] options = { "OK", "Cancel", "Help" };

    String title = "Title";
    int selection = JOptionPane.showOptionDialog(null, combo, title, JOptionPane.DEFAULT_OPTION,
            JOptionPane.PLAIN_MESSAGE, null, options, options[0]);

    if (selection > 0) {
        System.out.println("selection is: " + options[selection]);
    }//from w w  w.jav  a 2  s  .  c o  m

    Object weekday = combo.getSelectedItem();
    if (weekday != null) {
        System.out.println("weekday: " + weekday);
    }

}

From source file:EditComboBox.java

public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
    JFrame frame = new JFrame("Editable JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    final JComboBox comboBox = new JComboBox(labels);
    comboBox.setMaximumRowCount(5);/*from   w ww. ja  v  a 2s .  c o m*/
    comboBox.setEditable(true);
    contentPane.add(comboBox, BorderLayout.NORTH);

    final JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    contentPane.add(scrollPane, BorderLayout.CENTER);

    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            textArea.append("Selected: " + comboBox.getSelectedItem());
            textArea.append(", Position: " + comboBox.getSelectedIndex());
            textArea.append(System.getProperty("line.separator"));
        }
    };
    comboBox.addActionListener(actionListener);

    frame.setSize(300, 200);
    frame.setVisible(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. j  a  v a 2 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

public static String getSelectedName(JComboBox comboBox) {
    return (String) comboBox.getSelectedItem();
}

From source file:Main.java

public static String getComboBoxValue(JComboBox comp) {
    String selectedPath = comp.getSelectedItem().toString();
    if (selectedPath == null || !selectedPath.equals(comp.getEditor().getItem())) {
        selectedPath = comp.getEditor().getItem().toString();
    }/*from   w  w  w .  j av a 2  s. co m*/
    return selectedPath;
}

From source file:Main.java

/**
 * When the text is longer than the text box it gets centered, this
 * method ensures they all show the end of the text, eg the filename.
 */// ww w . jav a 2 s.  c  o  m
public static void setCaretPosition(JComboBox comboBox) {
    Object item = comboBox.getSelectedItem();
    if (item != null) {
        String val = item.toString();
        JTextComponent c = (JTextComponent) comboBox.getEditor().getEditorComponent();
        c.setCaretPosition(val.length());
    }
}

From source file:Main.java

/**
 * Check if the JComboBox selection is empty
 * /*from   w w  w. j av  a  2  s  . co  m*/
 * @param input the JComboBox object
 * @return true or false
 */
public static boolean isEmptyStr(javax.swing.JComboBox input) {
    String str = (String) input.getSelectedItem();
    return str == null || "".equals(str.trim());
}

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.  j  av a 2  s.  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 ww . j av a  2 s.c  o  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
 *///w  ww.  j ava 2  s . co  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);
}