KeyEvent不会改变JPanels的背景颜色

时间:2014-12-06 19:37:56

标签: java swing keylistener keyboard-events

我希望KeyEvent改变我的JP​​anels的背景颜色。当我按下键盘上的任何东西时没有任何反应。我的应用程序规范之一是我需要一个“从JPanel扩展的自定义组件”。这就是为什么我的图形面板有另一个类。

我的问题是当G被按下时没有任何反应,但我的中心面板应该变绿......

以下是我的部分申请的代码。

public class Maths extends JFrame implements KeyListener
{    
private JPanel pNorth = new JPanel();
private JPanel pSouth = new JPanel();
private JPanel pCenter = new JPanel();
private JPanel pEast = new JPanel();
private JPanel pWest = new JPanel();
private File file;
private JPanel pDraw = new GraphicsPanel();

public static void main(String args[]) 
{
    new Maths();

}

public Maths()
{
    mainFrame = new JFrame();

    mainFrame.setTitle("Maths Test Game");
    mainFrame.setLayout(new BorderLayout());
    mainFrame.setSize(1200, 800);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    mainFrame.add(pNorth, BorderLayout.NORTH);
    mainFrame.add(pSouth, BorderLayout.SOUTH);
    mainFrame.add(pCenter, BorderLayout.CENTER);
    mainFrame.add(pEast, BorderLayout.EAST);
    mainFrame.add(pWest, BorderLayout.WEST);

    pNorth.setLayout(new FlowLayout());
    pSouth.setLayout(new FlowLayout());
    pCenter.setLayout(new FlowLayout());
    pEast.setLayout(new FlowLayout());
    pWest.setLayout(new FlowLayout());

    addKeyListener(this);
    setFocusable(true);

    mainFrame.setVisible(true);
}

class GraphicsPanel extends JPanel 
{
    GraphicsPanel() 
    {
        // set a preferred size for the custom panel.
        setPreferredSize(new Dimension(250, 300));
    }
    @Override
    public void paint(Graphics g) 
    {
        super.paint(g);
        // set blue color for drawing
        g.setColor(Color.blue);
        // face
        g.drawOval(90, 70, 80, 80);
        // eyes
        g.drawOval(110, 95, 5, 5);
        g.drawOval(145, 95, 5, 5);
        // nose
        g.drawLine(130, 95, 130, 115);
        // mouth
        g.drawArc(113, 115, 35, 20, 0, -180);

    }
}

@Override
public void keyPressed(KeyEvent e) 
{
    if(e.getKeyCode() == KeyEvent.VK_G)
    {
        pCenter.setBackground(Color.green);
    }
    repaint();
}

@Override
public void keyReleased(KeyEvent e) 
{

}

@Override
public void keyTyped(KeyEvent e) 
{

}

}

1 个答案:

答案 0 :(得分:0)

有很多原因可能无法正常工作,一般来说,您不希望将KeyListener附加到JFrame等顶级容器,因为它们只是很多东西都可以阻碍框架引发关键事件。

相反,请使用键绑定API。有关详细信息,请参阅How to Use Key Bindings