该程序的编译和执行成功。但是当我键入一些字符时,框架中没有显示这些字符。为什么呢?有什么错误。?
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/