简体   繁体   English

如何在JLabel数组中添加

[英]How to add in JLabel array

I don't know what to do. 我不知道该怎么办。 Please help me 请帮我

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

    public class Sample{
    static JLabel label[];
    static int count = 0;

      public static void main (String [] args){
      JFrame frame = new JFrame("Sample");
      JTextField tf = new JTextField(10);
      JButton bt = new JButton("Okay");
      frame.setSize(800,600);
      frame.setLayout(new FlowLayout());
      frame.setVisible(true);
      frame.add(tf);
      frame.add(bt);


      bt.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent ae){
          int sum = count++;
          String getTF = tf.getText();
          label[count] = new JLabel(getTF);
        }
    });
      }
}

It says NullPointerException. 它说NullPointerException。 How do I add getTF to label[] ? 如何将getTF添加到label[] I am confused and I can't find the right answer someone might have something for me. 我很困惑,找不到合适的答案,可能有人会帮我。

You have not initialized your array: 您尚未初始化数组:

static JLabel label[];   // "label" reference is null

You need to initialize it with an actual array object, eg like 您需要使用实际的数组对象对其进行初始化,例如

static JLabel label[] = new JLabel[10];

However, this will then have a fixed array size (10 in this case). 但是,这将具有固定的数组大小(在这种情况下为10)。 You will not be able to add more than 10 elements to that array. 您将不能向该数组添加超过10个元素。 You should use an ArrayList instead which is a dynamically growing array: 您应该使用一个动态增长的数组ArrayList代替:

static List<JLabel> label = new ArrayList<>();

Then add your new label like 然后像这样添加新标签

label.add(new JLabel(getTF));

Besides that, you should use static fields only if absolutely necessary - better create an instance of your application class and make the fields non-static. 除此之外,仅在绝对必要时才应使用static字段-更好地创建应用程序类的实例,并使字段为非静态。

You should also remove the wild card imports (like java.util.* ) and only import those classes and interfaces which you require (like java.util.List and java.util.ArrayList ). 您还应该删除通配符导入(如java.util.* ),而仅导入所需的类和接口(如java.util.Listjava.util.ArrayList )。 Otherwise you might get name clashes (like between java.awt.List and java.util.List ) 否则,您可能会遇到名称冲突(例如java.awt.Listjava.util.List之间)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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