我正在 JPanel 的图形上下文中绘制图像。但是,当我按 S 时,图像不会从图形上下文中删除。我确定我的 keyListener 正在工作。
如果我正在处理图形上下文,图形上下文中的内容不应该消失吗?
public class MainMenu extends JPanel implements KeyListener {
private JFrame frame;
private int width = 660;
private int height = 500;
private Image image;
private boolean removeImage = false;
public MainMenu()
{
frame = new JFrame();
frame.setResizable(false);
frame.setTitle("Menu Test");
setBackground(Color.BLACK);
frame.setSize(width,height);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add main menu to the frame
frame.add(this);
// let the frame know about keyevents from this class
frame.addKeyListener(this);
}
public void setup()
{
frame.setVisible(true);
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode() == KeyEvent.VK_S)
{
removeImage = true;
}
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
try {
image = ImageIO.read(new File("Game/menuScreen.PNG"));
g.drawImage(image, 0, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(removeImage)
{
g.dispose();
}
}