本人想写一个小程序,目的想在文本域上输入全班同学的成绩.并输出全班的平均成绩和不及格人数.由于人数之多,JLabel与JTextfield不能一个一个的定义,想到用数组和形式,可是在实验的时候却出现异常.请问是哪里出错了.还有如何获得在文本域输入的数据?
import java.applet.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Shiyan10A extends Applet{
JFrame f=new JFrame( "成绩 ");
Container contentPane;
JLabel []la1 =new JLabel[2];
JTextField []num1=new JTextField [2];
public void init(){
contentPane=f.getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
for(int i=0;i <2;i++){
la1[i]=new JLabel( "i ");
contentPane.add(la1[i]);
}
for(int i=0;i <2;i++)
contentPane.add(num1[i]);
f.pack();
f.setVisible(true);
f.setSize(300,300);
}
}
------解决方案--------------------
num1元素还没有new
------解决方案--------------------
contentPane.add(num1[i]);
num[i]从哪儿来的?哈,它的元素要new
------解决方案--------------------
看看这个,对你有点提示吧
import java.applet.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.util.*;
public class Test extends Applet{
JFrame f=new JFrame( "成绩 ");
Container contentPane;
JLabel []la1 =new JLabel[2];
JTextField []num1=new JTextField [2];
public void init(){
contentPane=f.getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
class getAction implements DocumentListener
{
public void insertUpdate(DocumentEvent event)
{
try {
System.out.println(event.getDocument().getText(0, event.getDocument().getLength()));
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void removeUpdate(DocumentEvent event){}
public void changedUpdate(DocumentEvent event){}
}
DocumentListener listener = new getAction();
for(int i=0;i <2;i++){
la1[i]=new JLabel( "i ");
contentPane.add(la1[i]);
num1[i]=new JTextField(4);
contentPane.add(num1[i]);
num1[i].getDocument().addDocumentListener(listener);
}
f.pack();
f.setVisible(true);
f.setSize(300,300);
}
}