Action event automatically triggered for combo box

Hi all,
I am facing a typical event handling problem for combo box in Swing(Using Net Beans 5.0, jdk 1.4.2)
While adding items to combo box it is firing action event twice instead of once irrespective of no. of items added to it.
For eg if there are 1 or more than 1 item added to combo box it is triggerring action event twice(one just after when first item is added and one again when rest all items are added)
and if there is no item then also it is triggering once.
Can you please help me out.
Thanks

post the SSCCE code, then only it is easy to find the problem

Similar Messages

  • Help needed: triggering a combo box selection

    I'm new to creating forms in Acrobat (Acrobat 9 on Mac). I'm trying to create a form for my department where a student selects a faculty name from a combo box, and once the value is selected, another field is filled with an int value (course section number).
    Question: what is the correct trigger for executing the javascript for this? Mouse up seems to trigger too early and the others don't seem appropriate.
    I think my rudimentary JavaScript knowledge can get me far enough to check the value and the use a switch/if to prefill the int value in the other field, so the correct trigger is my current issue.
    Thanks in advance.

    I found where it's supposed to be stored, but I'm having some issues with missing ().  I'm using Acrobat X Pro for Windows Vista.  There was a post that I've spent the last 2 hours looking for that had a modified code that added in missing (), and now I can't find it   Any help would be greatly appreciated. Anyway, here's my code:
    function mater list for Alpha1()
    var oAlpha1 = {
    ACC: [
    ["-","None"], ["201",Intro to Financial Accounting], ["202",Intro to Managerial Accounting], ["-96",Selected Topics], ["-99",Directed Reading and Research]
    ANTH: [
    ["-","None"], ["151",Emerging Humanity], ["152",Culture and Humanity], ["210",Archaeology], ["215",Physical Anthropology], ["215L",Physical Anthropology Lab], ["310",Human Origins], ["313",Culture Through Film], ["321",World Archeology], ["342",Indigenous Peoples & Modernity], ["350",Pacific Islands Cultures], ["351",Culture Thought and Behavior], ["358",Myth, Symbol, and Ritual], ["362",Gender, Culture, and Society], "380",Field Archaeology], ["383",Museum Studies], ["384",Human Skeletal Biology], ["415",Human Ecological Adaptation], ["420",Culture & Communication], ["422",Magic Witchcraft & Supernatl], ["423",Social and Cultural Change], ["437",Pacific Archaeology], ["447",Polynesian Cultures], ["448",Micronesian Cultures], ["457",Okinawans Locally & Globally], ["458",Forensic Investigations], ["460",Adv Tech in Forensic Anth], ["474",Culture and Mental Illness], ["483",Archaeology of Hawaii], ["487",Philippine Culture], ["490",History & Theory Anthropology], ["495",Research Seminar], ["496",Selctd Tpcs:], ["499",Directed Reading & Research], ["296F",Intro to Field Archaeology], ["496A",Culture Through Film], ["496B",Phillipines Studies], ["496C",Museum Studies], ["496D",Okinawans Locally & Globally], ["496E",Pacific Island Cultures]
    APSC: [
    ["-","None"], ["486",Senior Project-Applied Sci], ["490",Senior Practicum], ["486C",Senior Project-CENT], ["486I",Senior Project-IT], ["486M",Senior Project-CULM], ["486R",Senior Project-RESP], ["490C",Admin Practicum-CENT], ["490I",Admin Practicum-IT], ["490M",Admin Practicum-CULM], ["490R",Admin Practicum-RESP]
    ASTR: [
    ["-","None"], ["110",Survey of Astronomy]
    It goes on like this through all our subjects.  I then modified the next bits of code in thomp's doc to reflect what I need to be pulled and populated:
    var nACCItems=oAlpha1["ACC"];
        var n201Title=ACCItems[1]; var n202Title=ACCItems[1]; var n-96Title=ACCItems[1]; var n-99Title=ACCItems[1];
    var nANTHItems=oAlpha1["ANTH"];
        var n151Title=ANTHItems[1]; var n152Title=ANTHItems[1]; var n210Title=ANTHItems[1]; var n215Title=ANTHItems[1]; var n215LTitle=ANTHItems[1]; var n310Title=ANTHItems[1]; var n313Title=ANTHItems[1]; var n321Title=ANTHItems[1]; var n342Title=ANTHItems[1]; var n350Title=ANTHItems[1]; var     n351Title=ANTHItems[1]; var n358Title=ANTHItems[1]; var n362Title=ANTHItems[1]; var n380Title=ANTHItems[1]; var n383Title=ANTHItems[1]; var n384Title=ANTHItems[1]; var n415Title=ANTHItems[1]; var n420Title=ANTHItems[1]; var n422Title=ANTHItems[1]; var n423Title=ANTHItems[1]; var n437Title=ANTHItems[1]; var n447Title=ANTHItems[1]; var n448Title=ANTHItems[1]; var n457Title=ANTHItems[1]; var n458Title=ANTHItems[1]; var n460Title=ANTHItems[1]; var n474Title=ANTHItems[1]; var n483Title=ANTHItems[1]; var n487Title=ANTHItems[1]; var n490Title=ANTHItems[1]; var n495Title=ANTHItems[1]; var n496Title=ANTHItems[1]; var n499Title=ANTHItems[1]; var n296FTitle=ANTHItems[1]; var n496ATitle=ANTHItems[1]; varn496BTitle=ANTHItems[1]; var n496CTitle=ANTHItems[1]; var n496DTitle=ANTHItems[1]; var n496ETitle=ANTHItems[1];
    var nAPSCItems=oAlpha1["APSC"];
    through all our subjects.  Do I need to leave the lists of var nSUBJItems and var nNUMTitle separate, or is the way I have them (subject followed by titles in each subject) okay?
    Then, I made the keystroke codes.  Do they go in the Document level as well, or do they go in the keystroke event or both?  Right now, I just have them as a doc level code because I can't save the document level code without fixing the () error.  I'd just like to know ahead of time.
    Number Keystroke Event
    function SetNumberEntries()
    if(event.willCommit)
    // Get the numbers list from the Master List
    // Since the selection is being committed,
    // event.value contains the Alpha1 name
    var lst = oAlpha1[event.value];
    // Clear the Number list if there are no numbers for the selected alpha
    if( (lst != null) && (lst.length > 0) )
    this.getField("NumberSelect").setItems(lst);
    else
    this.getField("NumberSelect").clearItems();
    // We have a new number list and the first entry is
    // is a non-selection, so clear the title field.
    this.getField("Title").value = 0;
    Uncommitted Keystroke Event
    function SetTitleValue()
    // In order to get easy access to the export value, i.e. Title. This
    // function needs to be run on the un-committed change event.
    // This field is set up for Commit on select so we know the value
    // will be committed anyway.
    if(!event.willCommit)
    // If the export value is Not written then
    // set the title to --.
    var nSelExp = --;
    if(!isNaN(event.changeEx))
    nSelExp = event.changeEx
    this.getField("Title").value = nSelExp;

  • Enter event not triggering for read-only checkbox

    I have some objects in a form that get "locked" when the user signs the form.  I'm not using the digital signatures.  Instead, when the user types their name into the signature text field, a script runs on the change event that makes all of the fields in the form read only.  It also unlocks the fields if the signature is deleted.
    I was worried that we would get a lot of phone calls with users that didn't understand that the form had locked ("Why doesn't this form work?!"), so I added some code to the enter event for all of the fields that would pop up a messagebox to explain to people trying to edit a signed form that the form was locked and that they would need to delete the signature to edit the form.
    This plan works perfect for my text fields and decimal fields.  It does NOT work at all for my checkboxes.  For some reason, the enter event is never triggered for read-only checkboxes.  I don't see any other events that would obviously work for me though.  Any ideas?
    Thanks

    Thanks, those are reasonable suggestions.
    In the first suggestion, I'm unclear about one aspect of how I would accomplish this.  I assume I would allow people to modify fields in the form, but that when they did, a msgbox would pop up that would inform them that, if they continued with this modification to a signed form, the signature would be removed.  I'm all good to that point.  But if they answered that they do not want to continue modifying that field and removing the signature, how can I code it to set the value back to what it was before the change?  Is there some method that will give me access to the value of the field BEFORE the attempted modification?  I went looking for something like $.previousvalue, but found nothing.
    I'd suggest that I could use a two-stage solution, in which I store the previous value on the enter event, and save it just in case they do not want to change the field when prompted by the msgbox, but since the enter event does not exist for checkboxes (my original problem), that seems like it won't work.
    As far as radio button suggestion, I like radio buttons very much except for one fatal flaw: they aren't (as far as I can tell) clearable.  That is a shame.  Clearly some people (like me) want both exclusivity AND clearability.  And we'd like the controls to have an enter event.  But I know I'm demanding   Anyway, as it is, I just end up having to use checkboxes and create a boatload of silly code to make them exclusive.
    Emily

  • Enumeration binding for combo box - missing feature

    Hi,
    In our application, combo boxes are usually employed for similar purpose as radio button groups: provide the end-user with an exclusive, static list of choices.
    Unfortunately, JUComboBoxBinding.createEnumerationBinding method does not seem to follow the same paradigm as JUButtonGroupBinding.createEnumerationBinding.
    In fact, for JUButtonGroupBinding, one parameter is "AbstractButton[] buttons", which is used for display purposes (end-user descriptions of the choices), and another is "Object[] valueList", which is the list of values for the corresponding attribute (usually, the valid values in the database for the column).
    Meanwhile, JUComboBoxBinding is only receiving one array parameter, "Object[] values", which is used both for display purposes and for database values... This approach is very restrictive, as long as we expect to display in the combo box a descriptive text for the coded value in the database (and localizable, as well!).
    Is this a known bug, or am I the first one to have noticed it? Is there any schedule for making this feature available?
    Thanks,
    Adrian

    I'm not sure where my last reply went, so another try.
    Unfortunately, I have the same feeling as usual, that my posted messages are not carefully read...
    The main issue was the comparison between JUComboBoxBinding and JUButtonGroupBinding, and my question was about the possible future availability of a feature. Nothing about this in the answer...
    Could I have an aswer to my original message, please?JUButtonGroupBinding is a custom control provided by JClient and has an api to let a user 'provide' custom Button objects instead of the default 'RadioButton's that would get created if none is passed in. The fact that you could use that to perform LOV kind of indirection of displaying a value other than what's set is 'a side-effect' of the original intention.
    FYI, we already implemented an extension to JUComboBoxBinding which is just doing what I was asking for. It is not complex at all:( I was only thinking that it might be useful also in standard...The 'standard' way of getting this behavior you're asking for is to create a programmatic VO as suggested above, with both display/update attribute values and bind it to the ComboBox as an LOV Binding. And yes you can certainly create custom controls extending Swing and use the existing bindings or 'extend' them as per an application need.
    Regards,
    Adrian

  • Event problem in editable combo box

    I have three editable combo box in my JDialog. I can select the value from the combo or I can enter any value. I have to perform some operation when one button is pressed after I have given the values in the three combo boxes. Here, If I select any value from the combo box, there is no problem. But if I enter the value in the combo boxes, when I press the button, in the first click nothing is happening. The First click just selects the value that entered in the last combo box and in the second click it works properly. I am not facing this problem in JDK 1.2.2 or JDK1.3. This occurs only in JDK1.4. Please let me if anyone knows the reason for this.
    Thanks.

    in the fla that contains your loadMovie() statement:
    1. drag a combobox to the stage.
    2. remove it.
    3. the combobox component will now be in your library.
    re-publish your swf and retest.

  • Alternative for Combo-box

    Hi,
    Combo-BOx is not supported by Forms on web,so I would like to make combo-box my-
    self .. I dont know how but I guess I can
    do it with JAVA. Also I like to prepare it
    exactly same like Oracle COMBO-BOX with
    all functionality ..
    Anybody have any IDEA pl.
    give me respond or
    send me a mail : [email protected]

    Combo-Boxes are supported in the current version of Forms on the Web. (6.0 and 6i)

  • 'CHANGE' event not triggering for BTE 2214 on park/change from FBV1/FBV2

    I have designed a workflow template for FI parking. If the parked document is rejected, i need to trigger FIPP 'CHANGE' event for sending workitem to approver when someone changes the parked document. In SWEL event trace, the 'CHANGE' event is not getting raised.
    So i implemented a BTE 000002214 and now i am able to raise 'CHANGE' event and capture it in workflow. But this is only working when i park a document using FV50 transaction and later change it.
    But when i park a document using FBV1 and then make changes from FBV2, the 'CHANGE' event is not being triggered in SWEL. Should i implement some other BTE like 2218 etc? Can you please help?

    Hi Gokul,
    You can try handling the SAVE event instead of the CHANGED event.
    T-code FBV2 will not allow you to save the document unless you make some changes.
    Try implementing BTE 2218 and revert.
    Thanks,
    Sreekanth

  • Event not triggering for SWEC entry (MM_SERVICE) on create

    Hi All,
    I have been trying to trigger a customised event for BUS2009 based on creation of the Change Object MM_SERVICE.  I have created an entry in SWEC as follows:
    - Change Doc Object: MM_SERVICE
    - Object Cat : BOR
    - Object Type: BUS2009
    - Event: RELEASEDREQCHANGED
    - On Create
    (no field conditions)
    However, the event does not seem to publish upon an insert of ESUH-SUMLIMIT (Overall Limit on the Purchase Req - a field in Change Object MM_SERVICE), as I am not seeing the event in SWEL.  Please note I have also tried to do this with field conditions in SWEC, but to no avail. 
    Alternatively, I have tried to setting the Change Doc config via SWU_EWCD, however, it comes back with an error message saying "No change document object for business object type BUS2009" - I believe this might have to do with the incompatibility of the key structures between MM_SERVICE and BUS2009.  We have written a function module to overcome this problem and placed same in SWEC, which is why the (BUS2009) event is currently publishing for "on change" of MM_SERVICE - is there any way around this?
    On the other hand, the event will publish OK if the SWEC entry is amended to "ON CHANGE" (with field conditions) - upon changing the value of ESUH-SUMLIMIT, not insert/create.
    Would anyone be able to kindly advise how I can get the event to publish upon "ON CREATE" as well?
    Thanks in advance.
    ~Andy.

    Thanks for your prompt response Surjith.
    However, I believe the above setup in SWEC is already configured for the purpose of triggering the event.  The customised event in BUS2009 (RELEASEDREQCHANGED) is linked to the Change Document Object MM_SERVICE via "on create" in SWEC - it's just that there are no events coming up in SWEL
    I have exactly the same config setup for RELEASEDREQCHANGED, MM_SERVICE via "on change" - and this is working perfectly fine (ie. I can see the event in SWEL whenever there is a change in any of the restricted fields of MM_SERVICE).
    My understanding is that upon "on create" (in SWEC), it is not necessary to set up field restrictions in order to publish the event.  In any case, I have tried to trigger the event both with and without any field restrictions, none of which came up with any event when a field in MM_SERVICE has been inserted.  This is the reason why I tried SWU_EWCD instead, however, due to the incompatibility in the key structure between BUS2009 and MM_SERVICE, the transaction did not allow me to complete the setup.
    Is there any way around this?
    Many thanks.
    ~ Andy

  • Where is event 'READY_FOR_WORKFLOW' triggered for invoice p-c workflow?

    Dear forum members,
    I am setting up process-controlled workflow in SRM 7.0 (SP 7) for invoices and have found when saving an invoice with errors that the new process-controlled workflow does not get triggered. It works OK for invoices without errors.
    How can I find where the event  'READY_FOR_WORKFLOW' is triggered to check whether the workflow is only triggered on certain conditions? I have looked all over the system but can't find anywhere yet.
    Thanks a lot in advance,
    Nick

    Hi,
    I solved this myself. There are checks in include LBBP_PDF0L (form PROCDOC_SAVE) which prevent invoice approval workflow starting for us.
    The checks for starting the process-controlled workflow are shown from line 505:
          ELSEIF lv_pdo_layer_active NE lc_true.
            DATA lr_status         TYPE REF TO crm_jest.
            DATA lv_start_process  TYPE abap_bool VALUE abap_undefined.
            DATA lv_version_no     TYPE char08. " initial version number
            DATA lv_process_status TYPE char4.
            CONSTANTS:
              lc_process_status_initial  TYPE char4 VALUE 'INIT'.
            " check, if 'In Approval' status (I1015) or
            " 'Currently In Release Process' (I1052 for invoice) is set as new status
            LOOP AT x_status REFERENCE INTO lr_status.
              CHECK ( lr_status->stat EQ /sapsrm/if_pdo_status_c=>gc_pdo_rel_process OR "I1015
    I have created a message to SAP.
    Best regards,
    Nick

  • Display Attribute for Combo Box List of Value

    Hi all,
    I am wondering that if even for JDeveloper 12c we need to keep doing this work around https://blogs.oracle.com/adf/entry/combo_lov_how_to_display in order to display a meaningful attribute?
    Regards

    You could, for example. store both of them (old value, along with new one) in the pageFlowScope. You can do that in the valueChangeListener (before calling popup), and use them in the dialog listener...

  • Why will this not work for combo box

    I need to know why this will not work a combobox but it works for text fields. Isay ther is an error in the doc.createTextNode.
    Please any help would be great.
    Thanks
    // Repeats for each Element in the User Configuration.
    item = doc.createElement("COMPANY_NAME"); // Create element
    item.appendChild( doc.createTextNode(SetupCompanyNameJText.getText()) );
    UserConfig.appendChild( item ); // atach element to User Config element
    item = doc.createElement("INTIALS"); // Create element
    item.appendChild( doc.createTextNode(SetupIntialsjComboBox.getSelectedItem()) );
    UserConfig.appendChild( item ); // atach element to User Config element
    item = doc.createElement("FIRST_NAME"); // Create element
    item.appendChild( doc.createTextNode(SetupFirstNamejText.getText()) );
    UserConfig.appendChild( item );

    when I do that I end up with the following
    Error: #:300: class Configuration not found in class
    any ideas
    thanks

  • ArrayCollection for combo box - null vlaue

    I have defined an ArrayCollection like this:
    public var typename:ArrayCollection = new ArrayCollection(["Simple" , "Complex"]);
    In mxml file,
    the usage is,
    <mx:ArrayCollection id = "sample">
    <mx:Object dataField = "type" dataType = "Array" dataProvider = "{com.values.typename}" editable = true updatable = "true"/>
    </mx:ArrayCollection>
    In screen, i get the drop down with a null value. I want only two values dropped down , Simple and Complex.
    Where does this null field come from??

    1. your arrayCollection should be bindable:
    [Bindable]
    public var typename:ArrayCollection = new ArrayCollection(["Simple" , "Complex"]);
    2. What is com.values? Is that a reference to a class? If you store typename in a class, you can do two things:
         a. Store it as a static var:
              public static var typename....
              and then reference it as MyClass.typename
         b. Store it in a singleton class and then reference it as MyClass.getInstance().typename
    3. How do you populate your comboBox? Where is it in your code?
    Dany

  • How can I programmatically fire a combo box action?

    I'm maintaining a program that was developed for JDK 1.3 and recently was migrated to JDK 1.4
    At that time, the developer forgot to perform some initializations in a panel when first displayed, but after all, everything was solved because in 1.3 some automatic calls to the actionPerformed method, where the event source is a combo box, made the work, because it has some code that performs those initializations.
    In 1.4, those calls to actionPerformed don't happen and the mistake has been detected. For me, the easiest way to fix the problem is firing those actions at initialization. Is there any way to do it?
    Thanks

    either doClick or dispatchEvent

  • Determine the best width for ListCellRenderer - Multi-column combo box

    Currently, I am having a multi column combo box. In order for the column to align properly during show popup, I use box layout to do so. However, the short coming for box layout is that, the size for each column is fixed. This makes me have a difficulty, when I have a long string to be displayed. The problem is shown through the following screen shoot.
    http://i.imgur.com/4Nfc6.png
    This is because in 2nd column,
    1) All the 3 rows must be in same size so that they are aligned.
    2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.
    The code (2 files) to demo this problem is as follow. Is there any way the size of the cell will be adjusted automatically? Yet, all the row will be aligned properly.
    ResultSetCellRenderer.java
    package javaapplication24;
    import java.awt.Color;
    import java.awt.Component;
    import javaapplication24.NewJFrame.ResultType;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.UIManager;
    * @author yccheok
    public class ResultSetCellRenderer extends javax.swing.JPanel implements ListCellRenderer {
        /** Creates new form ResultSetCellRenderer */
        public ResultSetCellRenderer() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.X_AXIS));
            jLabel1.setText("jLabel1");
            jLabel1.setMaximumSize(new java.awt.Dimension(88, 14));
            jLabel1.setMinimumSize(new java.awt.Dimension(88, 14));
            jLabel1.setPreferredSize(new java.awt.Dimension(88, 14));
            add(jLabel1);
            jLabel2.setText("jLabel2");
            jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
            jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
            jLabel2.setPreferredSize(new java.awt.Dimension(100, 14));
            add(jLabel2);
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        // End of variables declaration
        // Do not use static, so that our on-the-fly look n feel change will work.
        private final Color cfc  = UIManager.getColor("ComboBox.foreground");
        private final Color cbc  = UIManager.getColor("ComboBox.background");
        private final Color csfc = UIManager.getColor("ComboBox.selectionForeground");
        private final Color csbc = UIManager.getColor("ComboBox.selectionBackground");
        private final Color cdfc = UIManager.getColor("ComboBox.disabledForeground");
        // For Nimbus look n feel.
        private final Color nimbus_csfc;
             Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].textForeground");
             // Pretty interesting. Applying "c" directly on the component will not
             // work. I have the create a new instance of Color based on "c" to make
             // it works.
             nimbus_csfc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
        private final Color nimbus_csbc;
            Color c = UIManager.getColor("ComboBox:\"ComboBox.renderer\"[Selected].background");
             // Pretty interesting. Applying "c" directly on the component will not
             // work. I have the create a new instance of Color based on "c" to make
             // it works.
            nimbus_csbc = c != null ? new Color(c.getRed(), c.getGreen(), c.getBlue()) : null;
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            final Color _csbc = csbc != null ? csbc : nimbus_csbc;
            final Color _csfc = csfc != null ? csfc : nimbus_csfc;
            this.setBackground(isSelected ? _csbc : cbc);
            this.setForeground(isSelected ? _csfc : cfc);
            jLabel1.setBackground(isSelected ? _csbc : cbc);
            jLabel1.setForeground(isSelected ? _csfc : cfc);
            jLabel2.setBackground(isSelected ? _csbc : cbc);
            jLabel2.setForeground(isSelected ? _csfc : cfc);
            final ResultType result = (ResultType)value;
            jLabel1.setText(result.symbol);
            jLabel2.setText(result.name);
            return this;
    NewJFrame.java
    package javaapplication24;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    import javax.swing.plaf.basic.BasicComboPopup;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
        public static class ResultType {
             * The symbol.
            public final String symbol;
             * The name.
            public final String name;
            public ResultType(String symbol, String name) {
                this.symbol = symbol;
                this.name = name;
            @Override
            public String toString() {
                return symbol;
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jComboBox1.addPopupMenuListener(this.getPopupMenuListener());
            this.jComboBox1.setRenderer(new ResultSetCellRenderer());
            this.jComboBox1.addItem(new ResultType("Number 1", "Normal"));
            this.jComboBox1.addItem(new ResultType("Number 2", "Normal"));
            this.jComboBox1.addItem(new ResultType("Number 3", "A VERY VERY VERY VERY long text"));
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 110, -1));
            pack();
        }// </editor-fold>
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    final NewJFrame frame = new NewJFrame();
                    frame.setVisible(true);
        private PopupMenuListener getPopupMenuListener() {
            return new PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    // We will have a much wider drop down list.
                    adjustPopupWidth(jComboBox1);
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
         * Adjust popup for combo box, so that horizontal scrollbar will not display.
         * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
         * http://www.camick.com/java/source/BoundsPopupMenuListener.java
         * @param comboBox The combo box
        public static void adjustPopupWidth(JComboBox comboBox) {
            if (comboBox.getItemCount() == 0) return;
            Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
            if (!(comp instanceof BasicComboPopup)) {
                return;
            BasicComboPopup popup = (BasicComboPopup)comp;
            JList list = popup.getList();
            JScrollPane scrollPane = getScrollPane(popup);
            // Just to be paranoid enough.
            if (list == null || scrollPane == null) {
                return;
            //  Determine the maximimum width to use:
            //  a) determine the popup preferred width
            //  b) ensure width is not less than the scroll pane width
            int popupWidth = list.getPreferredSize().width
                            + 5  // make sure horizontal scrollbar doesn't appear
                            + getScrollBarWidth(popup, scrollPane);
            Dimension scrollPaneSize = scrollPane.getPreferredSize();
            popupWidth = Math.max(popupWidth, scrollPaneSize.width);
            //  Adjust the width
            scrollPaneSize.width = popupWidth;
            scrollPane.setPreferredSize(scrollPaneSize);
            scrollPane.setMaximumSize(scrollPaneSize);
         *  I can't find any property on the scrollBar to determine if it will be
         *  displayed or not so use brute force to determine this.
        private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
            int scrollBarWidth = 0;
            JComboBox comboBox = (JComboBox)popup.getInvoker();
            if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
                JScrollBar vertical = scrollPane.getVerticalScrollBar();
                scrollBarWidth = vertical.getPreferredSize().width;
            return scrollBarWidth;
         *  Get the scroll pane used by the popup so its bounds can be adjusted
        private static JScrollPane getScrollPane(BasicComboPopup popup) {
            JList list = popup.getList();
            Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
            return (JScrollPane)c;
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }Edited by: yccheok on Jan 13, 2011 9:35 AM

    Are these two lines intentionally or is it just a mismatch?
    jLabel2.setMaximumSize(new java.awt.Dimension(100, 14));
    jLabel2.setMinimumSize(new java.awt.Dimension(200, 14));
    2) But 1st row and 2nd row cell renderer, do not know 3rd row is holding such a long string.There is only one cell renderer for all rows, so no need for the rows to know each other.
    To calculate the exact maximum width of column two, you have to check each entry.
    If you can do this BEFORE creating the combo, you could do this in a loop similar to this pseudo code
    FontMetrics fm= jComboBox1.getFontMetrics(jComboBox1.getFont());
    foreach (column2String) {
      int length= fm.stringWidth(column2String);
      if (length>max) max= length;
    }Now you have a max value to dimension jLabel2 in your renderer.
    If you don't fill your combo in one go, but rather at runtime, you have to check at each
    jComboBox1.addItem(...)
    whether the string for label2 is extending the current max, redefine max, and repaint the combo.
    This second approach I haven't done so far, but that's how I would try.

  • Adding an event listener to combo box

    I am working on a mortgage calculator and I cannot figure out how to add an event listener to a combo box.
    I want to get the mortgage term and interest rate to calucate the mortgage using the combo cox. Here is my program.
    Modify the mortgage program to allow the user to input the amount of a mortgage
    and then select from a menu of mortgage loans: 7 year at 5.35%, 15 year at 5.50%, and
    30 year at 5.75%. Use an array for the different loans. Display the mortgage payment
    amount. Then, list the loan balance and interest paid for each payment over the term
    of the loan. Allow the user to loop back and enter a new amount and make a new
    selection, with resulting new values. Allow user to exit if running as an application
    (can't do that for an applet though).
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.text.NumberFormat;
    import java.util.Locale;
    //creates class MortgageCalculator
    public class MortgageCalculator extends JFrame implements ActionListener {
    //creates title for calculator
         JPanel row = new JPanel();
         JLabel mortgageCalculator = new JLabel("MORTGAGE CALCULATOR", JLabel.CENTER);
    //creates labels and text fields for amount entered          
         JPanel firstRow = new JPanel(new GridLayout(3,1,1,1));
         JLabel mortgageLabel = new JLabel("Mortgage Payment $", JLabel.LEFT);
         JTextField mortgageAmount = new JTextField(10);
         JPanel secondRow = new JPanel();
         JLabel termLabel = new JLabel("Mortgage Term/Interest Rate", JLabel.LEFT);
         String[] term = {"7", "15", "30"};
         JComboBox mortgageTerm = new JComboBox(term);
         JPanel thirdRow = new JPanel();
         JLabel interestLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
         String[] interest = {"5.35", "5.50", "5.75"};
         JComboBox interestRate = new JComboBox(interest);
         JPanel fourthRow = new JPanel(new GridLayout(3, 2, 10, 10));
         JLabel paymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
         JTextField monthlyPayment = new JTextField(10);
    //create buttons to calculate payment and clear fields
         JPanel fifthRow = new JPanel(new GridLayout(3, 2, 1, 1));
         JButton calculateButton = new JButton("CALCULATE PAYMENT");
         JButton clearButton = new JButton("CLEAR");
         JButton exitButton = new JButton("EXIT");
    //Display area
         JPanel sixthRow = new JPanel(new GridLayout(2, 2, 10, 10));
         JLabel displayArea = new JLabel(" ", JLabel.LEFT);
         JTextArea textarea = new JTextArea(" ", 8, 50);
    public MortgageCalculator() {
         super("Mortgage Calculator");                     //title of frame
         setSize(550, 350);                                             //size of frame
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container pane = getContentPane();
         GridLayout grid = new GridLayout(7, 3, 10, 10);
         pane.setLayout(grid);
         pane.add(row);
         pane.add(mortgageCalculator);
         pane.add(firstRow);
         pane.add(mortgageLabel);
         pane.add(mortgageAmount);
         pane.add(secondRow);
         pane.add(termLabel);
         pane.add(mortgageTerm);
         pane.add(thirdRow);
         pane.add(interestLabel);
         pane.add(interestRate);
         pane.add(fourthRow);
         pane.add(paymentLabel);
         pane.add(monthlyPayment);
         monthlyPayment.setEnabled(false);
         pane.add(fifthRow);
         pane.add(calculateButton);
         pane.add(clearButton);
         pane.add(exitButton);
         pane.add(sixthRow);
         pane.add(textarea); //adds texaarea to frame
         pane.add(displayArea);
         setContentPane(pane);
         setVisible(true);
         //Adds Listener to buttons
         calculateButton.addActionListener(this);
         clearButton.addActionListener(this);
         exitButton.addActionListener(this);
         mortgageTerm.addActionListener(this);
         interestRate.addActionListener(this);
    public void actionPerformed(ActionEvent event) { 
         Object command = event.getSource();
         JComboBox mortgageTerm = (JComboBox)event.getSource();
         String termYear = (String)mortgageTerm.getSelectedItem();
    if (command == calculateButton) //calculates mortgage payment
         int year = Integer.parseInt(mortgageTerm.getText());
         double rate = new Double(interestRate.getText()).doubleValue();
         double mortgage = new Double(mortgageAmount.getText()).doubleValue();
         double interest = rate /100.0 / 12.0;
         double monthly = mortgage *(interest/(1-Math.pow(interest+1,-12.0 * year)));
                   NumberFormat myCurrencyFormatter;
                   myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
                   monthlyPayment.setText(myCurrencyFormatter.format(monthly));
         if(command == clearButton) //clears all text fields
                   mortgageAmount.setText(null);
                   //mortgageTerm.setText(null);
                   //interestRate.setText(null);
                   monthlyPayment.setText(null);
              if(command == exitButton) //sets exit button
                        System.exit(0);
         public static void main(String[] arguments) {
              MortgageCalculator mor = new MortgageCalculator();

    The OP already did this to both JComboBoxes.
    mochatay, here is a new actionPerformed method for you to use.
    I've improved a few things here and there...
    1) You can't just cast the ActionEvent's source into a JComboBox!
    What if it was a JButton that fired the event? Then you would get ClassCastExceptions (I'm sure you did)
    So check for all options, what the source of the ActionEvent actually was...
    2) You can't assume the user will always type in valid data.
    So enclose the Integer and Double parse methods in try-catch brakcets.
    Then you can do something when you know that the user has entered invalid input
    (like tell him/her what a clumsy idiot they are !)
    3) As soon as user presses an item in any JComboBox, just re-calculate.
    I did this here by programmatically clicking the 'Calculate' button.
    Alternatively, you could have a 'calculate' method, which does everything inside the
    if(command==calculateButton) if-block.
    This will be called when:
    a)calculateButton is pressed
    b)when either of the JComboBoxes are pressed.
    public void actionPerformed (ActionEvent event)
            Object command = event.getSource ();
            if (command == calculateButton) //calculates mortgage payment
                int year = 0;
                double rate = 0;
                double mortgage = 0;
                double interest = 0;
                /* If user has input invalid data, tell him so
                and return (Exit from this method back to where we were before */
                try
                    year = Integer.parseInt (mortgageTerm.getSelectedItem ().toString ());
                    rate = new Double (interestRate.getSelectedItem ().toString ()).doubleValue ();
                    mortgage = new Double (mortgageAmount.getText ()).doubleValue ();
                    interest = rate / 100.0 / 12.0;
                catch (NumberFormatException nfe)
                    /* Display a message Dialogue box with a message */
                    JOptionPane.showMessageDialog (this, "Error! Invalid input!");
                    return;
                double monthly = mortgage * (interest / (1 - Math.pow (interest + 1, -12.0 * year)));
                NumberFormat myCurrencyFormatter;
                myCurrencyFormatter = NumberFormat.getCurrencyInstance (Locale.US);
                monthlyPayment.setText (myCurrencyFormatter.format (monthly));
            else if (command == clearButton) //clears all text fields
                /* Better than setting it to null (I think) */
                mortgageAmount.setText ("");
                //mortgageTerm.setText(null);
                //interestRate.setText(null);
                monthlyPayment.setText ("");
            else if (command == exitButton) //sets exit button
                System.exit (0);
            else if (command == mortgageTerm)
                /* Programmatically 'clicks' the button,
                As is user had clicked it */
                calculateButton.doClick ();
            else if (command == interestRate)
                calculateButton.doClick ();
            //JComboBox mortgageTerm = (JComboBox) event.getSource ();
            //String termYear = (String) mortgageTerm.getSelectedItem ();
        }Hope this solves your problems.
    I also hope you'll be able to learn from what I've indicated, so you can use similar things yourself
    in future!
    Regards,
    lutha

Maybe you are looking for