Search code examples
javaswingloopsjcomboboxjapplet

JComboBox[] loop to show on JApplet not working


public class NewAccountApplet extends JApplet implements ActionListener{
    JPanel jp1, jp2, jp3, jp4, jp5, jp6;
    GridLayout productLO = new GridLayout(10,4,10,10);
    int qty = 5;
    JComboBox<Object>[] selectQty;

if (e.getActionCommand().equals("Login")) {

    if (id.equals(checkID) && pw.equals(checkPW)) {
    JOptionPane.showMessageDialog(null, "Authenticated");
    JPanel content = (JPanel)getContentPane(); 
    GridBagConstraints firstCol = new GridBagConstraints(); 
    firstCol.weightx = 1.0; 
    firstCol.anchor = GridBagConstraints.WEST; 
    firstCol.insets = new Insets(5, 20, 5, 5); 
    GridBagConstraints lastCol = new GridBagConstraints(); 
    lastCol.gridwidth = GridBagConstraints.REMAINDER; 
    lastCol.weightx = 1.0; 
    lastCol.fill = GridBagConstraints.HORIZONTAL; 
    lastCol.insets = new Insets(5, 5, 5, 20); 

    selectQty = new JComboBox[qty];

    jp1.setVisible(false);
    jp2.setVisible(false);
    jp3.setVisible(false);
    jp4.setVisible(true);
    jp5.setVisible(true);
    jp6.setVisible(true);

    String[] itemText = {"1", "2", "3", "4", "5"};
    JLabel[] items = new JLabel[6];
    JLabel purchasePage = new JLabel("Items for Purchase"); 
    jp4.add(purchasePage);
    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); 
    content.add(jp4);

    jp4 = new JPanel();
    jp5 = new JPanel(new GridBagLayout()); //set jp5 as a new jpanel with gridbaglayout
    jp6 = new JPanel(); 

    for(int i=0; (i<items.length); i++) { 
        items[i] = new JLabel(); //adds items[i] as JLabel
        items[i].setText(itemText[i]); //sets text of items as itemText[]
        jp5.add(items[i], firstCol);  //adds items to firstcol of jp5
        selectQty[i] = new JComboBox<Object>(); //JComboBox selectqty[i]
        selectQty[i].setPreferredSize(new Dimension(300, 20)); //sets the size
        jp5.add(selectQty[i], lastCol); //sadsdasd
        }

    }
    else JOptionPane.showMessageDialog(null, "Wrong account information");}

I have some questions regarding adding a JComboBox into a loop to display on my JApplet. the for loop on the bottom adds my JComboBox (selectQty) to the screen. But I get an error message on eclipse where i coded as: items[i].setText(itemText[i]);. It shows up my JPanel jp4 correctly. but the JPanel jp5 is not showing up.. I wonder what is wrong...

So to summarize, the code compiles (with other codes that are not on here), but japplet only shows jp4 jpanel, and error occrs on line: items[i].setText(itemText[i]);.


Solution

  • itemText has 5 elements {"1", "2", "3", "4", "5"} but JLabel[] items = new JLabel[6] items has 6.