import javax.swing.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;public class test extends Applet implements ActionListener, KeyListener {
    String text = "fds";
    JButton boldbutton,italicbutton,largebutton;
    boolean bold = false;
    boolean italic = false;
    boolean large = false;    public void init() {
        boldbutton = new JButton("Bold font");
        italicbutton = new JButton("Italic font");
        largebutton = new JButton("Large font");        boldbutton.addActionListener(this);
        italicbutton.addActionListener(this);
        largebutton.addActionListener(this);        add(boldbutton);
        add(italicbutton);
        add(largebutton);
        addKeyListener(this);
        requestFocus();
    }    public void actionPerformed(ActionEvent event) {
        if (event.getSource() == boldbutton) bold = !bold;
        if (event.getSource() == italicbutton) italic = !italic;
        if (event.getSource() == largebutton) large = !large;
        requestFocus();
        repaint();
    }    public void paint(Graphics g) {
        String fontname = "Courier";
        int type = Font.PLAIN;
        int size = 36;
        Font font;
        FontMetrics fm;        if (bold) type = Font.BOLD;
        if (italic) type = Font.ITALIC;
        if (large) size = 72;        font = new Font(fontname, type, size);
        g.setFont(font);        fm = getFontMetrics(font);
        int xloc = (getSize().width - fm.stringWidth(text)) / 2;
        int yloc = (getSize().height + fm.getHeight()) / 2;        g.drawString(text, xloc, yloc);
    }    public void keyTyped(KeyEvent e) {
        text = text + e.getKeyChar();
        repaint();
    }    public void keyPressed(KeyEvent e) {
    }    public void keyReleased(KeyEvent e) {
    }}

解决方案 »

  1.   


    初始化时已经在最后写了 requestFocus(); 为什么不聚焦窗口以便直接打字输入,反而聚焦在按钮上,奇怪!!!!!
      

  2.   

    init()时窗口还没有显示,此时设置焦点是无效的。
      

  3.   

    推荐你看一下这个:Setting focus to second component of modal dialoghttp://bbs.hit.edu.cn/cgi-bin/bbs2/bbscon?board=Java&file=M.1053580719.A&num=2049