【问题标题】:Error in KeyAdapter part of this program此程序的 KeyAdapter 部分出错
【发布时间】:2014-11-20 02:49:32
【问题描述】:

本程序编译执行成功。但是当我输入一些字符时,框架没有在其中显示这些字符。为什么 ?错误是什么?

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 类中。但无法找到解决方案。

【问题讨论】:

    标签: java swing jframe paint keylistener


    【解决方案1】:
    1. KeyListener 仅在其注册的组件可聚焦且具有键盘焦点时才响应按键事件
    2. Frame 不可聚焦,从关键事件的角度来看,这使得它无法接收关键事件通知,但默认情况下...

    除非您迫切需要这样做,否则我建议您不要使用Frame,而是使用JFrame 作为您的窗口,因为 AWT 已经过时 15 年以上并且通常不再使用。更多详情请关注Creating a GUI With JFC/Swing

    相反,从JPanel 开始,覆盖它的paintComponent 方法,在那里执行您的自定义绘画。更多详情请查看Performing Custom Painting

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

    【讨论】:

    • 是的,我怎么忘了。非常感谢 Madprogrammer。
    猜你喜欢
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 2022-07-25
    • 2020-03-01
    • 2011-12-02
    • 1970-01-01
    相关资源
    最近更新 更多