0
我希望KeyEvent更改我的JPanel的背景顏色。當我按下鍵盤上的任何東西時什麼都沒有發生我的一個應用規範是我需要一個'從JPanel擴展的定製組件'。這就是爲什麼我有我的圖形面板的另一個類。KeyEvent不會更改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](http://stackoverflow.com/help/mcve)來展示具體問題嗎? – Vulcan 2014-12-06 19:42:11
[如何使用密鑰綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – MadProgrammer 2014-12-06 19:44:29
哪些代碼是不必要的?我添加了圖形類,因爲我認爲這可能是問題。也許我需要那個班裏的我的準考人。 – Fin 2014-12-06 19:44:34