Skip to content

No output after button click, since the variable doesn’t exist?

I wanted a frame with one TextArea and one Button. When I press the button, the TextArea should show a food menu of 5 Pizzas, well it shows nothing at all, except for the console which shows

"Exception in thread "AWT-EventQueue-0"  
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)

In the method windowsStart() the objects exists and are adjustable. In the actionPerformed()Method the objects are … kind of invisible, not existing?

public void windowStart()
    MainFrame mFrame = new MainFrame();
    PizzaReader2 test = new PizzaReader2();
    pPizza = test.csvRead();
    System.out.println("nnn" + pPizza.get(0) + "nnn");

    f = new JFrame("Textfield");
    b = new JButton("Menu");
    jt = new JTextArea(10,10);
    JPanel pTextArea = new JPanel();


    f.setSize(300, 300);
public void actionPerformed(ActionEvent e) 
    System.out.println("nnn" + pPizza.get(0) + "nnn");
    String s = e.getActionCommand(); 
    if (s.equals("Menu")) 
        System.out.println("Button gedrückt");
        for (int i = 0; i < pPizza.size(); i++) 

The TextArea should get the value of the ArrayList



Your exception occurs in : at

This action is linked during windowStart with b.addActionListener(mFrame);.

But What I see is that you pass another instance of MainFrame called mFrame as parameter (as an ActionListener). This mFrame never load the list with

pPizza = test.csvRead();

So in short, you have two instance MainFrame:

  • one created and use to call windowStart
  • one created in windowsStart and use to execute actionPerformed.

This last one never load the list of data. Explaining why your list is populated in windowStart but not in actionPerformed, you are actually using two distinct instance MainFrame with two list pPizza.

You can correct this by removing this second instance and use this, the first instance as an ActionListener