Example usage for javax.swing JComboBox setSelectedItem

List of usage examples for javax.swing JComboBox setSelectedItem

Introduction

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

Prototype

@BeanProperty(bound = false, preferred = true, description = "Sets the selected item in the JComboBox.")
public void setSelectedItem(Object anObject) 

Source Link

Document

Sets the selected item in the combo box display area to the object in the argument.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    // Create a read-only combobox
    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);

    cb.setEditable(true);/*from  w  w w.  j a v a2 s .  com*/
    cb.setSelectedItem("item3");
    Object obj = cb.getSelectedItem();

}

From source file:Main.java

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

    Object obj = cb.getSelectedItem();

    cb.setSelectedItem("item2");
    obj = cb.getSelectedItem();//from   www. ja  va 2 s .c om

    cb.setSelectedItem("item3");
    obj = cb.getSelectedItem();
}

From source file:Main.java

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

    String[] list = { "Hello 1", "Hello 2", "Hello 3", "Hello 4" };
    DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(list);
    JComboBox<String> comboBox = new JComboBox<>(model);
    frame.add(comboBox, BorderLayout.NORTH);

    final JTextField textField = new JTextField(30);
    frame.add(textField, BorderLayout.SOUTH);
    frame.add(new JLabel("Type something, then press enter", JLabel.CENTER));

    textField.addActionListener(ae -> {
        String text = textField.getText();
        model.addElement(text);//from  w w  w. j  ava2  s .  co m
        comboBox.setSelectedItem(text);
        textField.setText("");

    });

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    int SIZE = 14;
    String FONT = "Dialog";

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextPane tp = new JTextPane();
    tp.setFont(new Font(FONT, Font.PLAIN, SIZE));
    tp.setPreferredSize(new Dimension(400, 300));
    StyledDocument doc = tp.getStyledDocument();
    Style defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style boldStyle = doc.addStyle("bold", defaultStyle);
    StyleConstants.setBold(boldStyle, true);
    String boldText = "this is bold test";
    String plainText = "this is plain.";

    doc.insertString(doc.getLength(), boldText, boldStyle);
    doc.insertString(doc.getLength(), plainText, defaultStyle);

    JPanel panel = new JPanel();
    panel.add(tp);//from   w  w  w . j av a 2 s  . com

    JComboBox<String> zoomCombo = new JComboBox<String>(
            new String[] { "0.75", "1.00", "1.50", "1.75", "2.00" });
    zoomCombo.addActionListener(e -> {
        String s = (String) zoomCombo.getSelectedItem();
        double scale = new Double(s).doubleValue();
        int size = (int) (SIZE * scale);
        tp.setFont(new Font(FONT, Font.PLAIN, size));
    });
    zoomCombo.setSelectedItem("1.00");
    JPanel optionsPanel = new JPanel();
    optionsPanel.add(zoomCombo);
    panel.setBackground(Color.WHITE);
    frame.add(panel, BorderLayout.CENTER);
    frame.add(optionsPanel, BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
}

From source file:Main.java

/**
 * Thread-friendly wrapper method for <code>JComboBox.setSelectedItem</code>.
 * @param component//from  w w w .ja  v  a 2s .c  o m
 * @param selectedItem
 *
 * @see javax.swing.JComboBox.setSelectedItem(Object)
 * @deprecated
 */
@Deprecated
public static void setSelectedItem(final JComboBox component, final Object selectedItem) {
    Runnable r = new Runnable() {

        public void run() {
            component.setSelectedItem(selectedItem);
        }
    };

    if (EventQueue.isDispatchThread()) {
        r.run();
        return;
    }

    runTask(r, 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 ava 2  s . c o  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   www  . ja v  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
 *///from w ww .  jav  a  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);
}

From source file:cimat.tesis.sna.visualization.ShowLayouts.java

private static JPanel getGraphPanel() {
    g_array = (Graph<? extends Object, ? extends Object>[]) new Graph<?, ?>[graph_names.length];

    Factory<Graph<Integer, Number>> graphFactory = new Factory<Graph<Integer, Number>>() {
        public Graph<Integer, Number> create() {
            return new SparseMultigraph<Integer, Number>();
        }/* ww w. j a va 2  s  .  c o m*/
    };

    Factory<Integer> vertexFactory = new Factory<Integer>() {
        int count;

        public Integer create() {
            return count++;
        }
    };
    Factory<Number> edgeFactory = new Factory<Number>() {
        int count;

        public Number create() {
            return count++;
        }
    };

    g_array[0] = TestGraphs.createTestGraph(false);
    g_array[1] = MixedRandomGraphGenerator.generateMixedRandomGraph(graphFactory, vertexFactory, edgeFactory,
            new HashMap<Number, Number>(), 20, true, new HashSet<Integer>());
    g_array[2] = TestGraphs.getDemoGraph();
    g_array[3] = TestGraphs.createDirectedAcyclicGraph(4, 4, 0.3);
    g_array[4] = TestGraphs.getOneComponentGraph();
    g_array[5] = TestGraphs.createChainPlusIsolates(18, 5);
    g_array[6] = TestGraphs.createChainPlusIsolates(0, 20);

    Graph<? extends Object, ? extends Object> g = g_array[4]; // initial graph

    final VisualizationViewer<Integer, Number> vv = new VisualizationViewer<Integer, Number>(new FRLayout(g));

    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<Integer>(vv.getPickedVertexState(), Color.red, Color.yellow));

    final DefaultModalGraphMouse<Integer, Number> graphMouse = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(graphMouse);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });
    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Layout<Integer, Number> layout = vv.getGraphLayout();
            layout.initialize();
            Relaxer relaxer = vv.getModel().getRelaxer();
            if (relaxer != null) {
                //            if(layout instanceof IterativeContext) {
                relaxer.stop();
                relaxer.prerelax();
                relaxer.relax();
            }
        }
    });

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(((DefaultModalGraphMouse<Integer, Number>) vv.getGraphMouse()).getModeListener());

    JPanel jp = new JPanel();
    jp.setBackground(Color.WHITE);
    jp.setLayout(new BorderLayout());
    jp.add(vv, BorderLayout.CENTER);
    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    // use a renderer to shorten the layout name presentation
    jcb.setRenderer(new DefaultListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });
    jcb.addActionListener(new LayoutChooser(jcb, vv));
    jcb.setSelectedItem(FRLayout.class);

    JPanel control_panel = new JPanel(new GridLayout(2, 1));
    JPanel topControls = new JPanel();
    JPanel bottomControls = new JPanel();
    control_panel.add(topControls);
    control_panel.add(bottomControls);
    jp.add(control_panel, BorderLayout.NORTH);

    final JComboBox graph_chooser = new JComboBox(graph_names);

    graph_chooser.addActionListener(new GraphChooser(jcb));

    topControls.add(jcb);
    topControls.add(graph_chooser);
    bottomControls.add(plus);
    bottomControls.add(minus);
    bottomControls.add(modeBox);
    bottomControls.add(reset);
    return jp;
}

