Search code examples
javaswingjtextfieldindexoutofboundsexception

print an array items in a JTextField


I have an application of java swing . my purpose to print the elements of a an array into a JTextField

but when I press a jbutton to do that I get the following exception

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 3

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



public class Main extends JFrame  implements ActionListener   {

    /**
     * @param args the command line arguments
     */

    JTextField jtext;
    JPanel panel;




    public Main()
    {

    jtext = new JTextField("                                   " );
    Container pane = getContentPane();
JButton b =new JButton("Click Me");
     panel = new JPanel();


     panel.add(jtext);
     panel.add(b);

     b.addActionListener(this);
     pane.add(panel);
    }

 public void actionPerformed(ActionEvent e)

    {
          String[] strArray = new String[] {"John", "Mary", "Bob"};
int j;
       for( j=0;j< strArray.length;j++)
  {

  }

  jtext.setText(strArray[j]);
}

    public static void main(String[] args) {
        // TODO code application logic here
       Main m = new Main();
       m.setVisible(true);

    }

}

Solution

  • Rewrite the code as:

    String valueToBeInserted="";
    
    for( j=0;j< strArray.length;j++)
     {
       valueToBeInserted=valueToBeInserted + " " + strArray[j];
     }
    
     jtext.setText(valueToBeInserted);