在JTextField中打印数组项 [英] print an array items in a JTextField

查看:99
本文介绍了在JTextField中打印数组项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java swing应用程序.我的目的是将数组的元素打印到JTextField

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

但是当我按下一个jbutton时,我得到了以下异常

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

线程"AWT-EventQueue-0"中的异常java.lang.ArrayIndexOutOfBoundsException:3

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

    }

}

推荐答案

将代码重写为:

String valueToBeInserted="";

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

 jtext.setText(valueToBeInserted);

这篇关于在JTextField中打印数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