我尝试做一个小菜单,你可以用键盘更改选项,创建一个从键适配器扩展的内部类,然后将其添加到菜单类,但是我没有得到任何响应键盘,有人可以帮我解决这个问题吗?
public class MenuWindow extends JComponent
{
private Rectangle2D.Float returnButton;
private Rectangle2D.Float mainMenuButton;
private Rectangle2D.Float restartButton;
private Rectangle2D.Float highScoreButton;
private int selectedButton;
public MenuWindow ()
{
selectedButton=0;
mainMenuButton = new Rectangle2D.Float(25, 25, 200, 75);
restartButton = new Rectangle2D.Float(25, 125, 200, 75);
highScoreButton = new Rectangle2D.Float( 25, 225, 200, 75);
returnButton = new Rectangle2D.Float( 25, 325, 200, 75);
this.addKeyListener(new MenuKeyInput());
this.requestFocus();
}
public void paint (Graphics g)
{
Graphics2D g2 = (Graphics2D ) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
g2.setColor(Color.BLACK);
g2.fillRect(0, 0, 250, 425);
g2.setStroke(new BasicStroke(14));
g2.setColor(Color.BLUE);
g2.drawRect(0, 0, 250, 425);
//draw buttons
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.2f));
g2.setColor(Color.BLUE);
g2.fill(mainMenuButton);
g2.fill(restartButton);
g2.fill(highScoreButton);
g2.fill(returnButton);
// paint selected button
paintSelectedButton(mainMenuButton, restartButton, highScoreButton, returnButton, g2);
}
public void paintSelectedButton(Rectangle2D.Float a,Rectangle2D.Float b,Rectangle2D.Float c,Rectangle2D.Float d, Graphics2D g)
{
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.45f));
g.setColor(Color.YELLOW);
switch (selectedButton)
{
case 0:
g.fill(a);
break;
case 1:
g.fill(b);
break;
case 2:
g.fill(c);
break;
case 3:
g.fill(d);
break;
}
}
//inner class
public class MenuKeyInput extends KeyAdapter
{
public void keyPressed (KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE)System.exit(0);
if (keyCode == KeyEvent.VK_UP)
{
selectedButton--;
if (selectedButton == -1)
{
selectedButton=3;
}
repaint();
}
else if (keyCode == KeyEvent.VK_DOWN)
{
selectedButton++;
if (selectedButton ==4)
{
selectedButton=0;
}
repaint();
}
}
}
}
这是我正在使用的主要课程:
public static void main (String arg[])
{
JFrame frame = new JFrame ();
MenuWindow window = new MenuWindow();
frame.add(window);
frame.setSize(new Dimension(250, 425));
frame.setResizable(false);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}