Example usage for javax.swing JComboBox getItemCount

List of usage examples for javax.swing JComboBox getItemCount

Introduction

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

Prototype

@BeanProperty(bound = false)
public int getItemCount() 

Source Link

Document

Returns the number of items in the list.

Usage

From source file:Main.java

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

    cb.removeItemAt(cb.getItemCount() - 1);
}

From source file:Main.java

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

    // Get number of items
    int num = cb.getItemCount();

    // Get items//from   ww  w.ja va  2s  . c  o m
    for (int i = 0; i < num; i++) {
        Object item = cb.getItemAt(i);
    }
}

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
    JComboBox<String> comboBox = new JComboBox<>(labels);
    comboBox.setEditable(true);//from  www .  j  av a2 s. co  m

    comboBox.addActionListener(new ActionListener() {
        boolean found = false;

        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            String s = (String) comboBox.getSelectedItem();
            for (int i = 0; i < comboBox.getItemCount(); i++) {
                if (comboBox.getItemAt(i).toString().equals(s)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                System.out.println("Added: " + s);
                comboBox.addItem(s);
            }
            found = false;
        }
    });

    frame.add(comboBox);

    frame.pack();
    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  www .  j  ava  2 s .  c  o 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 boolean isValidIndex(JComboBox<?> comboBox, int index) {
    if (comboBox == null) {
        throw new NullPointerException("comboBox == null");
    }//  w w w  .j  av a2  s  . c  om
    int itemCount = comboBox.getItemCount();
    return index >= 0 && index < itemCount;
}

From source file:com.eviware.soapui.utils.ContainerWalker.java

public <T> JComboBox findComboBoxWithValue(T value) {
    for (Component component : containedComponents) {
        if (component instanceof JComboBox) {
            JComboBox comboBox = (JComboBox) component;
            for (int i = 0; i < comboBox.getItemCount(); i++) {
                if (comboBox.getItemAt(i).equals(value)) {
                    return comboBox;
                }/*from  ww w .j a  va 2 s .  c  om*/
            }
        }
    }
    throw new NoSuchElementException("No combo box found with item " + value);
}

From source file:Main.java

public void actionPerformed(ActionEvent e) {
    JComboBox jcb = (JComboBox) e.getSource();
    System.out.println("down action");
    ComboBoxUI ui = jcb.getUI();/*from w w w .j a  v a2  s.c o m*/

    if (ui.isPopupVisible(jcb)) {
        int i = jcb.getSelectedIndex();
        if (i < jcb.getModel().getSize() - 1) {
            jcb.setSelectedIndex(i + 1);
            jcb.repaint();
        }
    } else {
        int nItems = jcb.getItemCount();

        ComboBoxEditor cbe = jcb.getEditor();

        String st; // Search text

        st = ((String) cbe.getItem()).toUpperCase();

        for (int i = 0; i < nItems; i++) {
            String item = ((String) jcb.getItemAt(i)).toUpperCase();

            if (item.startsWith(st)) {
                jcb.setSelectedIndex(i);
                break;
            }
        }

        ui.setPopupVisible(jcb, true);
    }
}

From source file:carfuzzy.Operations.java

public double getMembership(JComboBox s, int input) {
    double membership;
    if (s.getSelectedIndex() == 0) { //veryslow ya da veryclose ise(left Trapezoid)
        if (s.getSelectedItem().getClass() == Speed.class) {
            speed = (Speed) s.getSelectedItem();
            membership = leftTrapezoidalMembership(input, speed.getValue());
            return membership;
        } else {// w ww  . jav a 2s . c  om
            distance = (Distance) s.getSelectedItem();
            membership = leftTrapezoidalMembership(input, distance.getValue());
            return membership;

        }
    } else if (s.getSelectedIndex() == s.getItemCount() - 1) { //veryfast ya da away ise(right Trapezoid)
        if (s.getSelectedItem().getClass() == Speed.class) {
            speed = (Speed) s.getSelectedItem();
            membership = rightTrapezoidalMembership(input, speed.getValue());
            return membership;
        } else {
            distance = (Distance) s.getSelectedItem();
            membership = rightTrapezoidalMembership(input, distance.getValue());
            return membership;
        }

    } else { // Triangular ise
        if (s.getSelectedItem().getClass() == Speed.class) {
            speed = (Speed) s.getSelectedItem();
            membership = triangularMembership(input, speed.getValue());
            return membership;
        } else {
            distance = (Distance) s.getSelectedItem();
            membership = triangularMembership(input, distance.getValue());
            return membership;
        }
    }
}

