此程序的KeyAdapter部分出错

时间:2014-09-25 10:51:46

标签: java swing jframe paint keylistener

此程序中的编译和执行成功。但是当我输入一些字符时,框架不会显示其中的那些字符。为什么?什么是错误。?

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

class frameadapter extends WindowAdapter
{
    newframe newthis;

    public frameadapter(newframe n)
    {
        newthis=n;
    }
    public void windowClosing(WindowEvent we)
    {
        newthis.setVisible(false);
        System.exit(0);
    }

}


class keyadapter extends KeyAdapter
{
    newframe keythis;
    public keyadapter(newframe n1)
    {
        keythis=n1;
    }

    public void KeyTyped(KeyEvent ke)
    {
        keythis.keymsg+=ke.getKeyChar();
        System.out.println(keythis.keymsg);
        keythis.repaint();
    }   
}




public class newframe extends Frame implements MouseListener
{
    int mouseX;
    int mouseY;
    String keymsg="This is a Test";
    String msg="";
    public newframe()
    {
        addKeyListener(new keyadapter(this));
        addWindowListener(new frameadapter(this));
        addMouseListener(this);
        this.setSize(600,600);
        this.setVisible(true);
    }

    public void paint(Graphics g)
    {
        g.drawString(keymsg,100,100);
        g.drawString(msg, 500, 200);
    }


    public void mouseClicked(MouseEvent e) {
        mouseX=this.getX();
        mouseY=this.getY();
        msg="MOUSE CLICKED AT";
        repaint();
    }


    public void mousePressed(MouseEvent e) {
        mouseX=this.getX();
        mouseY=this.getY();
        msg="MOUSE PRESSED AT";
        repaint();
    }

    public void mouseReleased(MouseEvent e) {
        mouseX=this.getX();
        mouseY=this.getY();
        msg="MOUSE RELEASED AT";
        this.setForeground(Color.WHITE);
        this.setBackground(Color.BLACK);
        repaint();
    }

    public void mouseEntered(MouseEvent e) {
        mouseX=this.getX();
        mouseY=this.getY();
        msg="MOUSE ENTERED AT";
        repaint();
    }


    public void mouseExited(MouseEvent e) {
        mouseX=this.getX();
        mouseY=this.getY();
        msg="MOUSE EXITED AT";
        repaint();
    }

    public static void main(String args[])    
    {
        newframe n=new newframe();
    }
}

错误我认为是在Keyadapter类中。但是无法找到解决方案。

1 个答案:

答案 0 :(得分:2)

  1. KeyListener仅在注册的组件可调焦且具有键盘焦点时才响应键事件
  2. Frame无法集中精力,从关键事件的角度来看,这使得它无法接收关键事件通知,但默认情况下......
  3. 除非你有迫切的需要这样做,否则我建议不要使用Frame,而是使用JFrame作为你的窗口,因为AWT已经过时15年了,而且通常不是使用时间更长请查看Creating a GUI With JFC/Swing了解更多详情

    相反,从JPanel开始,覆盖它的paintComponent方法,在那里执行自定义绘画。有关详细信息,请查看Performing Custom Painting

    对面板使用key bindings API注册表操作键操作。这将允许您定义面板接收关键事件通知所需的焦点级别