2013-10-14 117 views
0

正如標題所說,我正試圖向JPanel添加一個keylistener。到目前爲止,我得到它的唯一方法是添加一個空的文本框並單擊它。現在我不想在我的JPanel中有一個空的textfield,所以我想將keylistener添加到面板本身。JPanel中的KeyListener無法正常工作(面板集中)

這裏是一流的,我在談論:

package cookieClicker; 

import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Rectangle; 
import java.awt.event.KeyListener; 
import java.awt.event.MouseListener; 

import javax.swing.ImageIcon; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 

public class CookieView extends JPanel 
{ 
    private CookieModel cm; 
    private ImageIcon cookie; 
    public Rectangle rect; 

    public CookieView(CookieModel cm) 
    { 
     this.cm = cm; 
     this.setFocusable(true); 
     this.requestFocusInWindow(); 
    } 

    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     cookie = new ImageIcon("Untitled-1.png"); 
     g.setColor(Color.ORANGE); 
     g.drawImage(cookie.getImage(), this.getWidth()/2 - 100, this.getHeight()/2 - 100, 200, 200, this); 
     rect = new Rectangle(this.getWidth()/2 - 100, this.getHeight()/2 - 100, 200, 200); 
    } 

    public void addListener(MouseListener m, KeyListener k) 
    { 
     this.addMouseListener(m); 
     this.addKeyListener(k); 
    } 
} 

有誰知道如何使這項工作?

+0

http://stackoverflow.com/questions/11487369/jpanel-doesnt-respone-to-keylistener-event。檢查這LINL – Raghunandan

回答

4

面板集中

你怎麼知道的面板集中?

requestFocusInWindow()方法只有在該方法被調用時框架已經可見時才起作用。因此,在構造函數中調用該方法將不會執行任何操作。

基本代碼應該是:

CookieView panel = new CookieView(); 

JFrame frame = new JFrame(); 
frame.add(panel); 
frame.pack(); 
frame.setVisible(true); 
panel.requestFocusInWindow(); 

你也應該確保所有的代碼是在事件調度線程中執行。

但是,你應該甚至不應該使用KeyListener。在大多數情況下,Swing旨在與Key Bindings一起使用。閱讀教程,看看鍵綁定是否適合你。

最後,您不應該在paintComponent()方法中讀取圖像文件。每當Swing確定組件需要重新繪製時,都會調用繪畫方法,因此一遍又一遍地讀取圖像效率不高。

+0

感謝隊友,設法讓它現在工作。 – RemcoW