简体   繁体   中英

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) at de.kvwl.pizza.MainFrame.actionPerformed(MainFrame.java:54)"

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("\n\n\n" + pPizza.get(0) + "\n\n\n");

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

    pTextArea.add(jt);
    pTextArea.add(b);
    f.add(pTextArea);

    f.setSize(300, 300);
    f.setVisible(true);
}
public void actionPerformed(ActionEvent e) 
{    
    //jt.setText("TestText");
    System.out.println("\n\n\n" + pPizza.get(0) + "\n\n\n");
     
    String s = e.getActionCommand(); 
    if (s.equals("Menu")) 
    { 
        System.out.println("Button gedrückt");
        //jt.setText("");
        for (int i = 0; i < pPizza.size(); i++) 
        {
            jt.append(pPizza.get(i)+"\n");
        }

The TextArea should get the value of the ArrayList

Your exception occurs in : at de.kvwl.pizza.MainFrame.actionPerformed(MainFrame.java:54)

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

b.addActionListener(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM