【问题标题】:KeyEvent won't change background color of JPanelsKeyEvent 不会改变 JPanels 的背景颜色
【发布时间】:2014-12-06 19:37:55
【问题描述】:

我希望 KeyEvent 更改我的 JPanel 的背景颜色。当我按键盘上的任何东西时,什么都没有发生。我的应用程序规范之一是我需要一个“从 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) 
{

}

}

【问题讨论】:

  • 我注意到您的问题中包含了一些不必要的代码。您能否创建一个MCVE 来展示具体问题?
  • 哪些代码是不必要的?我添加了图形类,因为我认为这可能是问题所在。那也许我需要那个班的关键听众。
  • 我的问题是按下 G 时没有任何反应,但我的中心面板应该变成绿色...

标签: java swing keylistener keyboard-events


【解决方案1】:

这可能不起作用的原因有很多,一般来说,您不想将KeyListeners 附加到像JFrame 这样的顶级容器,因为它们只是对许多可能会妨碍的事情并防止框架引发关键事件。

改为使用键绑定 API。详情请见How to Use Key Bindings

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 2014-04-21
    • 2021-01-23
    • 2011-06-15
    • 2022-06-11
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    相关资源
    最近更新 更多