Modifications on an item in a JComboBox

Hi everybody !
I have some problems to do some changes on an item contained in a JComboBox. If I know the SelectedItem, can I Modifiy it ? For example : the Object in my ComboBox is a String "Element 1". I want to change it in "Element 2".
How can i do ? I can't solve this problem by myself, because I'm a beginner in the world of java. Thanks for your help and I hope, see you soon !

Here is the program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class foru7 extends JFrame{
JComboBox petList;
{   setDefaultCloseOperation(EXIT_ON_CLOSE);
String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig","Element 1" };
petList = new JComboBox(petStrings);
JButton jb=new JButton("Hai");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if((petList.getSelectedItem()).equals("Element 1")){
               petList.insertItemAt("Element 2",petList.getSelectedIndex() );
               petList.removeItem("Element 1");
getContentPane().add(petList, BorderLayout.NORTH);
getContentPane().add(jb,BorderLayout.SOUTH);
pack();
setVisible(true);
public static void main(String s[]) {
new foru7();
}

Similar Messages

  • How to color an item in a JComboBox?

    I need to color some item of my JComboBox,.
    or color the string text or the background of the single item
    anyone can help me?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        Object[] data = { new ColoredObject(Color.RED,"Hello"),
                          new ColoredObject(Color.BLUE,"World,"),
                          new ColoredObject(Color.CYAN,"These"),
                          new ColoredObject(Color.GREEN,"Are"),
                          new ColoredObject(Color.MAGENTA,"Some"),
                          new ColoredObject(Color.ORANGE,"Colors")
        JComboBox jcb = new JComboBox(data);
        jcb.setRenderer(new ColoredRenderer());
        content.add(jcb, BorderLayout.NORTH);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class ColoredObject {
      Color color;
      Object object;
      public ColoredObject(Color color, Object object) {
        this.color=color;
        this.object=object;
      public Object getObject() { return object; }
      public Color getColor() { return color; }
      public String toString() { return object.toString(); }
    class ColoredRenderer extends DefaultListCellRenderer {
      public Component getListCellRendererComponent(JList list, Object value,
                                                    int index, boolean isSelected,
                                                    boolean hasFocus) {
        Component c = super.getListCellRendererComponent(list, value, index,
            isSelected,hasFocus);
        if (!isSelected && !hasFocus && value instanceof  ColoredObject) {
          c.setBackground(((ColoredObject)value).getColor());
        return c;
    }

  • How do you set new items within a JComboBox that is within a JTable

    I have searched and searched for the answer to this and do not thing there is one. I have a JTable that has 5 columns. 2 of the columns use DefaultCellRenderers where a JComboBox is used. One of the columns has a value of different football positions. The other has a value of the different players. When a user enters a particular position such as Kickers I want all the Kickers to be showin within the Players JComboBox within the table.
    The problem is that I ONLY want the cell to be modified within that row and column that the position was changed. I have found ways to modify the component but it modifies it for the whole Column. I only want it to be modified for the player cell within the row that the Position was modified. Bottom line is that I just want to modify the JComboBox's components.
    If anyone has had this challenge before please advise.

    I'm not sure I fully understood what you wanted. Does the following little program help you?import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumnModel;
    import java.awt.*;
    * User: weebib
    * Date: 29 janv. 2005
    * Time: 23:37:57
    public class FootballTable extends JPanel {
         private static final String[] COLUMN_NAMES = {"Position", "Name"};
         private static final String[] POSITIONS = {"goal", "arriere", "milieu", "avant"};
         private static final String[] GOALS = {"goal1", "goal2", "goal3"};
         private static final String[] ARRIERES = {"arriere1", "arriere2", "arriere3"};
         private static final String[] MILIEUX = {"milieu1", "milieu2", "milieu3"};
         private static final String[] AVANTS = {"avant1", "avant2", "avant3"};
         public FootballTable() {
              super(new BorderLayout());
              DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 10);
              final JTable table = new JTable(model);
              TableColumnModel columnModel = table.getColumnModel();
              columnModel.getColumn(0).setCellEditor(new DefaultCellEditor(new JComboBox(POSITIONS)));
              columnModel.getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox()) {
                   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                        JComboBox nameComboBox = (JComboBox)super.getTableCellEditorComponent(table, value, isSelected, row, column);
                        Object position = table.getValueAt(row, 0);
                        if (position == null) {
                             nameComboBox.setModel(new DefaultComboBoxModel());
                        } else if (position.equals("goal")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(GOALS));
                        } else if (position.equals("arriere")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(ARRIERES));
                        } else if (position.equals("milieu")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(MILIEUX));
                        } else if (position.equals("avant")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(AVANTS));
                        } else {
                             nameComboBox.setModel(new DefaultComboBoxModel());
                        return nameComboBox;
              add(new JScrollPane(table), BorderLayout.CENTER);
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              final JFrame frame = new JFrame(FootballTable.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new FootballTable());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(400, 300);
                        frame.show();
    }Sorry for the French words, I have no idea how they are called in english (and too lazy to search).
    There is another solution. You also can override the table's prepareEditor method and add the relevant code before returning the Component.

  • Problem with setting tooltips for items of a JCombobox

    hi guys,
    I want to set tooltips for items of JComboBox & the code that i have written is given below , but the tooltip text is set for all the items of Nonitindustrycombo but the tooltips remain the same even for Nonitdesgcombo's items.
    Is that we need to refresh the ComboboxRenderer every time ?
    I am not able to trace out the exact reason for this,please if anyone can suggest me something regarding this would be of great use to me.
    class Searchpanel extends JPanel {
    String[] str = null;
    public SearchPanel(){
    Nonitindustrycombo.addItem("--Select--");
    ArrayList NonITindus = ERPModel.getAllNonitIndustry(); //gets all the items(strings) for Nonitindustrycombo
    for (Iterator iter = NonITindus.iterator(); iter.hasNext();) {
    String str = iter.next().toString();
    Nonitindustrycombo.addItem(str);
    SetTooltip(Nonitindustrycombo,NonITindus);
    Nonitdesgcombo.addItem("--Select---");
    ArrayList desg = ERPModel.getAllNonitDesg(); //gets all the items(strings) for Nonitdesgcombo
    for (Iterator iter = desg.iterator(); iter.hasNext();) {
    Nonitdesgcombo.addItem(iter.next());
    SetTooltip(Nonitdesgcombo,desg);
    class MyComboBoxRenderer extends BasicComboBoxRenderer
    public Component getListCellRendererComponent(JList list, Object value,
    int index, boolean isSelected,
    boolean cellHasFocus)
    if (isSelected)
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    if (0 < (index))
    list.setToolTipText(str[index - 1]);
    else
    setBackground(list.getBackground());
    setForeground(list.getForeground());
    setFont(list.getFont());
    setText((value == null) ? "" : value.toString());
    return this;
    private void SetTooltip(JComboBox combo,ArrayList arr){
    str = (String []) arr.toArray (new String [arr.size ()]);
    combo.setRenderer(new MyComboBoxRenderer());
    public static void main(String[] args){
    new SearchPanel();
    Thanks ,
    vishal

    1) You where given a working example in your last posting on this topic. Compare your code with the working code to see whats different and fix it.
    2) The code you posted doesn't compile.
    3) You didn't use the "Code Formatting Tags" when you posted your code so it not readable.

  • How to edit an item in a JComboBox

    I want the user to be able to edit an item in a combobox box. You select an item, edit in the top, press enter, and viola, the item is renamed.
    I've tried some approaches but they're not working out. Thanks for any ideas. What's the point of having an editable combobox if it doesn't EDIT?!

    Hi,
    should be as easy as:
    String[] patternExamples = {
          "dd MMMMM yyyy",
          "dd.MM.yy",
          "MM/dd/yy",
          "yyyy.MM.dd G 'at' hh:mm:ss z",
          "EEE, MMM d, ''yy",
          "h:mm a",
          "H:mm:ss:SSS",
          "K:mm a,z",
          "yyyy.MMMMM.dd GGG hh:mm aaa"
    JComboBox patternList = new JComboBox(patternExamples);
    patternList.setEditable(true);
    patternList.addActionListener(...);

  • Changing a item in a JComboBox

    I must change the text in the JComboBox of an Item at the runtime. Is theree a way to change it without delating and adding it new?
    Greatings
    Sven

    Note that this has anything to do with Swing, but rather with the fact that Strings are immutable. Also note that you can put other things than Strings in a combobox, and if you put something that is mutable in there you should be able to change its appearance in the combobox without deleting and re-adding it.

  • Programatic item events in JComboBox

    I have three JComboBoxes. Each has an ItemListener which calls setCustomerFields.
    public void setCustomerFields(ItemEvent e)
    JComboBox aComboBox = (JComboBox) e.getSource();
    int aIndex = aComboBox.getSelectedIndex();
    myAddressComboBox.setSelectedIndex(aIndex);
    myCustNameComboBox.setSelectedIndex(aIndex);
    myCustNumComboBox.setSelectedIndex(aIndex);
    Each JComboBox looks something like:
    myAddressComboBox = new JComboBox(myAddresses);
    myAddressComboBox.setEditable(true);
    myAddressComboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent e) {
    setCustomerFields(e); } } );
    The purpose is to have all three JCombBoxes stay in sync. When the user selects a value in one setCustomerFields will set the value in the others. The API documentation for JComboBox.addItemListener states addItemListener Specified by: addItemListener in interface ItemSelectable. ItemSelectable Method Details for addItemListener says "Adds a listener to receive item events when the state of an item is changed by the user. Item events are not sent when an item's state is set programmatically. If l is null, no exception is thrown and no action is performed."
    This tells me that "item events are not sent when an item's state is set programmatically." So calling setSelectedIndex in setCustomerFIields should not send an Iterm event. BUT IT IS. And thus I get an endless loop.
    My work around is to call removeItermListener in setCustomerFields.
    I have looked through the forum and found some similar questions but no definitive answer (except call removeItemListener) Also I see reference to a bug http://developer.java.sun.com/developer/bugParade/bugs/4664606.html which is similar but not directly related.
    So my questions:
    1) Am I using ItemListener correctly?
    2) If so why is the Item Event occurring in setCustomerField?
    3) Is the documentation wrong?
    4) I choice ItemListener over ActionListener because ItemListener "isn't" supposed to fire when the state changes programatically. Was that the correct choice?
    Thanks
    Brad

    ItemEvent should send when ever setSelectedIndex call, but you can do one thing :
    public void itemStateChanged(ItemEvent e) {
    if( e.getStateChange() == ItemEvent.SELECTED ){
    setCustomerFields(e); }
    may be this will work from your situation, or i guess you can use some flags type too for checking which one combobox changed then do appropriate action for this.

  • Setting color of an item in a Jcombobox in a JTable when editing

    Hello,
    I have a situation where I have a JCombobox in a JTable . The JCombobox is non-editable. The items within the combobox are colored in pink or blue in order to help the user differentiate between the two categories that are in the list.
    But the problem is that when the user is on that cell and is just typing the first letter(s) in the combobox, he does see the item starting with that letter(s) but that item is not shown as colored. However, if the user clicks on the combobox with a mouse, the list pops-up and the items are shown as colored. I want the first part to work where the user can just use keyboard and see the items as colored in that cell itself. By default, currently when the row is selected the foreground is white and background is black. I want that particularly when this combobox has focus and an item is selected, the foreground should be of the same color as the color of the item.
    Can someone help?
    Thanks a lot in advance.

    Additional information on above:
    I associate a customized renderer with the column of my table for which i want to set the colors.
    TableColumn tc6 = jTableDRS.getColumnModel().getColumn(myDRSModel.FINANCECODE_COLUMN);
    tc6.setCellRenderer(new ColorRenderer());
    here is the renderer that I am using...
    public class ColorRenderer extends JLabel implements TableCellRenderer {
    protected Border noFocusBorder;
    public ColorRenderer() {
    noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    Color foreground = null;
    Color background = null;
    Font font = null;
    if(column == myDRSModel.FINANCECODE_COLUMN)
    setFont((font != null) ? font : table.getFont());
    String str = (String)value.toString();
    if (!str.equalsIgnoreCase("SELECT ONE")) {
    int y = financedesc.indexOf(str);
    if((payreceiveind.get(y).toString()).equals("R")){
    setForeground(Color.RED);
    } else if((payreceiveind.get(y).toString()).equals("P")){
    setForeground(new Color(147,112,240));
    if(isSelected)
    if((payreceiveind.get(y).toString()).equals("R")){
    setForeground(Color.RED);
    } else if((payreceiveind.get(y).toString()).equals("P")){
    setForeground(new Color(147,112,240));
    setBackground(table.getSelectionBackground());
    else{
    setBackground(table.getBackground());
    else
    if(isSelected)
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    setValue(value);
    return this;
    protected void setValue(Object value) {
    setText((value == null) ? "" : value.toString());
    }

  • AddItem() adds item to all JComboBoxes

    I dynamically generate a series of JComboBoxes using a loop.
    inside my loop i test if a certain condition is true, if true i add an item.
    The problem is that when the condition tests true, the item I add is added to all my dynamically generated JComboBoxes.
    Hopefully some fresher eyes can spot my error.
    thanks in advance,
    Pete
    Here's the offending code:
    for(int i = 0; i < counter; ++i)
    unitField[i] = new JTextField(5);
    boxWeights[i] = new JComboBox(vecWeightText);
    String tempName = FCProItem.ingredients.getNameOfIngredient();
    lblIngredients[i] = new JLabel(tempName);
    if(FCProItem.ingredientsi].hasConversiontempName,FCProMenuItem.CONVERSION_FILE_PATH_TEST) )
    System.out.println("Add conversion to combo-box for: " + FCProItem.ingredients[i].getNameOfIngredient());
    Vector hold = FCProItem.ingredients[i].getIngredientConversions(tempName);
         for(int z = 0; z < hold.size(); z++)
         if(z % 3 == 0)
         boxWeights[i].addItem(hold.elementAt(z));
    .... more code...

    In my efforts to solve this I've ruled out as mcu as i can think of.
    My problem remains, however, slightly improved. Now I add the correct items, yet still to very JComboBox.
    Latest code:
    for(int i = 0; i < counter; ++i)
                   unitField[i] = new JTextField(5);
                   boxWeights[i] = new JComboBox(vecWeightText);
                   String tempName = FCProItem.ingredients.getNameOfIngredient();
                   lblIngredients[i] = new JLabel(tempName);
                   boolean flag = FCProItem.ingredients[i].hasConversion(tempName, FCProMenuItem.CONVERSION_FILE_PATH_TEST);
                   if( flag )// we have a conversion
                             Vector hold = FCProItem.ingredients[i].getIngredientConversions(tempName);
                             for(int z = 0; z < hold.size(); z=z+2)
                                  boxWeights[i].addItem(hold.elementAt(z));

  • Select same item (AGAIN) in JComboBox

    I don't know, if it's feature or bug :) But JCombobox do not "fire action" when I select same item again (value, which is already selected). But i need to call action ALWAYS when user select some item, even if he select already selected item. Anyone knows how to do it? Thanx

    Bug,... well, try this...
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class jComboBoxAction extends JPanel  {
    JComboBox jc;
        public  jComboBoxAction() {
          jc = new JComboBox();
          jc.addItem("France");
          jc.addItem("Germany");
          jc.addItem("Italy");
          jc.addItem("Japan");
          add(jc);
          jc.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            System.out.println(""+jc.getSelectedItem());
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new  jComboBoxAction());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
    }

  • Modification of menu items HTML

    Does somebody know, how to modify menu item rendering in oracle UCM 11g?
    In previous version, 10g, I used to make in using menuA_MenuItem_OpeningHtml(node, nodeLocation), menuA_MenuItem_CoreHtml(node, nodeLocation), menuA_MenuItem_ClosingHtml(node, nodeLocation) javascript methods in my custom layout.js template, but in the 11th version those methods are not fired. Menu items itself are rendered as DIV wish UL element in it, I would like to have another HTML markup there. Is it any option to do than in a simple way?

    Hello, Jiri, the tutorial you've sent makes 100% clear how to add items into menuA or MenuB, but it still does not explain, hot to change menu item rendering. Yahoo  interface library generates UL/LI elements for the main menu, but in case I would like to have a table instead of LIs, what modifications need to be done, that's a question. But may be I just cannot read. Will go through the example one more time.

  • "Payment Terms(VBKD-ZTERM)"  Modification at Order item Level

    Hi,
    I want to modify Payment terms(VBKD-ZTERM) at Order Item Level when user hit "SAVE" button while creating(VA01) OR changing(VA02) the Order.
    I am using User Exit "MOVE_FIELD_TO_VBKD" for the same.
    Has anybody worked on the same requirement before.
    can anybody help me out in this regard.
    thanks in advance.
    Nitin

    Hi Anji Reddy,
    I had similar problem and i coded like below but it is not working ...so can u provide any sample code related to this or please correct me in the below code ..where exactly i am doing mistake...
    The requirements is as like below and please guide me where i am doing mistake in below coiding.
    If sales order required delivery date (VBAK-VDATU) is LT Document create date7days(SY-DATUM7) and next condition is
    item required delivery date (VBEP-EDATU) is LT the Document create date 7days(SY-DATUM7)
    then we need to move '0001' TO VBKD-ZTERM(Payment terms)
    ELSE move the payments terms as in the customer master (kurgv-zterm).
    now i am getting the error as :
    Header business data does not apply ti item 000020.
    Please find the code below and guide me where i am doing mistake.
    Ihad coded in program : MV45AFZZ ---> FORM USEREXIT_MOVE_FIELD_TO_VBKD.
    DATA: chk_date  TYPE vbep-edatu.
        CLEAR chk_date.
        chk_date = sy-datum + 7.
        CHECK : NOT vbak-vdatu IS INITIAL.
        IF vbak-vdatu < chk_date.
           CHECK : NOT vbap-posnr IS INITIAL.
           CHECK : NOT vbep-edatu IS INITIAL.
           IF vbep-edatu < chk_date.
              vbkd-zterm = '0001'.
           ELSE.
              vbkd-zterm = kurgv-zterm.
           ENDIF.
        ENDIF.
    Thanks in advance
    Srinivas
    Edited by: Srinivas on Aug 21, 2008 12:57 AM

  • How to invoke an event when i select one of the items in my JComboBox

    Can any one help me for doing this,i have a combobox in a panel,when i select one item in the combobox some text fields below the combobox need to be disabled,that disabled components vary with the item selected,i try to do this by using event listener but some how i could not get invoke the event,pl some one help me for this,any help would be appreciated.
    Regards.

    The block:
    ivjJComboBox1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    ivjJComboBox1_mouseClicked(e);
    usually should be included in your constructor or init method.
    The method:
    void ivjJComboBox1_mouseClicked(MouseEvent e){
    String s = (String)ivjJComboBox1.getSelectedItem();
    System.out.println(s);
    should be outside your constructor or init method.
    So it should be:
    public class yourClassName extends xxxxx implements xxxxx
    public yourClassName (...) {
    ivjJComboBox1.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    ivjJComboBox1_mouseClicked(e);
    void ivjJComboBox1_mouseClicked(MouseEvent e){
    String s = (String)ivjJComboBox1.getSelectedItem();
    System.out.println(s);

  • Different JCombobox items in JTable for the same column

    Hello Everyone,
    I am reading from a file and displaying in a JTable. I want all cells in a specific column to be JComboBoxes but the items in the JComboBox differ from one cell to another, how can this be achieved?
    The following is a snippet from the Sun tutorials,
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    And hence every cell in the sportColumn has the exact same set of options in the JComboBox which is not what I want since I read from an external file.
    Any help or sample code would be highly appreciated.
    Thank you in advance

    Override getCellEditor(int row, int column) in JTable to control which editor gets used for which cell.

  • How to select multiple items in JComboBox

    Is it possible to select multiple items in a JComboBox
    if yes, then how to do?
    If no , then is there any other way to acheieve this ?

    Hi
    ComboBoxModel extends ListModel and not ListSelectionModel, so i think JComboBox does not provide multiple selection. But u can try customizing ur combo box.. may be its possible.. not very sure
    Shailesh

Maybe you are looking for