该程序编译执行成功。但是当我输入一些字符时,框架不会显示其中的这些字符。为什么 ?错误是什么?
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 类中。但无法找到解决方案。
最佳答案
KeyListener
仅当其注册的组件可聚焦且具有键盘焦点时才响应按键事件Frame
不可聚焦,从关键事件的角度来看,这使得它无法(但默认)接收关键事件通知...
除非您迫切需要这样做,否则我建议不要使用 Frame
,而是使用 JFrame
作为您的窗口,因为 AWT 已经有 15 年以上的历史了已过时,一般不再使用。看看Creating a GUI With JFC/Swing了解更多详情
相反,从 JPanel
开始,重写它的 paintComponent
方法,以便在那里执行自定义绘制。看看Performing Custom Painting了解更多详情。
使用key bindings API登记针对专家组的关键行动。这将允许您定义面板接收关键事件通知所需的焦点级别
关于java - 该程序的 KeyAdapter 部分出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26036738/