From source file:edu.uci.ics.jung.samples.ShowLayouts.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static JPanel getGraphPanel() {
    g_array = (Graph<? extends Object, ? extends Object>[]) new Graph<?, ?>[graph_names.length];

    Factory<Graph<Integer, Number>> graphFactory = new Factory<Graph<Integer, Number>>() {
        public Graph<Integer, Number> create() {
            return new SparseMultigraph<Integer, Number>();
        }/*from   w w  w.  j av  a  2  s.co m*/
    };

    Factory<Integer> vertexFactory = new Factory<Integer>() {
        int count;

        public Integer create() {
            return count++;
        }
    };
    Factory<Number> edgeFactory = new Factory<Number>() {
        int count;

        public Number create() {
            return count++;
        }
    };

    g_array[0] = TestGraphs.createTestGraph(false);
    g_array[1] = MixedRandomGraphGenerator.generateMixedRandomGraph(graphFactory, vertexFactory, edgeFactory,
            new HashMap<Number, Number>(), 20, true, new HashSet<Integer>());
    g_array[2] = TestGraphs.getDemoGraph();
    g_array[3] = TestGraphs.createDirectedAcyclicGraph(4, 4, 0.3);
    g_array[4] = TestGraphs.getOneComponentGraph();
    g_array[5] = TestGraphs.createChainPlusIsolates(18, 5);
    g_array[6] = TestGraphs.createChainPlusIsolates(0, 20);

    Graph<? extends Object, ? extends Object> g = g_array[4]; // initial graph

    final VisualizationViewer<Integer, Number> vv = new VisualizationViewer<Integer, Number>(new FRLayout(g));

    vv.getRenderContext().setVertexFillPaintTransformer(
            new PickableVertexPaintTransformer<Integer>(vv.getPickedVertexState(), Color.red, Color.yellow));

    final DefaultModalGraphMouse<Integer, Number> graphMouse = new DefaultModalGraphMouse<Integer, Number>();
    vv.setGraphMouse(graphMouse);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });
    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Layout<Integer, Number> layout = vv.getGraphLayout();
            layout.initialize();
            Relaxer relaxer = vv.getModel().getRelaxer();
            if (relaxer != null) {
                //            if(layout instanceof IterativeContext) {
                relaxer.stop();
                relaxer.prerelax();
                relaxer.relax();
            }
        }
    });

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(((DefaultModalGraphMouse<Integer, Number>) vv.getGraphMouse()).getModeListener());

    JPanel jp = new JPanel();
    jp.setBackground(Color.WHITE);
    jp.setLayout(new BorderLayout());
    jp.add(vv, BorderLayout.CENTER);
    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    // use a renderer to shorten the layout name presentation
    jcb.setRenderer(new DefaultListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });
    jcb.addActionListener(new LayoutChooser(jcb, vv));
    jcb.setSelectedItem(FRLayout.class);

    JPanel control_panel = new JPanel(new GridLayout(2, 1));
    JPanel topControls = new JPanel();
    JPanel bottomControls = new JPanel();
    control_panel.add(topControls);
    control_panel.add(bottomControls);
    jp.add(control_panel, BorderLayout.NORTH);

    final JComboBox graph_chooser = new JComboBox(graph_names);

    graph_chooser.addActionListener(new GraphChooser(jcb));

    topControls.add(jcb);
    topControls.add(graph_chooser);
    bottomControls.add(plus);
    bottomControls.add(minus);
    bottomControls.add(modeBox);
    bottomControls.add(reset);
    return jp;
}