print an array items in a JTextField

馋奶兔 提交于 2019-12-12 00:49:12

问题


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);

    }

}

回答1:


Rewrite the code as:

String valueToBeInserted="";

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

 jtext.setText(valueToBeInserted);



回答2:


You're running through the loop without doing anything. When you finally get out of the loop j will indeed have become 3 as it doesn't match the j is less than strArray.length condition. But since Arrays are 0 based in java, you are trying to get the fourth element of a three element array.

The following code should fix your issue. Place this instead of your for loop.

StringBuilder sb=new StringBuilder();
for(int j=0;j< strArray.length;j++)
{
   sb.append(strArray[j]);
}
jtext.setText(sb.toString());


来源:https://stackoverflow.com/questions/15383750/print-an-array-items-in-a-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!