日期:2014-05-20  浏览次数:20720 次

请教一个监听键盘事件的问题
我是新手,请教一个问题
下面这个问题是要从三个文本框输入三个数再比较大小,我想用三个变量记录三个文本框监听到的数据,请问怎样分别监听三个文本框的键盘事件啊?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.math.*;
class JieMian extends KeyAdapter implements ActionListener
{
public static final int WIDTH=500;
  public static final int HEIGHT=300;
  JFrame mainFrame;
  String string_1="";
  String string_2="";
  String string_3="";
  DataText datatext;
  Compel compel;
  Res result;
  String s1="";
  String s2="";
  String s3="";
  JButton button=new JButton();
  public JieMian()
  {
  mainFrame=new JFrame();
  mainFrame.setTitle("数据比较器");
mainFrame.setSize(WIDTH,HEIGHT);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.show();
Container op=mainFrame.getContentPane();
op.setLayout(null);
datatext=new DataText();
compel=new Compel();
result=new Res();
op.add(datatext);
datatext.setBounds(0,0,350,30);
op.add(compel);
compel.setBounds(350,0,150,30);
op.add(result);
result.setBounds(0,30,400,30);
mainFrame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
  System.exit(0);
  }
  }
  );  
  }

class DataText extends JPanel
{
private JTextField t1,t2,t3;
private JLabel l1;
public DataText()
{
l1=new JLabel("请输入三个正整数:");
add(l1);
l1.setBounds(0,0,120,30);
t1=new JTextField();
add(t1);
t2=new JTextField();
add(t2);
t3=new JTextField();
add(t3);
t1.setHorizontalAlignment(t1.LEFT);
  t1.setBackground(Color.WHITE);
  t1.setForeground(Color.BLACK);
  t2.setHorizontalAlignment(t1.LEFT);
  t2.setBackground(Color.WHITE);
  t2.setForeground(Color.BLACK);
  t3.setHorizontalAlignment(t1.LEFT);
  t3.setBackground(Color.WHITE);
  t3.setForeground(Color.BLACK);
  t1.setBounds(125,0,70,30);
  t2.setBounds(200,0,70,30);
  t3.setBounds(275,0,70,30);
  setLayout(null);
}
}
class Compel extends JPanel
{
private JButton button;
public Compel()
{
button=new JButton("比较");
add(button);
button.setBounds(0,0,70,30);
}
}
class Res extends JPanel
{
private JLabel l2;
private JTextField t4;
public Res()
{
l2=new JLabel("最大数为:");
add(l2);
l2.setBounds(0,0,120,30);
t4=new JTextField();
add(t4);
t4.setHorizontalAlignment(t4.LEFT);
  t4.setBackground(Color.WHITE);
  t4.setForeground(Color.BLACK);
  t4.setBounds(125,0,100,30);
  setLayout(null); 
}
}
}
public class MaxFind
{
  public static void main(String[] args)
{
JieMian testJM=new JieMian();
}
}

------解决方案--------------------
package maxvalue;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.JButton;