簡體   English   中英

在線程awt-eventqueue-1 java.lang.nullpointerexception中獲取異常?

[英]getting exception in thread awt-eventqueue-1 java.lang.nullpointerexception?

在線程awt-eventqueue-1中獲取異常java.lang.nullpointerexception? 錯誤的根源是什么? 我想創建一個applet來反轉給定的string。

public class MyApp extends Applet implements ActionListener
{
Panel p1,p2;
TextField tf[]= new TextField[2];
public void init()
{
    setBackground(Color.cyan);

}
public void start()
{
    TextField tf[]= new TextField[2];
    tf[0] = new TextField();
    tf[0].setColumns(20);
    Label l1=new Label("String:");
    p1 = new Panel();
    p1.add(l1);
    p1.add(tf[0]);
    p1.setLayout(new FlowLayout());

    tf[1] = new TextField();
    tf[1].setColumns(20);
    Button l2=new Button("Reverse:");
    l2.addActionListener(this);
    p2 = new Panel();
    p2.add(l2);
    p2.add(tf[1]);
    p2.setLayout(new FlowLayout());
    add(p1);
    add(p2);

}
public void actionPerformed(ActionEvent ae)
{
    tf[1].setText("hiii");  
    if(ae.getActionCommand()=="Reverse:")
    {
    StringBuffer sb=new StringBuffer(tf[0].getText());
    String s= new String(sb.reverse());
    tf[1].setText("hiii");  
    }
}


}

您在類和方法start都聲明了數組tf
因此,您在start中初始化的不是類成員,而是start本地的變量。 成員變量tf保持為null

所以,在start ,改變

TextField tf[]= new TextField[2];

tf[]= new TextField[2];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM