2014-09-25 17 views
0

編譯和執行在此程序中成功。但是,當我鍵入一些字符的框架不顯示其中的字符。爲什麼?什麼是錯誤。?此程序的KeyAdapter部分出錯

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類。但無法找到解決方案。

回答

2
  1. KeyListener只響應關鍵事件,當它被註冊到組件是可聚焦和具有鍵盤焦點
  2. Frame不可作爲焦點,從關鍵事件的角度來看,這使得它不可能爲它,但默認情況下,收到關鍵事件通知...

除非你有迫切需要的話,我會建議不要使用Frame,而是,使用JFrame作爲你的窗口,因爲AWT是15歲以上過時一般的和不再使用。看看Creating a GUI With JFC/Swing更多細節

相反,先從JPanel,覆蓋它的paintComponent方法有執行你的風俗畫。請參閱Performing Custom Painting瞭解更多詳情。

使用key bindings API來針對面板註冊表鍵操作。這將允許您定義面板接收關鍵事件通知所需的焦點級別

+0

是的,我是怎麼忘記的。感謝一噸Madprogrammer。 – user3414734 2014-09-25 11:31:35