JComboBox selected value

Hi,
I have a JComboBox and I need to be notified if the selected item (or index) has changed. How can I do that?
Thanks a bunch

Use the addItemListener() method and add an item listener to the JComboBox. This will tell you when the selection changes.
Mitch Goldstein
Author, Hardcore JFC (Cambridge Univ Press)
[email protected]

Similar Messages

  • How to clear the selected values in the JCombobox

    Hi All,
    Can you please tell - how to clear the selected values in the JCombobox
    I have four dropdowns in my application, When I click "CLEAR" button, what ever the values selected in the four drop downs should go off and view as "SELECT" in all the dropdowns.

    In addition to the above you should also check out [Combo Box Prompt|http://www.camick.com/java/blog.html?name=combo-box-prompt] which makes it easy to display the default prompt.

  • JComboBox : colors in the selected value field

    I have a JComboBox with a custom ListCellRenderer. However the JComboBox seems to change the colors of the Component that my ListCellRenderer creates when the Component is in the Selected value field. Some code is below...
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class ComboBoxTest {
      public static final void main(String[] args) {
        JComboBox cbox;
        Vector elements;
        elements = new Vector();
        elements.add("One");
        elements.add("Two");
        elements.add("Three");
        cbox = new JComboBox(elements);
        cbox.setRenderer(new MyRenderer());
        cbox.setEditable(false);
        JFrame frame = new JFrame();
        JPanel content = (JPanel) frame.getContentPane();
        content.add(cbox);
        frame.pack();
        frame.setVisible(true);
    class MyRenderer implements ListCellRenderer {
      public Component getListCellRendererComponent(
        JList list,
        Object value,
        int index,
        boolean isSelected,
        boolean cellHasFocus)
        String strValue;
        JLabel label;
        strValue = (String) value;
        label = new JLabel("<" + strValue + ">");
        label.setOpaque(true);
        if( isSelected ) {
          label.setForeground(Color.black);
          label.setBackground(Color.green);
        } else {
          label.setForeground(Color.white);
          label.setBackground(Color.black);
        return label;
    }This code simply creates a JComboBox with 3 String values, "One", "Two", and "Three". The renderer creates a JLabel with the String value enclosed in triangle brackets. The renderer also sets the colors of the JLabel to white on black if unselected and black on green if selected.
    When I run this program, the list portion of the JComboBox looks correct, but the entry in the edit field is wrong. It has the enclosing triangle brackets around the selected String, but the colors are still the default black on gray.
    What do I need to do to get the colors in the edit field to display correctly?
    - James

    A JComboBox is similar to a JSpinner in the sense that it has an associated editor that has an associated textfield....check out the link shown below
    http://forum.java.sun.com/thread.jsp?forum=57&thread=385077
    ;o)
    V.V.

  • Problem in JComboBox selected Index change

    hi all
    Can anyone send me the code for Loading values to JComboBox & then i want to Display Particular value for that Loaded value in JTextField.
    Ex:
    I loaded category cade for JComboBox & when JComboBox selected index change the particular category name should appear in JTextBox
    Thankz

    Hi,
    I am sending a sample program.
    Try this, if u had any problem just mail me at [email protected]
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SwingDemo extends JFrame implements ItemListener
         JComboBox combo;
         JTextField text;
         Properties props;
         public SwingDemo() throws Exception
              super();
              combo=new JComboBox();
              text=new JTextField();
              addItems("combodata.dat");
              setLayout(new GridLayout(2,1));
              add(combo);
              add(text);
              combo.addItemListener(this);
              setTitle("JComboBox - Demo");
              setSize(400,400);
              setVisible(true);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) throws Exception
              new SwingDemo();
         public void addItems(String str) throws Exception
              FileInputStream fis=new FileInputStream(str);
              props=new Properties();
              props.load(fis);
              Enumeration e=props.propertyNames();
              while(e.hasMoreElements())
                   combo.addItem((String)e.nextElement());
         public void itemStateChanged(ItemEvent ie)
              //System.out.println(ie.getSource());
              //System.out.println((ie.getSource()==combo));
              if(ie.getSource()==combo)
                   System.out.println(combo.getSelectedItem());
                   System.out.println(props.getProperty(combo.getSelectedItem().toString()));
                   text.setText(props.getProperty(combo.getSelectedItem().toString()));
                   pack();
    For the above program I took data from a file instead of the database
    You have to create that file to execute the above program with the name combodata.dat and the values as follwos
    1=BSc
    2=BCA
    3=BA/BCom
    4=MSc(IS)
    5=MSc(Cs)
    6=MCA
    7=BE/BTech
    8=MBA
    Bye...
    Thanks & Regards,
    Santhosh Reddy Mandadi

  • Getting the last selected value of the combo  - very very urgent...........

    On my panel i have a jcombobox in upper half(which displays say the address type.) and few text fields on the lower half(which displays the add details). when the user selects a value in the combo box the text fields are populated based on the selection. The user can change the values displayed in the text fields. So before setting the new values in the text fields the last displayed values need to be saved.
    I have an ActionListener for my combo which gives me the currently selected value by calling getSelecetdItem()
    How can i get the last selcted value of the combobox without using any variable of my own.

    To update the last displayed details(the address details say) i need to check what type of address the combo had previousely.....
    when i display the panel first time the home address is set by default and i have a variable to hold this value..as the user changes the selection i update the variable...I don't want to use this variable..instead if i can get the last selcted value from the event that would be great...
    thanks

  • ADF  Get selected values from Dynamic Lists

    Hi,
    I have a created a dropdown list box where the list gets value through a managed bean. On commit I want the selected value to be saved into the CardiacV1EchoSched column of the Entity object (database). The source looks like this.
    <af:selectOneChoice value="#{bindings.CardiacV1EchoSched.inputValue}"
    label="#{bindings.CardiacV1EchoSched.label}"
    valuePassThru="true">
    <f:selectItems value="#{TTrack.carScheList}"/>
    </af:selectOneChoice>
    The problem is that getCardiacV1EchoSched() in the entity object class is null. The selected value does not get passed into #{bindings.CardiacV1EchoSched.inputValue} at all. If I bind the value to a variable in managed bean I get the selected value.
    Thanks in advance,

    Hi,
    not sure which business service you use to update the database, but if you use ADF Business Components then you need to call the commit operation
    Frank

  • Error while attaching document to report on Portal - Invalid selection valu

    Hello All,
    We are running our reports on Portal and as per the business requirement the users have to create comments or attach documents to certain amounts in certain columns and once they create the comment a document icon shows up near that amount (for example there are 3 columns Budget, actual, balance then the user have to create comment for some amounts which needs explanation) they do that from context menu  Documents -> Create new Comment.
    Now we want those documents to be saved on Infoprovider level and not on master data for any particular object. We have activated the flag "Characteristic is document property" on related infoobjects. We have the flag to display document icon on Infoprovider active in the web template. Now when I run the report I am able to create new comments on first two columns and when the report refreshes it shows me icon near that amount but it gives me errors on third column after the report refreshes itself. Now when I go in portal KM repository where documents are stored I do see the document that I created for the third column as well so looks like the document is getting created and being stored but the issue is when it tries to display the icon on that third column.
    The error I get is this:
    The initial exception that caused the request to fail was:
    Invalid selection value:  AttributeMember
    com.sap.ip.bi.bics.dataaccess.resource.impl.bi.exceptions.BicsResourceBwRuntimeException: Invalid selection value:  AttributeMember
    at com.sap.ip.bi.bics.dataaccess.resource.impl.bi.selector.selection.ProviderRange.setLowForced(ProviderRange.java:297)
    at com.sap.ip.bi.bics.dataaccess.resource.impl.bi.selector.selection.ProviderRange.setLow(ProviderRange.java:291)
    at com.sap.ip.bi.bics.dataaccess.resource.impl.bi.selector.selection.ProviderRange.set(ProviderRange.java:469)
    at com.sap.ip.bi.bics.dataaccess.consumer.impl.selector.selection.SingleMember.set(SingleMember.java:125)
    at com.sap.ip.bi.km.common.assignment.AssignmentMember.isContained(AssignmentMember.java:192)
    Please give some inputs if anyone is facing same problem or is anyone has worked previously with this kinda of stuff.
    Thanks in advance.
    Kiran

    Hi!
    Have you solved this problem? I have the same problem after a SPS implementation (SPS 17). The message appears when we select a single value in a DP (hierarchical filter item) that filters another one, but when I select a node it doesn't.
    Before the patch implementation the apliccation worked ok.
    Any idea?
    Thanks in advance.
    Jose

  • How to refresh page after selecting value from LOV item , in a tabular form

    Hi ,
    I have a tabular form, which contains 2 items(columns), of type "Select List - named LoV".
    Now, couple of issues here.
    1.
    2nd item(column) in tabular form, that LoV should get populated based user's selection value in first item LoV. So how do i refer to the value, that user selected in first item's LoV? I will have to use this reference in LoV query of my 2nd item ( on this tabular form)
    2.
    How can we refresh the page, when user selectes value in first item ( from LoV). As this is a tabular form, here item type is Select List, we dont have an option to pick item type as Select List with Submit. So problem is that when user selects value for item 1, refresh does not happen and item 2 LoV does not get populated as per user's selection in item 1.
    Please help here. Would be really appreciated.
    Thanks and Regards,
    Rave.

    Thanks Ben and Dan for your responses.
    Ben, your solution helped me with refresh of page, as page got submitted.
    This answers to my 2nd question. However, I still need to know first question, which basically is, how do i refer to the value, that user selected in first item LoV.
    Issue is, I selected the value in first item LoV, it got submitted and page fot refreshed. But after page refresh, first item LoV loses its value that I had selected last time. It does not retain the selected value after refresh.
    I have an unconditional process, that on every submit(refresh) of page, I set my items with their corresponding values. But problem is what do i mention there to refer to this item.
    I looked in view source of my page, this item is referred as f03.
    So i used "apex_application.g_f03", to set this item to its value, in my uncoditional submit process. But it did not work. I tried to refer this item as "f03" in this unconditional submit process. But still it did not help, the selected item loses its value after page refresh(submit).
    Any help here would be really appreciated. Please suggest how do we refer to this item's selected value.
    Thanks and Regards,
    Ravi.

  • Unable to set the selected value for a ADF LOV

    Hi,
    I am developing an application using jdeveloper 10.1.3 and Struts.
    I have created a ADF LOV on my JSP Page as given below:
    <html:select property="lob" onchange="javascript:selectLOB(this.form)">
    <html:optionsCollection label="prompt" value="index" property="lob.displayData"/>
    </html:select>
    When i submit the form, i am able to get the value of the selected Value in the List.
    JUCtrlListBinding listBinding = (JUCtrlListBinding) formBean.get("Lob");
    Row r = (Row) listBinding.getSelectedValue();
    String SoLob = (String) r.getAttribute("LobLob");
    But i am unable to set the selected value back in the list when i return to the form again.
    I tried the following:
    int x = listBinding.getSelectedIndex();
    listBinding.setSelectedIndex(x);
    It would be really helpful if some one could let me know what needs to be done.
    Thanks,
    Subashini

    Gyan,
    I tried with the code you suggest , its trying to set the value of a field, but my requirement is to change the property for
    "Rendered" on the field so that based on search parameters we can hide result table column.
    After searching online, I modified the controller code as follows
    1.Created a new transient attribute (Testrender) with type "Boolean" and always updateable.
    2.changed the "Rendered" property value on the field I want to hide as ${oa.PoSearchVO1.Testrender}.
    3. Modified the controller code as follows :
            OAApplicationModule am = pageContext.getApplicationModule(webBean);
            OAViewObject testvo = (OAViewObject)am.findViewObject("PoSearchVO1");
            OADBTransaction txn = am.getOADBTransaction();
            if (testvo != null)
              OARow row = (OARow)testvo.first();
                if (a.equalsIgnoreCase("Approved"))
                     row.setAttribute("Testrender", Boolean.FALSE);
                else
                     row.setAttribute("Testrender", Boolean.TRUE);
            } But now when i run the page and populate the search field and click "Go" its hiding the field but throwing the following error and the search results are also bad.
    Its using only the value of one search parameter but not the second one .
    The search cannot be executed because the table has pending changes that would be lost. I think the vo is getting dirty when I update the transient attribute value. So I used txn.rollback ,then search is working fine but its not hiding the field.
    So can you please let me know how to proceed from here ?

  • SSRS Report with mutli select values in parameters

    Hi All,
    I am creating a SSRS report and displaying the result in tablix. I want to make the report to filter by multi select values from the parameters.
    I have 3 parameters. For all the three parameters, I have set "Default  Values" and "Available Values". Also, modified my result dataset to get the values from parameters using "WHERE ID = @Parameter1" (example) and so
    on..
    3 Parameters types:   1. Yes or No       
    2. Date          3. Values with NULL in the DB
    Problems:
    1. When I am passing the default values "Yes" "No" - it is throwing errors because default values is passed as Yes "AND" No instead of "OR" condition. The value stored in the DB wil have either Yes or No but not both.
    2. When I am querying the date values, it is a DateTime field in the DB. But I have queried like SELECT CONVERT(DATE, EXE_DATE) AS DATE FROM table which is giving only date in SQL but in SSRS displaying date with time.
    3. When I pull the list of values for third Parameter from SQL, it has some NULL values. When I try to use it in SSRS, it is not displaying the NULL value as select option in the list of values
    Any suggestions for the above three problems for SSRS with multi select values as filter will be helpful.
    Maruthu | My Blog

    Hi Maruthi,
    Regarding the three things:
    1.) I believe your first parameter is mutliselect , please convert it to single select.
    Steps: 
    a.) Select the parameter, right click and go to parameter properties
                    b.) Under General Tab in DataType section remove the checkbox for Allow Multiple Value.
    2.) Instead of returning as the date please return string. For example : 
    SELECT CONVERT(VARCHAR, GETDATE(),101)
    Here is the list of conversion : http://www.sqlusa.com/bestpractices/datetimeconversion/
    3.) As such there is no concept of null in SSRS. (Its a relational concept) . We do have nothing , which means empty. In Order to use null please select the Allow null option in the DataType section of the Parameter, This will add an checkbox for null in
    the report preview. Its developer job to handle the null values in there query.
    Regards Harsh

  • Automatically Selecting Values in Multiple Values Dropdown Parameters

    Hi,
    Is it possible to have parameter values automatically selected in a dropdown in an SSRS report?  I'm using SQL Server 2008 R2 Enterprise edition.  Basically what I have in mind is this:  The user wants to save his parameter selections in a
    table that will be available as a dropdown parameter of a report, call it
    ParamUserSelection.  ParamUserSelection is the first parameter of the report and other parameters depend on it.
    We have two other parameters called ParamCountry and
    ParamState.  These are dropdown text parameters that allow multiple values to be selected.  Populating the list is not a problem as I use a standard cascading parameter technique.  What I'm trying to do is the following:
    The user selects a value from ParamUserSelection, call it Selection1.  Selection1 is stored in a table and has all the values that should be selected in ParamCountry and ParamState.  In other words, it should tell these two subsequent parameters,
    what values should be selected in their respective dropdowns.  For example if the user selects Selection1 from ParamUserSelection, it reads the values in the database table and if it finds US and Canada for countries and CA, NY, ON for states, ParamCountry
    should be populated with all the countries available in the database but should have ONLY US and Canada as selected values and ParamState should be populated with all the states in the database but should have ONLY CA, NY and ON as selected values.
    If then I click on selection 2 and it has ParamCountry = US, ParamState = TX,OH in its database then again all countries and states should be in the dropdown but only US for ParamCountry and TX,OH for ParamState should be selected.
    Is this possible with SSRS?  I've tried using the Default Values tab with a dataset that returns all the selected values under Report Parameters Properties but this only works for the first time that I select ParamUserSelection.  It appears that
    if I change the value of ParamUserSelection again, the default values are not invoked.
    If this is possible, please tell me how to do this as I have been struggling for a day with it.

    Hi Comedian,
    According to your description, you have a report with three parameters (ParamUserSelection, ParamCountry, ParamState). The available value lists of ParamCountry and ParamState are based on the selection of a value for ParamUserSelection. Now you want to
    show all countries and states in their parameter dropdown list when selecting a user selection instead of only showing the cascading values. Right?
    In Reporting Service, when we want a parameter to show the cascading values, we only need to set the corresponding dataset and field for Default Values in this parameter. In this scenario, if we want to show all countries and states in their dropdown list,
    we just need to set another dataset for Available Values in those parameters so they can display all countries and states. We have tested your case in our local environment. Since you have done with the cascading parameters, we just give some part of steps
    and screenshots for your reference:
    We created two tables (dbo.Selection, dbo.states) based on your information.
    Create one more dataset (named dataset2) in your report, put text below into your query:
    select distinct Country from states
    Create another dataset (named dataset3), put text below into your query:
    select distinct State from states
    Go to your ParamCountry, in Available Values, select dataset2 and Country for dataset and field.
    Go to your ParamState, in Available Values, select dataset3 and State for dataset and field.
    Save and preview. It looks like below:
    Reference:
    Report Parameters (Report Builder and SSRS)
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou
      

  • How to get selected value from selectOneRadio ???

    Hi...i want to how to get selected value from selectOneRadio and use it in another page and in backing bean.
    Note i have about 10 selectOneRadio group in one page i want to know value of each one of them.
    Plzzzzzzzz i need help

    You have a datatable in which each row is a question, correct?
    Also in each row you have 5 possible answers that are in a radio, correct?
    So,
    You need to put in your datatable model, a question, and a list of answers (5 in yor case) and the selected one.
    So you will have a get to the question, an SelectItem[] list to populate the radios and another get/set to the selected question.
    ex:
    <h:selectOneRadio value="#{notas.selectedString}" id="rb">
    <f:selectItem itemValue="#{notas.valuesList}"/>
    </h:selectOneRadio>
    Search the web for examples like yours.

  • How to get selected value from OADefaultListBean.

    Hi All,
    How to get selected value from OADefaultListBean ?
    Thanks,

    Hi,
    To identify the user's selection(s) when the page is submitted, you would add the following logic to your processFormRequest() method:
    OADefaultListBean list =
    (OADefaultListBean)webBean.findChildRecursive("positionsList");
    String name = list.getName();
    String[] selectedValues = pageContext.getParameterValues(name);
    To retrieve all the values in the list box, call list.getOptionsData().
    --Prasanna                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to get selected values from selectManyCheckbox ?

    Hi,
    I am a SOA developer and using 'Auto generated adf form' of Human Task. I did some customization in the form. I need to show one dynamic list (contains multiple string values) on a form, from which user will select desired values. For this I have used <af:selectManyCheckbox> adf component.
    It has generated code as follows...
    <af:selectManyCheckbox value="#{bindings.Response.inputValue}"
                                             label="#{bindings.Response.label}"
                                             id="smc1">
                        <f:selectItems value="#{bindings.Response.items}" id="si9"/>
    </af:selectManyCheckbox>
    I am able to show list on a form and can select multiple values also.
    Now, I want the multiple selected values back in my BPEL process. I need only those values which are selected by user.
    Currently I am getting complete list as it is back in BPEL process.
    Please help me out..!
    Thanks..
    Suraj

    Unwinding ADF: How to retrieve Selected Items from selectManyCheckbox using ValueChnageListener

  • How to get selected values from af:selectManyCheckbox

    Hi i am using jdeveloper 11.1.2 and i drag n drop a view object as Multiple select (<af:selectManyCheckbox) component and now i am trying to get the checked values in backing bean so that i can save in the database.
    Right now i am getting all the values but not the selected values.
    JSPX Page.
    <af:selectManyCheckbox value="#{bindings.HREmpDetailsVO1.inputValue}"
    label="EMPLOYEES"
    binding="#{backingBeanScope.backing_TestForm.smc1}"
    id="smc1">
    <f:selectItems value="#{bindings.HREmpDetailsVO1.items}"
    binding="#{backingBeanScope.backing_TestForm.si1}"
    id="si1"/>
    </af:selectManyCheckbox>
    Bean Class:
    public List getSelectedValues() {
    if (selectedValues == null || refreshSelectedList) {
    selectedValues =
    attributeListForIterator(selectedValuesIteratorName,
    selectedValuesValueAttrName);
    return selectedValues;
    public static List attributeListForIterator(DCIteratorBinding iter,
    String valueAttrName) {
    List attributeList = new ArrayList();
    for (Row r : iter.getAllRowsInRange()) {
    attributeList.add(r.getAttribute(valueAttrName));
    return attributeList;
    Can some one pls help me in getting the values with sample code.
    Thanks in advance

    Thank you so much for your help. But i am getting null values in the SOP. I could get count of selected values but not the values.

Maybe you are looking for

  • Front camera of my iPhone 4 doesn't work, the virtual cover doesn't open.

    Yesterday I have bought an used iPhone 4, so I don't have any guarantee. But the front camera doesn't work, the virtual cover doesn't open. I have read that it is something like a hardware fault. Now my question is, if Apple has to repair it because

  • Windows XP crashes when I plug in new ipod classic

    I bought my daughter a ipod classic for Christmas and she hasn't been able to put any music on it. When we plug it into the usb on the pc (emachines T1840 - OK it's old) it gets a blue screen stating an error. STOP: 0x0000007E (0XC0000005, 0X00000000

  • Characteristic 0MATERIAL is blocked by conversion

    Hi experts, I am transporting the 0MATERIAL changes into production (after extra navigational attribute added), while importing into production system, its giving below error message. Characteristic 0MATERIAL is blocked by conversion the new navigati

  • Problem with Desktop redirector forwarding messages

    In my office 5 of us use the desktop redirector , and it stopped working last Saturday so I fairly sure the problem is with our SPAM filtering or exchange etc the problem is everyone I talk to seems clueless, In out look I see all the BB messages now

  • Show front panel in runtime

    I want to show front panel in runtime( or when called) without all the menus, tool bars and scroll bar, just as a ordinary control panel only with window title. any suggest will be appreciated. Jacob Sent via Deja.com http://www.deja.com/ Share what