-1

I am drawing on an image on JPanel's graphic context. However the image does not remove itself from the graphics context when I press S. I know for sure my keyListeners are working.

If I am disposing the graphics context, shouldn't the content on the graphics context go away?

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();
        }

    }
Nicholas
  • 679
  • 2
  • 11
  • 29

1 Answers1

2

Calling Graphics#dispose will not remove the image from the JPanel

if (removeImage) {
   g.dispose();
}

instead use a boolean flag to indicate whether or not the image should be painted

if (showImage) {
   g.drawImage(image, 0, 0, this);
}

update the flag to false and invoke repaint to effectively "clear" any previous images.

showImage = false;
repaint();

Notes:

  • It is unnecessary to invoke dispose for Graphics objects in paintComponents. This only applys to custom Graphics references.
  • Don't load images from paintComponent - this degrades performance. Load the image from a method at startup
  • When developing Swing applications use Key Bindings rather than KeyListeners. The latter use KeyEvents which require focus to work. Key Bindings use KeyStrokes which work regardless of focus.
Reimeus
  • 158,255
  • 15
  • 216
  • 276