想要写一个小程序,主要是想实现从文本域输入一个班学生某门课程的成绩,并将不及格人数的平均分输出.但是无法解决如何从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];
String str=new String();
JTextField []num1=new JTextField[2];
void addActionListener(ActionListener e){
}
public void init(){
try{
contentPane=f.getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
for(int i=0;i <2;i++){
la1[i]=new JLabel( "num "+i);
contentPane.add(la1[i]);
num1[i]=new JTextField(4);
contentPane.add(num1[i]);
str=str+num1[i].getText();
}
f.pack();
f.setVisible(true);
f.setSize(300,300);
}catch(Exception e){}
}
public void Paint(Graphics g){
g.drawString(str,50,50);
}
}
------解决方案--------------------
把actionListener事件加到jTextField不就可以触发了,或者如果想用键盘事件用addKeyListener,把actionPerform方法换成
public void keyReleased(KeyEvent e){
if(e.getKeyCode()==e.VK_ENTER){ 就是回车,楼主可以自己试试,一点建议很粗浅,希望有所帮助
------解决方案--------------------
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 implements KeyListener {
JFrame f=new JFrame( "成绩 ");
Container contentPane;
JLabel la1 =new JLabel();
String str=new String();
JLabel result =new JLabel( "成绩结果 ");
JTextField num1;
int unpass = 0;
int total = 0;
float avg ;
void addActionListener(ActionListener e){
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode()==e.VK_ENTER){
this.repaint();
int score =Integer.parseInt( " "+num1.getText());
if (score <60){
unpass++;
total += score;
}
if(unpass != 0){
avg = total/unpass;
result.setText( "目前 "+unpass+ "人不及格,他们平均分是: "+avg);
}
f.repaint();
contentPane.repaint();
}
}
public void init(){
try{
contentPane=f.getContentPane();
contentPane.setLayout(new FlowLayout());
num1=new JTextField(4);
contentPane.add(num1);
contentPane.add(result);
num1.addKeyListener(this);
f.pack();
f.validate();
f.setVisible(true);
f.setSize(600,300);
}catch(Exception e){}
}
public void Paint(Graphics g){
}
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
this.repaint();
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
this.repaint();
}
}
------解决方案--------------------