设计题目三
本程序是将显示与用户按钮相对应的字符JTextField对象用于显示字符。当按下某个字母数字键时,将生成一个键盘事件,该键盘事件由KeyTyped方法处理,在显示用户按键之前,将JtypeField对象中删除先前的字符----程序一次只显示一个字符,该字符对所按键相对应,在主页程序中,字符的字体设置为Chinese_GB2312,字符的颜色随机变化,由于KeyListener接口共包含3个方法,而在在个程序中仅需要实现其中的一个方法,因此将使用匿名机制注册一个监听器对象。
注:在键盘发生时,所要执行的操作方法是下面的三个方法指定的。KeyListener接口包括三个:KeyPressed、KeyReleased、KeyTyped。
当按下某个meta键(如Control、Shift、Alt)时,将执行KeyPressed;按下字母时执行KeyTyped;当释放所选时将执行KeyReleased。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OneChar extends JApplet{
JTextField OneLetter=new JTextField(1);
public void init(){
Container c=getContentPane();
OneLetter.addKeyListener(new KeyAdapter(){
public void KeyTyped(KeyEvent e){
float red,green,blue;
Color fg,bg;
OneLetter.setText("");
red=(float)Math.random();
green=(float)Math.random();
blue=(float)Math.random();
fg=new Color(red,green,blue);
bg=Color.white;
OneLetter.setForeground(fg);
OneLetter.setBackground(bg);
OneLetter.setCaretColor(bg);
OneLetter.setFont(new Font("Courior",Font.BOLD,200));
}
});
c.setLayout(new GridLayout(1,1));
c.setBackground(Color.white);
c.add(OneLetter);
JOptionPane.showMessageDialog(null,"Clink on the applet;then type a key","Information",JOptionPane.PLAIN_MESSAGE);
}
}
HTML描述如下:
<HTML>
<!DOCTYPE.HTML PUBLIC"_//W3C//DTD HTML 4.01 Transitional //EN">
<HTML>
<HEAD>
<TITLE>ONECHAR APPLET</TILTE>
<HEAD>
<BODY>
<APPLET code="OneChar.class" width="350" height="300">
</APPLET>
</BODY>
</HTML>
使用Applet类,需要定义HTML语言