簡體   English   中英

Java-JPanel和KeyListener問題

[英]Java - JPanel and KeyListener Problem

我有一個帶有3個面板的JFrame。 我擴展了一個App類,然后向其中添加三個面板,如下所示:

JPanel controlButtonsPanel = new GameControlButtons();
        controlButtonsPanel.setPreferredSize(new Dimension(801,60));
        controlButtonsPanel.setBorder(new LineBorder(Color.white, 1));
        constraints.anchor = GridBagConstraints.NORTHWEST;
        constraints.weightx = 2;
        constraints.weighty = 0.3;
        this.add(controlButtonsPanel, constraints);

        JPanel tempP = new JPanel();     
/`/ *** I'm going to create a Jpanel subclass for this, too, I just haven't yet.`
        tempP.setPreferredSize(new Dimension(500,838));
        tempP.setBorder(new LineBorder(Color.white, 2));
        constraints.anchor = GridBagConstraints.NORTHEAST;
        constraints.weightx = 1;
        constraints.weighty = 2;
        this.add(tempP, constraints);

        JPanel graphicsPanel = new RoofRunnerGame("Ken");
        constraints.anchor = GridBagConstraints.SOUTHWEST;
        constraints.weightx = 2;
        constraints.weighty = 1;
        graphicsPanel.setBorder(new LineBorder(Color.white, 1));
        graphicsPanel.setPreferredSize(new Dimension(800,800));
        graphicsPanel.requestFocus();
        this.add(graphicsPanel, constraints);       

我已經為GameControlButtons和RoofRunnerGame類擴展了JPanel。 我在前者中添加了鼠標監聽器。 並且我為后者添加了一個鼠標偵聽器和一個鍵偵聽器。

**問題:鼠標偵聽器對於這兩種偵聽器都工作正常,但是關鍵偵聽器似乎在我的RoofRunnerGame面板中聽不到。**

我在網上找到了兩個可能的修復程序,但想先提出。

1)一個是在RoofRunnerGame子類中調用requestFocus()。 問題是,一旦我單擊其他面板,它就會失去焦點。 (這是短期修復。)

2)提到的另一件事是使用keyBindings。 我以前從未使用過它們。 如果您推薦的話,我會的,但是如果可能的話,我希望繼續使用keyListener。

所以你怎么看? 有什么辦法可以讓RoofRunnerGame面板始終讓KEY收聽?

您可以使其他面板無法聚焦,但是也可能需要使這些面板上的每個組件都無法聚焦。

這個 ,和這個有關通過ActionMap中添加鍵偵聽器的例子。 getInputMap()方法中的JComponent.WHEN_IN_FOCUSED_WINDOW標志應允許您的面板即使在未聚焦的情況下也可以接收輸入事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM