Search code examples
javaswingclassjframejcombobox

Java External class JComboBox missing selection


OK, so after rethinking my design of the payroll calculator, I am trying to modularize the program into reusable pieces. I am starting off by creating a JComboBox in one class, adding it to a JFrame that I am creating in another class and then calling the JFrame in my main.

When I tested my combo box alone, it worked. However, when I create it in a class and add it to the window class, I am loosing the String array that I added. Any ideas where I am going wrong?

My Main class:

import javax.swing.*;
import java.awt.*;


  public class WindowTesting 
  {

         public static void main(String[] args) {

             CreateWindow gui = new CreateWindow();
             gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

             CreateCombo deptBox = new CreateCombo();


         }

  } 

My Window class

import javax.swing.*;
import java.awt.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author bsmith624
 */


public class CreateWindow extends JFrame {

        public CreateWindow() {

        JFrame frame1;

        CreateCombo box1 = new CreateCombo();

        frame1 = new JFrame("Department Combo Box");
        frame1.setSize(400,200);
        frame1.add(box1);
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setVisible(true);

     }

}

And finally my JComboBox class:

import javax.swing.*;
import java.awt.*;




public class CreateCombo extends JComboBox {

    public static String [] deptList = {"Marketing","IT","Accounting","Development","Payroll","Facilities"};


    /**Creates the combo box 
     * with department names
     */
    public CreateCombo () {

        JComboBox combo = new JComboBox (deptList);
        combo.setVisible(true);

    }   


}

Solution

  • You are creating another JComboBox inside your CreateCombo , is not necesary cause your CreateCombo is a JComboBox

    You have to set the model

    public CreateCombo () {
            super(); // this call JComboBox superConstructor is implicit if you don't put it
            this.setModel(new DefaultComboBoxModel(depList));
            this.setVisible(true);
    } 
    

    Or may be a better design would be making this constructor

    public CreateCombo(Object[] array ){
              super(array);
      }
    

    Im not quite sure about your design ,i think you have to review it, you have a class CreateCombo that is a JComboBox may be you don't want this, may you only want a factory of JComboBox.