JComboBox itemStateChanged in 1.3 and 1.4

When I use 1.3 JDK the itemStateChanged() listener is not activated when i do a cb.setselectedindex(-1).
However in 1.4 JDK the cb.setselectedindex(-1) statement fires a ItemEvent ??

and is -1 in 1.4. Show us the 10 line demo program you used to test this statement.
I've never had a problem.

Similar Messages

  • How to fire JComboBox itemStateChanged event manually?

    hello:
    I want to know how to fire JComboBox itemStateChanged event manually.
    thank you
    -Daniel

    Call setSelectedIndex or setSelectedItem.

  • How do I set "JComboBox ItemStateChanged function" to do action only once

    I encounter a serious problem with JComboBox.
    When I use "ItemStateChanged" function,
    I found out it does every action TWICE !!!!!
    I need to use "ItemStateChanged" to decrease numbers by 1,
    since it does action twice, the numbers are decrease by 2 everytime, which is not what I intended.
    Are there anyway I could set "ItemStateChanged" to do the action only once?
    Please help me out

    The ItemEvent has a getStateChange() method that tells you what the state change was, "selected" vs "deselected". What you are seeing is that each item changes state twice, from delected to selected and vice versa. Check the result of this method to filter out the unwanted state changes.
    BTW don't use Choice, its AWT not swing.

  • JComboBox  itemStateChanged gets called twice.

    Hi i have a JComboBox whoes itemStateChanged gets called twice. I have taken a look at other post concerning this topic and non have worked for me . I will greatly appreciate it if someone can help me
    here is the code !!!!!!!!!!
    jComboBox3.addItemListener(new ItemListener(){
    public void itemStateChanged(ItemEvent e) {
    if(e.getStateChange() == e.SELECTED){
    jComboBox3_dosomething(e);
    thanks in advance

    Maybe this thread will answer why it gets called twice:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=257226

  • JCombobox on a jtabbed pane, AND Choice on jtabbed pane problems

    I have a Choice on a jtabbed pane, on a panel that isn't showing when the jtabbed pane is made visible. The Choice on the hidden pane is "bleeding" through to the first tabbed panel. help!
    If I click on the second tabbed panel (where the Choice is), and then click on the first tabbed panel, the Choice becomes hidden like it is supposed to.
    AND, I have a JComboBox on a JTabbedPane, it works for the most part, but when you click on it, the scrollbox underneath it doesn't appear! Instead, a grey box appears below it. Help!

    I was having similar problems when I was working with JFrames, Anything not covered by a piece of GUI would show other parts of my program (like the progress bar or buttons and stuff).
    Anyway, it went away when I used the setBackground() method. My guess is that using this forces the container to be opaque or something. Anyway, it worked for me, maybe it will work for you also.
    Steve

  • JComboBox Lost Listener on Look and Feel change

    When the user change the Look And Feel on the Fly , any Listener that is done using
    myComboBox.getEditor().getEditorComponent().addXXXListener
    is lost
    I'm using Windows XP Service Pack 2, java 6 build 105
    Does someone have any inputs why this happen or how this can be "fixed" or maybe prevent. Do I'm doing something wrong?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    /* ComboBoxDemo2.java requires no other files. */
    public class ComboBoxDemo2 extends JPanel
                               implements ActionListener {
        static JFrame frame;
        JLabel result;
        String currentPattern;
        public ComboBoxDemo2() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            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"
            currentPattern = patternExamples[0];
            //Set up the UI for selecting a pattern.
            JLabel patternLabel1 = new JLabel("Enter the pattern string or");
            JLabel patternLabel2 = new JLabel("select one from the list:");
            JComboBox patternList = new JComboBox(patternExamples);
            patternList.setEditable(true);
            patternList.addActionListener(this);
    //-------------------------------- XXX------------------------------------------
    //      This KeyListener it is lost when the user change the theme on the fly       
            patternList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
            public void keyPressed(KeyEvent e)
             System.out.println(" Key pressed is "+e.getKeyCode());     
            //Create the UI for displaying result.
            JLabel resultLabel = new JLabel("Current Date/Time",
                                            JLabel.LEADING); //== LEFT
            result = new JLabel(" ");
            result.setForeground(Color.black);
            result.setBorder(BorderFactory.createCompoundBorder(
                 BorderFactory.createLineBorder(Color.black),
                 BorderFactory.createEmptyBorder(5,5,5,5)
            //Lay out everything.
            JPanel patternPanel = new JPanel();
            patternPanel.setLayout(new BoxLayout(patternPanel,
                                   BoxLayout.PAGE_AXIS));
            patternPanel.add(patternLabel1);
            patternPanel.add(patternLabel2);
            patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
            patternPanel.add(patternList);
            JPanel resultPanel = new JPanel(new GridLayout(0, 1));
            resultPanel.add(resultLabel);
            resultPanel.add(result);
            patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(patternPanel);
            add(Box.createRigidArea(new Dimension(0, 10)));
            add(resultPanel);
            setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            reformat();
        } //constructor
        public void actionPerformed(ActionEvent e) {
             System.out.println("Action Event");                
            JComboBox cb = (JComboBox)e.getSource();
            String newSelection = (String)cb.getSelectedItem();
            currentPattern = newSelection;
            reformat();
        /** Formats and displays today's date. */
        public void reformat() {
             try {
            Date today = new Date();
            SimpleDateFormat formatter =
               new SimpleDateFormat(currentPattern);
                String dateString = formatter.format(today);
                result.setForeground(Color.black);
                result.setText(dateString);
            }catch (IllegalArgumentException iae) {     
            System.out.println("Ilegal argument Exception");   
            catch (Exception e) {
            System.out.println("Argument Exception");                
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            final JFrame frame = new JFrame("ComboBoxDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ComboBoxDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());      
            //frame.setContentPane(newContentPane,BorderLayout.CENTER);
            JMenuBar menuBar = new JMenuBar();
            JMenu theme = new JMenu("Theme");
            ButtonGroup bttnGroup = new ButtonGroup();
            JCheckBoxMenuItem metal = new JCheckBoxMenuItem("Metal");
            bttnGroup.add(metal);
            metal.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
              theme.add(metal);
            JCheckBoxMenuItem system = new JCheckBoxMenuItem("System");
            bttnGroup.add(system);
            system.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
            theme.add(system);
            menuBar.add(theme);     
            frame.setJMenuBar(menuBar);
            JToolBar jtb = new JToolBar();
            jtb.add(newContentPane);
            frame.add(jtb, BorderLayout.PAGE_START);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thanks to both Rodney_McKay and jasper for their replys and ideas
    This code is working fine
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import java.text.SimpleDateFormat;
    /* ComboBoxDemo2.java requires no other files. */
    public class ComboBoxDemo2 extends JPanel
                               implements ActionListener {
        static JFrame frame;
        JLabel result;
        String currentPattern;
        private JComboBox patternList = new JComboBox();
        public ComboBoxDemo2() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            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"
            currentPattern = patternExamples[0];
            //Set up the UI for selecting a pattern.
            JLabel patternLabel1 = new JLabel("Enter the pattern string or");
            JLabel patternLabel2 = new JLabel("select one from the list:");
            patternList = new JComboBox(patternExamples){
            public void updateUI(){
            System.out.println("UPDATE UI");
            super.updateUI();     
            changeUIAddEditorListener();
            changeUIAddEditorListener();
            patternList.setEditable(true);
            patternList.addActionListener(this);
            //Create the UI for displaying result.
            JLabel resultLabel = new JLabel("Current Date/Time",
                                            JLabel.LEADING); //== LEFT
            result = new JLabel(" ");
            result.setForeground(Color.black);
            result.setBorder(BorderFactory.createCompoundBorder(
                 BorderFactory.createLineBorder(Color.black),
                 BorderFactory.createEmptyBorder(5,5,5,5)
            //Lay out everything.
            JPanel patternPanel = new JPanel();
            patternPanel.setLayout(new BoxLayout(patternPanel,
                                   BoxLayout.PAGE_AXIS));
            patternPanel.add(patternLabel1);
            patternPanel.add(patternLabel2);
            patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
            patternPanel.add(patternList);
            JPanel resultPanel = new JPanel(new GridLayout(0, 1));
            resultPanel.add(resultLabel);
            resultPanel.add(result);
            patternPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            resultPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
            add(patternPanel);
            add(Box.createRigidArea(new Dimension(0, 10)));
            add(resultPanel);
            setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            reformat();
        } //constructor
        public void actionPerformed(ActionEvent e) {
             System.out.println("Action Event");                
            JComboBox cb = (JComboBox)e.getSource();
            String newSelection = (String)cb.getSelectedItem();
            currentPattern = newSelection;
            reformat();
        /** Formats and displays today's date. */
        public void reformat() {
             try {
            Date today = new Date();
            SimpleDateFormat formatter =
               new SimpleDateFormat(currentPattern);
                String dateString = formatter.format(today);
                result.setForeground(Color.black);
                result.setText(dateString);
            }catch (IllegalArgumentException iae) {     
            System.out.println("Ilegal argument Exception");   
            catch (Exception e) {
            System.out.println("Argument Exception");                
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Create and set up the window.
            final JFrame frame = new JFrame("ComboBoxDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ComboBoxDemo2();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setLayout(new BorderLayout());      
            //frame.setContentPane(newContentPane,BorderLayout.CENTER);
            JMenuBar menuBar = new JMenuBar();
            JMenu theme = new JMenu("Theme");
            ButtonGroup bttnGroup = new ButtonGroup();
            JCheckBoxMenuItem metal = new JCheckBoxMenuItem("Metal");
            bttnGroup.add(metal);
            metal.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
              theme.add(metal);
            JCheckBoxMenuItem system = new JCheckBoxMenuItem("System");
            bttnGroup.add(system);
            system.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent e){
              try{
              UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              SwingUtilities.updateComponentTreeUI(frame);
              }catch(Exception a){a.printStackTrace();}
            theme.add(system);
            menuBar.add(theme);     
            frame.setJMenuBar(menuBar);
            JToolBar jtb = new JToolBar();
            jtb.add(newContentPane);
            frame.add(jtb, BorderLayout.PAGE_START);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
       public void changeUIAddEditorListener() {
       patternList.getEditor().getEditorComponent().addKeyListener(new KeyAdapter()
       public void keyPressed(KeyEvent e)
       System.out.println(" Key pressed is "+e.getKeyCode());     
    }

  • JComboBox changes between 1.3 and 1.4

    Can anyone tell me if what I'm observing is true? It seems to me that the default selected index for JComboBox was 0 in java 1.3 and is -1 in 1.4. This is causing me some major problems (with someone else's code) and I would like confirmation that this is my problem and not something else.
    Any help is appreciated.

    and is -1 in 1.4. Show us the 10 line demo program you used to test this statement.
    I've never had a problem.

  • JComboBox selection actions on mouse and enter only

    I am driving some processing off of selections in a JComboBox.
    The ItemListener goes into action when the user mouse clicks on an item (this is good), but also when an item is arrowed through (bad).
    I want to wait until the person hits enter before starting my processing.
    Ideally the JComboBox popup could close before the start of my processing.
    The direction I am currently headed: I notice that when the mouse clicks, and when enter is hit, the JComboBox popup closes. Since these are the 2 user events I want to respond to, this fact interests me greatly. Is there any way to see and use the event of the popup closing?
    Note: I don't care so much about the direction I am thinking now as much as a solution to the overall problem.

    Try to register a KeyListener to the JComboBox or to its editor (if its editable) and react to the keyReleased Event. In the corresponding listener method you have to query the key typed and react to the ENTER key being pressed. Also get away from the ItemListener as the JComboBox / ItemListene combination is not the best the guys at sun farbricated...

  • Nested JComboBox itemStateChanged conundrum

    Hey, I'm new to the forums, so don't cuss me out yet.
    I need to have nested ComboBoxes, but am running into some goofy loops that prevent me from doing what I need.
    I have clients who have projects and each project has a description.
    In my dialog, there's a combobox where you select a client. the client combobox has an itemstatechange listener that removes all the items from the project combobox and then loads the projects belonging to the selected client into the project combobox.
    Great. this works. BUT, when I add an itemstatechange listener to the project combobox, to fire a description_field.setText("whatever"), I have huge problems.
    -- When I select a client, the itemStateChangeListener removes all items from the project combobox, which then fires the project itemstateChangeListener, which updates the description field, then the client combo listener adds the first project to the combo, which fires the project listener again, and so on and so forth. It's chaos, and creates a nasty loop and mysql server dumps me for having too many connections.
    Here's some code snippets. I need some suggestions.
    private void projectView_client_comboBoxItemStateChanged(java.awt.event.ItemEvent evt) {                                                            
    DBAccess dbsql = new DBAccess();
    String companyName = (String)projectView_client_comboBox.getSelectedItem();
    int companyid = dbsql.getID("client", "company", companyName);
    String[] data = dbsql.fillComboBox("projectname", "project", "client_id", companyid);
    //q is the DefaultComboBoxModel for the projectComboBox
    //it's "q" because NetBeans won't let me change it to anything with more than one character
    q.removeAllElements();
    for(int r=0; r<data.length; r++){
    q.addElement(data[r]);
    //This GetItButton is the only way I could hack this together. I'd rather have this code in the project_comboBoxItemStateListener.
    private void projectView_getIt_buttonActionPerformed(java.awt.event.ActionEvent evt) {               
    DBAccess dbsql = new DBAccess();
    Object[] selectedItem = new Object[1];
    selectedItem[0] = projectView_projectName_comboBox.getSelectedItem();
    String selectedItemStr = (String)selectedItem[0];
    if(selectedItemStr.equalsIgnoreCase("<none>")) {
    // Do nothing, since no records exist with the projectname of "<None>"
    else if(selectedItemStr.equalsIgnoreCase("<new>")){
    newProject_dialog.setVisible(true);
    else{
    // A valid project has been selected
    String[] projStr = {"projectname"};
    //Finds the project record with the project name of the selectedItem in project_comboBox
    Object[] record = dbsql.findRecord("project", projStr, selectedItem);
    //sets the description field to the third column in the given record (description)
    projectView_description_field.setText((String)record[2]);
    }

    Would you always recommend using ActionListeners for comboboxes?No, it depends on what you are trying to do. That said, for what most are
    generally trying to do with a combobox, ActionListeners are usually the correct
    choice.

  • Get help with JComboBox, itemStateChange

    hi, i get quite complex a problem.
    i have a list containing 2 types of list. one list is the car model and the other is the car type.
    so in one combo box, there will be a list of car model. when one car is selected in this, the other combo box will automatically update all the available car type (e.g. car model is BMW and car type is 318).
    i dont know how to keep the second combo box updated immediately after item of the first combo box changes state.
    some one help me pls

    hi,
    thanks for replying but my problem seems too hard for me.
    i just got another problem.
    i still have the file with a number of JFrames inside and the first, or considered to be the "main" JFrame. Now, when i click a button, a second JFrame after that will pop up but I dont know how to setVisible(false) for the main window using Netbeans. could you please help me do that?
    thanks alot

  • JComboBox - different behaviour in 1.3 and 1.4

    I have noticed that there is a difference in JCombobox behaviour in 1.3 and 1.4.
    I think it is better to give the program than explaining the issue.
    the below given program shows the difference.
    import javax.swing.* ;
    import java.awt.* ;
    import java.awt.event.* ;
    import java.util.* ;
    * Test program to show difference between
    * Combo behaviour in java1.3 and 1.4
    public class CTest extends JFrame
         private JComboBox combo1 ;
         private JComboBox combo2 ;
         public CTest()
              super() ;
         public void init()
         combo1 = new JComboBox() ;
              combo1.addItemListener( new ItemListener()
                        public void itemStateChanged( ItemEvent event )
                        if (null != combo1.getSelectedItem() && event.getStateChange() == ItemEvent.SELECTED)
                             loadCombo2(combo1.getSelectedIndex()+1) ;
         combo2 = new JComboBox() ;
              combo2.addItemListener( new ItemListener()
                        public void itemStateChanged( ItemEvent event )
                        if (null != combo2.getSelectedItem() && event.getStateChange() == ItemEvent.SELECTED)
                             System.out.println("Combo2 item selected : "+ combo2.getSelectedItem()) ;
              JPanel panel = new JPanel(new BorderLayout()) ;
              panel.add(combo1,BorderLayout.NORTH) ;
              panel.add(combo2,BorderLayout.SOUTH) ;
              getContentPane().add(panel) ;
         public void loadCombo1()
              combo1.removeAllItems() ;
              for (int iCount = 0 ; iCount <5 ; iCount++)
                   String strItem = "Item : "+iCount ;
              combo1.addItem(strItem) ;
              try
                   combo1.setSelectedIndex(0) ;
              catch(Exception e)
         private void loadCombo2(int itemCount)
              combo2.removeAllItems() ;
              for (int iCount = 0 ; iCount <itemCount ; iCount++)
                   String strItem = "Item : "+iCount ;
              combo2.addItem(strItem) ;
              try
                   combo2.setSelectedIndex(0) ;
              catch(Exception e)
         public static final void main(String args[])
              CTest app = new CTest() ;
              app.init() ;
              app.setSize(100,100) ;
              app.setVisible(true) ;
              app.loadCombo1() ;
    In jdk1.3 every time you change the selection in combo 1 there will be selection change in combo 2 also. but not in jdk1.4.
    i am not sure whether it is a bug. But surely te behaviour is different.
    any comments on this issue???

    Anil,
    I've just noticed this as well, so I had a quick look at the 1.4 sources. Quite simply, adding and removing items in a JComboBox will never fire an ItemStateChangedEvent, even if the selected item does change.
    The culprits are intervalAdded() and intervalRemoved() in JComboBox.java. Under 1.3 these methods called contentsChanged() which would then fire an ItemStateChangedEvent if necessary. Under 1.4, these methods are empty. Why? I have no idea. It seems like a bug to me, but can't see anything in the bug database about it. Hope someone from Sun can explain it.
    Regards,
    Peter

  • Get , store and retrieve values from JComboBox, JT.......

    please can you show me how to collect informations from some JComponents like JComboBox, JList , JTextField, JTextArea etc and store them on clicking on a single button and also retreiving them by clicking on another single button

    below are some functions that u can use:
    JComboBox: getSelectedItem()
    JList: getSelectedValue()
    JTextField, JTextArea: getText()
    basically u need to have button, add an action listener for the button, and store the value using the above functions when the button is clicked.
    hth.

  • Disabling UP and DOWN arrow keys in JComboBox

    I noticed that JComboBox by default toggles the popup menu up or down when it has focus and the user presses UP and DOWN arrow keys (I am working with JRE 1.3.1). I think this is not consistent with the documented key assignments for JComboBox. But -apart of this- I am trying without success to write a JComboBox extension that ignores UP and DOWN keys.
    Does anyone have any idea? Thanks in advance!

    Hi,
    something like this?:public class MyCombo extends JComboBox {
         public MyCombo() {
              super();
              addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
                        if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) {
                             e.consume();
    }

  • Any possibility for loading and changing XFL/... data at run time of Flash app?

    Hi everybody,
    I have a quick and general question for the following case:
    I want to produce some transitions and effects for a kinetic typography project in After Effects and then import these parts into Flash Professional via XFL and Bridge.
    So my actual problem is this one: my Flash application should be able to load these made transitions and effects dynamically at run-time and not from a pre-configured timeline made upfront. Because there should be dynamic text fields in these XFL data from After Effects I also need to be loaded at run-time for the kinetic typography thing.
    So is there any possible way to do / load / change the dynamic text fields in these XFL data or the order of all transitions and effects in Flash Professional at run-time or anything else?
    I know this is a special question, but I hope there would be an answer...
    Thanks for your help in advance
    Regards,
    Kevin

    Something along this model is what I had in mind:
    public class MainPanel extends JPanel
        private DrawPanel drawPanel = new DrawPanel();
        private JComboBox comboLeft = new JComboBox();
        private JComboBox comboRight = new JComboBox();
        public MainPanel()
            // add drawpanel and comboboxes to main panel
            // add item listener to comboboxes
        private class ComboListener implements ItemListener
            @Override
            public void itemStateChanged(ItemEvent arg0)
                if (...) // both comboboxes changed
                    // get values from comboboxes
                    drawPanel.setValues(left, right); // call drawpanel's method
    public class DrawPanel extends JPanel
        private int left = 0;
        private int right = 0;
        public DrawPanel()
            //setPreferredSize(....); // set panel size
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            //... draw the line depending on the left and right value
        public void setValues(int left, int right)
            this.left = left;
            this.right = right;
            repaint();
    }

  • Accessing values in an array of JComboBoxes

    Hello. I am building a program to calculate a user's GPA. This is a class assignment and so has some requirements I'm meeting.
    There are two event handlers: One runs a loop to add course input lines; one calculates the GPA based on the inputs.
    There are two related problems: When I instantiate JComboBoxes into two arrays (credits[] and grade[]) in the loop, the layout works but the calculate button only returns the values of credits[0] and grade[0] regardless of selection. When I instantiate the arrays outside the loop, the calculate button works but not the layout. I am at a complete loss. I'm posting the full code with comments. Sorry for it being very long.
    package macdonnell_COMP228Lab4_Ex1;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GPACalc extends JFrame {
         private String[] letterGrades = {"A+","A","B+","B","C+","C","D+","D","Fail"}; // Values to be used in combGrades
         private double[] gradePoints = {4.5,4.0,3.5,3.0,2.5,2.0,1.5,1.0,0};
         private String[] numberCourses = {"0","1","2","3","4","5","6","7","8"}; // Used to fill cbNumberCourses
         private String[] creditHours = {"1","2","3","4"}; //number of hours per week in the class
         private String[] numberGrades = {"90-100%","80-89%","75-79%","70-74%","65-69%","60-64%","55-59%","50-54%","0-49%"};
         private String[] combGrades = new String[9]; // Used to fill the JComboBox in grade[]
         //Arrays to hold JComboBoxes for Course Inputs
         private JComboBox[] credits = new JComboBox[8];
         private JComboBox[] grade = new JComboBox[8];
         private JLabel lblCreditHoursEarned = new JLabel("Credit Hours Earned: ");
         private JTextField txtCreditHoursEarned = new JTextField(5);
         private JLabel lblCurrentGPA = new JLabel("Current GPA: ");
         private JTextField txtCurrentGPA = new JTextField(5);
         private JLabel lblNumberCourses = new JLabel("Number of Courses: ");
         private JComboBox cbNumberCourses = new JComboBox(numberCourses); //ComboBox for users to select number of course inputs
         private JLabel lblNumber = new JLabel("Number: ");
         private JLabel lblCourseCode = new JLabel("Course Code: ");
         private JLabel lblCreditHours = new JLabel("Credit Hours: ");
         private JLabel lblGrade = new JLabel("Grade: ");
         private JLabel label;
         private JTextField coursCode;
         GridBagLayout gridBag;
         Container c;
         private JButton calculate = new JButton("Calculate");
         CalculateButtonHandler calculateButton = new CalculateButtonHandler();
         private JLabel lblYourGPA;
         public GPACalc(){
              for (int i = 0; i < combGrades.length; i++){
                   combGrades[i] = letterGrades[i] + ": " + numberGrades;
              /* This block is used for instantiating the JComboBoxes in credits[] and grade[] outside the loop
              //Assign course input ComboBoxes to arrays
              credits[0] = new JComboBox(creditHours);
              credits[1] = new JComboBox(creditHours);
              credits[2] = new JComboBox(creditHours);
              credits[3] = new JComboBox(creditHours);
              credits[4] = new JComboBox(creditHours);
              credits[5] = new JComboBox(creditHours);
              credits[6] = new JComboBox(creditHours);
              credits[7] = new JComboBox(creditHours);
              grade[0] = new JComboBox(combGrades);
              grade[1] = new JComboBox(combGrades);
              grade[2] = new JComboBox(combGrades);
              grade[3] = new JComboBox(combGrades);
              grade[4] = new JComboBox(combGrades);
              grade[5] = new JComboBox(combGrades);
              grade[6] = new JComboBox(combGrades);
              grade[7] = new JComboBox(combGrades);
              gridBag = new GridBagLayout();
         c = getContentPane();
         c.setLayout(gridBag);
         // ROW 1
         GridBagConstraints Constr1 = new GridBagConstraints();
         Constr1.gridx = 0; //first column
         Constr1.gridy = 0; //first row
         Constr1.gridwidth = 2; //number of cells in the row that will be covered
         Constr1.gridheight = 1; //number of cells in the column
         Constr1.fill = GridBagConstraints.HORIZONTAL; //resize the component horizontally
         // add the text field
         gridBag.setConstraints(lblCreditHoursEarned, Constr1); //apply the constraints to the grid
         c.add(lblCreditHoursEarned);
         GridBagConstraints Constr2 = new GridBagConstraints();
         Constr2.gridx = 3; //second column
         Constr2.gridy = 0; //first row
         Constr2.gridwidth = 1; //number of cells in the row that will be covered
         Constr2.gridheight = 1; //number of cells in the column
         Constr2.fill = GridBagConstraints.HORIZONTAL; //resize the component horizontally
         // add the text field
         gridBag.setConstraints(txtCreditHoursEarned, Constr2); //apply the constraints to the grid
         c.add(txtCreditHoursEarned);
         GridBagConstraints Constr3 = new GridBagConstraints();
         Constr3.gridx = 5; //fourth column
         Constr3.gridy = 0; //first row
         Constr3.gridwidth = 1; //number of cells in the row that will be covered
         Constr3.gridheight = 1; //number of cells in the column
         Constr3.fill = GridBagConstraints.HORIZONTAL; //resize the component horizontally
         // add the text field
         gridBag.setConstraints(lblCurrentGPA, Constr3); //apply the constraints to the grid
         c.add(lblCurrentGPA);
         GridBagConstraints Constr4 = new GridBagConstraints();
         Constr4.gridx = 6; //fifth column
         Constr4.gridy = 0; //first row
         Constr4.gridwidth = 1; //number of cells in the row that will be covered
         Constr4.gridheight = 1; //number of cells in the column
         Constr4.fill = GridBagConstraints.HORIZONTAL; //resize the component horizontally
         // add the text field
         gridBag.setConstraints(txtCurrentGPA, Constr4); //apply the constraints to the grid
         c.add(txtCurrentGPA);
         //ROW 2
         GridBagConstraints Constr5 = new GridBagConstraints();
         Constr5.gridx = 5; //fourth column
         Constr5.gridy = 1; //second row
         Constr5.gridwidth = 1; //number of cells in the row that will be covered
         Constr5.gridheight = 1; //number of cells in the column
         Constr5.fill = GridBagConstraints.HORIZONTAL; //resize the component horizontally
         // add the text field
         gridBag.setConstraints(lblNumberCourses, Constr5); //apply the constraints to the grid
         c.add(lblNumberCourses);
         GridBagConstraints Constr6 = new GridBagConstraints();
         Constr6.gridx = 6; //fourth column
         Constr6.gridy = 1; //second row
         Constr6.gridwidth = 1; //number of cells in the row that will be covered
         Constr6.gridheight = 1; //number of cells in the column
         Constr6.fill = GridBagConstraints.HORIZONTAL; //resize the component horizontally
         // add the text field
         gridBag.setConstraints(cbNumberCourses, Constr6); //apply the constraints to the grid
         c.add(cbNumberCourses);
         //ROW 3
         GridBagConstraints Constr7 = new GridBagConstraints();
         Constr7.gridx = 0;
         Constr7.gridy = 2;
         Constr7.gridwidth = 1;
         Constr7.gridheight = 1;
         Constr7.fill = GridBagConstraints.HORIZONTAL;
         gridBag.setConstraints(lblNumber, Constr7);
         c.add(lblNumber);
         GridBagConstraints Constr8 = new GridBagConstraints();
         Constr8.gridx = 2;
         Constr8.gridy = 2;
         Constr8.gridwidth = 1;
         Constr8.gridheight = 1;
         Constr8.fill = GridBagConstraints.HORIZONTAL;
         gridBag.setConstraints(lblCourseCode, Constr8);
         c.add(lblCourseCode);
         GridBagConstraints Constr9 = new GridBagConstraints();
         Constr9.gridx = 4;
         Constr9.gridy = 2;
         Constr9.gridwidth = 1;
         Constr9.gridheight = 1;
         Constr9.fill = GridBagConstraints.HORIZONTAL;
         gridBag.setConstraints(lblCreditHours, Constr9);
         c.add(lblCreditHours);
         GridBagConstraints Constr10 = new GridBagConstraints();
         Constr10.gridx = 6;
         Constr10.gridy = 2;
         Constr10.gridwidth = 1;
         Constr10.gridheight = 1;
         Constr10.fill = GridBagConstraints.HORIZONTAL;
         gridBag.setConstraints(lblGrade, Constr10);
         c.add(lblGrade);
         //ROW 4 is built by the event handler cbNumberCourses.addItemListener at line 191; insert panel to hold ROW 4
         //ROW 5
         GridBagConstraints Constr11 = new GridBagConstraints();
         Constr11.gridx = 6;
         Constr11.gridy = 11;
         Constr11.gridwidth = 1;
         Constr11.gridheight = 1;
         Constr11.fill = GridBagConstraints.HORIZONTAL;
         gridBag.setConstraints(calculate, Constr11);
         c.add(calculate);
         //ROW 6 is added in the SubmitButtonHandler at line 242
         calculate.addActionListener(calculateButton);
         cbNumberCourses.addItemListener(
                   new ItemListener(){
                        public void itemStateChanged(ItemEvent e){
                             for (int i = 0; i < cbNumberCourses.getSelectedIndex(); i++){
                                  label = new JLabel(Integer.toString(i+1));
                                  coursCode = new JTextField(10);
                                  GridBagConstraints ConstrA = new GridBagConstraints();
                                  ConstrA.gridx = 0;
                                  ConstrA.gridy = i+4;
                                  ConstrA.gridwidth = 1;
                                  ConstrA.gridheight = 1;
                                  ConstrA.fill = GridBagConstraints.HORIZONTAL;
                                  gridBag.setConstraints(label, ConstrA);
                                  c.add(label);
                                  GridBagConstraints ConstrB = new GridBagConstraints();
                                  ConstrB.gridx = 2;
                                  ConstrB.gridy = i+4;
                                  ConstrB.gridwidth = 1;
                                  ConstrB.gridheight = 1;
                                  ConstrB.fill = GridBagConstraints.HORIZONTAL;
                                  gridBag.setConstraints(coursCode, ConstrB);
                                  c.add(coursCode);
                                  credits[i] = new JComboBox(creditHours);
                                  GridBagConstraints ConstrC = new GridBagConstraints();
                                  ConstrC.gridx = 4;
                                  ConstrC.gridy = i+4;
                                  ConstrC.gridwidth = 1;
                                  ConstrC.gridheight = 1;
                                  ConstrC.fill = GridBagConstraints.HORIZONTAL;
                                  gridBag.setConstraints(credits[i], ConstrC);
                                  c.add(credits[i]);
                                  grade[i] = new JComboBox(combGrades);
                                  GridBagConstraints ConstrD = new GridBagConstraints();
                                  ConstrD.gridx = 6;
                                  ConstrD.gridy = i+4;
                                  ConstrD.gridwidth = 1;
                                  ConstrD.gridheight = 1;
                                  ConstrD.fill = GridBagConstraints.HORIZONTAL;
                                  gridBag.setConstraints(grade[i], ConstrD);
                                  c.add(grade[i]);
                             c.validate();
         private class CalculateButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   double creds, points, qualityPoints, gpa;
                   double totalQualityPoints = 0;
                   double totalCredits = 0;
                   for (int i = 0; i < cbNumberCourses.getSelectedIndex(); i++){
                        System.out.println(i);
                        System.out.println(credits[i].getSelectedItem());
                        System.out.println(grade[i].getSelectedItem());
                        //creds = Double.parseDouble(creditHours[credits[i].getSelectedIndex()]);
                        creds = Double.parseDouble((String)credits[i].getSelectedItem());
                        points = gradePoints[grade[i].getSelectedIndex()];
                        totalCredits = totalCredits + creds;
                        qualityPoints = creds * points ;
                        totalQualityPoints = totalQualityPoints + qualityPoints;
                        System.out.println(creds);
                        System.out.println(points);
                   gpa = totalQualityPoints / totalCredits;
                   String yourGPA = "Your GPA is: " + gpa;
                   lblYourGPA = new JLabel(yourGPA);
                   GridBagConstraints Constr12 = new GridBagConstraints();
              Constr12.gridx = 3;
              Constr12.gridy = 12;
              Constr12.gridwidth = 1;
              Constr12.gridheight = 1;
              Constr12.fill = GridBagConstraints.HORIZONTAL;
              gridBag.setConstraints(lblYourGPA, Constr12);
              c.add(lblYourGPA);
              c.validate();
         public static void main(String[] args) {
              GPACalc mf = new GPACalc();
              mf.setSize(650,700);
              mf.setVisible( true ); // display frame

    I changed the cbNumberCourses.addItemListener to an ActionListener. For whatever reason, this has fixed all my problems.

Maybe you are looking for

  • How can we handle browser settings while dealing with the security ?

    Hi , how can we handle browser settings while dealing with the security ?When we configured security in web.xml , during the first request the container is asking for the authentication credentials once they are provided it go's on. but when the user

  • SCOM 2012 Report error rsprocessingaborted rserrorexecutingcommand

    Hello All, I am able to run some reports from SCCM 2012 console but few of them do not work. Error in SCOM console when I try to run the report An error has occurred during report processing. (rsProcessingAborted) Query execution failed for dataset '

  • Fnd_user_pkg.updateuser - Remove End Date from Users

    As part of an upgrade, we need to end-date the vast majority of our users. I've used the fnd_user_pkg.updateuser API to populate the end_date on the fnd_user table. However, when I've come to test removing the end-date, I can't seem to do it. In the

  • Pc connected behind 7942g network issues

    All I have a situation where computers connected directly to a 7942 ip phone see a large reduction in network speed. If I remove the phone out of the equation and have the computer connected directly to the Ethernet network downloads become 20 times

  • Serious problem with open Pictuer or make a new pictuer..

    hey guys i have serious Problem with my ps cs6 when i open a pictuer or make a new Pictuer no thing happend's like i didn't do anything. and no thing come out.. i hope some one can help me out. thanks !