import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class String6 extends JFrame{ private JLabel promptLabel; private JTextField inputField; private JTextArea ouputArea; public String6() { super("Testring Class StirngTokenizer"); Container container = getContentPane(); container.setLayout(new FlowLayout()); promptLabel = new JLabel("Enter a sentence and press Enter"); container.add(promptLabel); inputField = new JTextField(20); inputField.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { StringTokenizer tokens = new StringTokenizer(event.getActionCommand()); outputArea.setText("Number of elements : " + tokens.countTokens() + "\nThe tokens are:\n" ); while(tokens.hasMoreTokens()) outputArea.append(tokens.nextToken() + "\n" ); } } ); container.add(inputField); outputArea = new JTextArea(10,20); outputArea.setEditable(false); container.add(new JScrollPane(outputArea)); setSize(275,240); setVisible(true); } public static void main(String args[]) { String6 application = new String6(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); } }
----------------解决方案--------------------------------------------------------
// 问题出在,你在用 outputArea 这个对象之前, 并没有建立这个对象!!!
// 修改如下:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class String6 extends JFrame
{
private JLabel promptLabel;
private JTextField inputField = new JTextField(20);
private JTextArea outputArea = new JTextArea(10,20);
public String6()
{
super("Testring Class StirngTokenizer");
Container container = getContentPane();
container.setLayout(new FlowLayout());
promptLabel = new JLabel("Enter a sentence and press Enter");
container.add(promptLabel);
inputField.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
StringTokenizer tokens =
new StringTokenizer(event.getActionCommand());
outputArea.setText("Number of elements : " +
tokens.countTokens() + "\nThe tokens are:\n" );
while(tokens.hasMoreTokens())
outputArea.append(tokens.nextToken() + "\n" );
}
});
container.add(inputField);
outputArea.setEditable(false);
container.add(new JScrollPane(outputArea));
setSize(275,240);
setVisible(true);
}
public static void main(String args[])
{
String6 application = new String6();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
}
}
----------------解决方案--------------------------------------------------------
其实没问题,只是你把
public class String6 extends JFrame{
private JLabel promptLabel;
private JTextField inputField;
private JTextArea ouputArea;
这里面的那个outputArea的t少写了,哈哈......
----------------解决方案--------------------------------------------------------
----------------解决方案--------------------------------------------------------