当前位置: 代码迷 >> J2SE >> 一个内部类的有关问题
  详细解决方案

一个内部类的有关问题

热度:83   发布时间:2016-04-24 13:20:28.0
一个内部类的问题
源程序如下:
[code=Java][/code]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class Text1
{
public static void main(String[] args)
{
TextFrame frame = new TextFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}


}

class TextFrame extends JFrame
{
public TextFrame()
{
setTitle("TextFrame");
setSize(WIDTH,HEIGHT);


panel = new JPanel();

panel.setLayout(new GridLayout(5,2));
panel.add(new JLabel("Input:"));
textfield1 = new JTextField(10); //增加一个Input文本域
panel.add(textfield1);
textfield1.addActionListener(listener1);

panel.add(new JLabel("output:"));
textfield2 = new JTextField(10); //增加一个Onput文本域
textfield2.setEditable(false);  
panel.add(textfield2);

  group = new ButtonGroup();

addRadioButton("A",false);
addRadioButton("B",false);
addRadioButton("C",false); //增加四个单选按钮
addRadioButton("D",false);

choice = new Choice(); //增加一个choice组件
panel.add(choice);

add(panel,BorderLayout.NORTH);

}

public void addRadioButton(String name,boolean selected)
{
JRadioButton button = new JRadioButton(name,selected);
group.add(button);
panel.add(button);
  button.addActionListener(listener2);
}


ActionListener listener1 = new ActionListener()
  {
public void actionPerformed(ActionEvent evt)
{

String s = textfield1.getText();
pass(s);
String text = textfield2.getText() + " " + textfield1.getText();
 
textfield2.setText(text);
 
if(evt.getSource() == textfield1)
{
textfield1.setText("");

}

}
 
  };
   
  ActionListener listener2 = new ActionListener()
  {
public void actionPerformed(ActionEvent evt)
{
String s1 = evt.getActionCommand();
String s2 = s1.toLowerCase();
find(s2);

}
 
  };
   
  int i = 0;
  public void pass(String s)
  {
   
  str[i] = s;
  i++;
  }

  public void find(String s)
  {
  for(int i = 0; i < str.length; i++)
  {
  if(str[i].startsWith(s))
  choice.add(str[i]);
  }
  }
   
   
   
public static final int WIDTH = 400;
public static final int HEIGHT = 300;
private JTextField textfield1;
private JTextField textfield2;
private JPanel panel;
private ButtonGroup group;
private Choice choice;
private String[] str;
}

编译没问题,但在Input文本域中输入单词按回车后就有异常了。想请教高手这是怎么回事?
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at TextFrame.pass(Text1.java:101)
at TextFrame$1.actionPerformed(Text1.java:69)
at javax.swing.JTextField.fireActionPerformed(Unknown Source)
at javax.swing.JTextField.postActionEvent(Unknown Source)
at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
  相关解决方案