From source file:king.flow.action.DefaultMsgSendAction.java

protected void showDoneMsg(final TLSResult result) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override/*from  w ww  . ja  v  a  2 s  .c o  m*/
        public void run() {
            if (doneDisplayList.size() == 1) {
                showOnComponent(getBlockMeta(doneDisplayList.get(0)), result);
            } else {
                try {
                    JSONParser jsonParser = new JSONParser();
                    Object element = jsonParser.parse(result.getOkMsg());
                    if (element instanceof JSONArray) {
                        JSONArray jsonArray = (JSONArray) element;
                        int len = Integer.min(doneDisplayList.size(), jsonArray.size());
                        for (int i = 0; i < len; i++) {
                            TLSResult freshResult = new TLSResult(result.getRetCode(),
                                    jsonArray.get(i).toString(), result.getErrMsg(), result.getPrtMsg());
                            showOnComponent(getBlockMeta(doneDisplayList.get(i)), freshResult);
                        }
                    } else {
                        showOnComponent(getBlockMeta(doneDisplayList.get(0)), result);
                    }
                } catch (Exception e) {
                    getLogger(DefaultMsgSendAction.class.getName()).log(Level.WARNING,
                            "Exception encounters during successful json value parsing : \n{0}", e);
                }
            }

            CommonUtil.cachePrintMsg(result.getPrtMsg());
            if (result.getRedirection() != null) {
                String redirection = result.getRedirection();
                getLogger(DefaultMsgSendAction.class.getName()).log(Level.INFO,
                        "Be forced to jump to page[{0}], ignore designated page[{1}]",
                        new Object[] { redirection, String.valueOf(next.getNextPanel()) });
                int forwardPage = 0;
                try {
                    forwardPage = Integer.parseInt(redirection);
                } catch (Exception e) {
                    panelJump(next.getNextPanel());
                    return;
                }
                Object blockMeta = getBlockMeta(forwardPage);
                if (blockMeta == null || !(blockMeta instanceof Panel)) {
                    getLogger(DefaultMsgSendAction.class.getName()).log(Level.INFO,
                            "Be forced to jump to page[{0}], but page[{0}] is invalid Panel type. It is type[{1}]",
                            new Object[] { redirection,
                                    (blockMeta == null ? "NULL" : blockMeta.getClass().getSimpleName()) });
                    panelJump(next.getNextPanel());
                    return;
                }
                panelJump(forwardPage);
            } else {
                panelJump(next.getNextPanel());

                //trigger the action denoted in sendMsgAction
                Integer trigger = next.getTrigger();
                if (trigger != null && getBlockMeta(trigger) != null) {
                    final Component blockMeta = (Component) getBlockMeta(trigger);
                    switch (blockMeta.getType()) {
                    case COMBO_BOX:
                        JComboBox comboBlock = getBlock(trigger, JComboBox.class);
                        ItemListener[] itemListeners = comboBlock.getItemListeners();
                        ItemEvent e = new ItemEvent(comboBlock, ItemEvent.ITEM_STATE_CHANGED,
                                comboBlock.getItemAt(comboBlock.getItemCount() - 1).toString(),
                                ItemEvent.SELECTED);
                        for (ItemListener itemListener : itemListeners) {
                            itemListener.itemStateChanged(e);//wait and hang on util progress dialog gets to dispose
                        }
                        if (comboBlock.isEditable()) {
                            String value = comboBlock.getEditor().getItem().toString();
                            if (value.length() == 0) {
                                return;
                            }
                        }
                        break;
                    case BUTTON:
                        JButton btnBlock = getBlock(trigger, JButton.class);
                        btnBlock.doClick();
                        break;
                    default:
                        getLogger(DefaultMsgSendAction.class.getName()).log(Level.WARNING,
                                "Invalid trigger component[{0}] as unsupported type[{1}]",
                                new Object[] { trigger, blockMeta.getType() });
                        break;
                    }
                } //trigger dealing 
                  //keep next cursor on correct component
                Integer nextCursor = next.getNextCursor();
                if (nextCursor != null && getBlockMeta(nextCursor) != null) {
                    JComponent block = getBlock(nextCursor, JComponent.class);
                    block.requestFocusInWindow();
                }
            } // no redirection branch
        }
    });
}

From source file:ch.admin.hermes.etl.load.HermesETLApplication.java

/**
 * CommandLine parse und fehlende Argumente verlangen
 * @param args Args// w  w  w  .  j a  v a 2s .c  o m
 * @throws ParseException
 */
private static void parseCommandLine(String[] args) throws Exception {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

    // HACK um UTF-8 CharSet fuer alle Dateien zu setzen (http://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding)
    System.setProperty("file.encoding", "UTF-8");
    Field charset = Charset.class.getDeclaredField("defaultCharset");
    charset.setAccessible(true);
    charset.set(null, null);

    // commandline Options - FremdsystemSite, Username und Password
    Options options = new Options();
    options.addOption("s", true, "Zielsystem - URL");
    options.addOption("u", true, "Zielsystem - Username");
    options.addOption("p", true, "Zielsystem - Password");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    site = cmd.getOptionValue("s");
    user = cmd.getOptionValue("u");
    passwd = cmd.getOptionValue("p");

    // restliche Argumente pruefen - sonst usage ausgeben
    String[] others = cmd.getArgs();
    if (others.length >= 1 && (others[0].endsWith(".js") || others[0].endsWith(".ftl")))
        script = others[0];
    if (others.length >= 2 && others[1].endsWith(".xml"))
        model = others[1];

    // Dialog mit allen Werten zusammenstellen
    JComboBox<String> scenarios = new JComboBox<String>(crawler.getScenarios());

    JTextField tsite = new JTextField(45);
    tsite.setText(site);
    JTextField tuser = new JTextField(16);
    tuser.setText(user);
    JPasswordField tpasswd = new JPasswordField(16);
    tpasswd.setText(passwd);
    final JTextField tscript = new JTextField(45);
    tscript.setText(script);
    final JTextField tmodel = new JTextField(45);
    tmodel.setText(model);

    JPanel myPanel = new JPanel(new GridLayout(6, 2));
    myPanel.add(new JLabel("Szenario (von http://www.hermes.admin.ch):"));
    myPanel.add(scenarios);

    myPanel.add(new JLabel("XML Model:"));
    myPanel.add(tmodel);
    JPanel pmodel = new JPanel();
    pmodel.add(tmodel);
    JButton bmodel = new JButton("...");
    pmodel.add(bmodel);
    bmodel.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model = getFile("Szenario XML Model", new String[] { "XML Model" }, new String[] { ".xml" });
            if (model != null)
                tmodel.setText(model);
        }
    });
    myPanel.add(pmodel);

    scenarios.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            try {
                Object o = e.getItem();
                tmodel.setText(crawler.getModelURL(o.toString()));
                scenario = o.toString();
            } catch (Exception e1) {
            }
        }
    });

    // Script
    myPanel.add(new JLabel("Umwandlungs-Script:"));
    JPanel pscript = new JPanel();
    pscript.add(tscript);
    JButton bscript = new JButton("...");
    pscript.add(bscript);
    myPanel.add(pscript);
    bscript.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            script = getFile("JavaScript/Freemarker Umwandlungs-Script",
                    new String[] { "JavaScript", "Freemarker" }, new String[] { ".js", ".ftl" });
            if (script != null)
                tscript.setText(script);
        }
    });

    // Zielsystem Angaben
    myPanel.add(new JLabel("Zielsystem URL:"));
    myPanel.add(tsite);
    myPanel.add(new JLabel("Zielsystem Benutzer:"));
    myPanel.add(tuser);
    myPanel.add(new JLabel("Zielsystem Password:"));
    myPanel.add(tpasswd);

    // Trick um Feld scenario und model zu setzen.
    if (scenarios.getItemCount() >= 8)
        scenarios.setSelectedIndex(8);

    // Dialog
    int result = JOptionPane.showConfirmDialog(null, myPanel, "HERMES 5 XML Model nach Fremdsystem/Format",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        site = tsite.getText();
        user = tuser.getText();
        passwd = new String(tpasswd.getPassword());
        model = tmodel.getText();
        script = tscript.getText();
    } else
        System.exit(1);

    if (model == null || script == null || script.trim().length() == 0)
        usage();

    if (script.endsWith(".js"))
        if (site == null || user == null || passwd == null || user.trim().length() == 0
                || passwd.trim().length() == 0)
            usage();
}