1

I'm making a pacman game using java swing. in my code i use 2 jpanels in the component panel the first is for the map and the second is for the pacman. now i am trying to move pacman to other cell when a button is clicked.it is moved but the old picture is not deleted.image before clicking, image after clicking as you can see the new pacman appears but the old didn't disappear. and some trash also appeared. this is the code of creating the jpanel for the pacman

JLabel pacman = new JLabel("", new ImageIcon("pacman.png"), JLabel.CENTER);
    player = new JPanel(new BorderLayout());
    player.setBounds(n*1, n*1, n, n);
    //pacman.setOpaque(true);
    pacman.setBackground(new Color(0, 0, 0, 0));
    player.add(pacman);
    //player.setOpaque(true);
    player.setBackground(new Color(0, 0, 0, 0));
    contentPane.setLayout(null);

    JPanel panel = new JPanel();
    panel.setBounds(0, 0, 1000, 1000);
    panel.setLayout(null);
    panel.add(player);  
    panel.setBackground(new Color(0, 0, 0,0));
    contentPane.add(panel);

the code inside the button actionPreformed method is :

            panel.remove(player);
            player.setLocation(new Point(n*1, n*2));
            panel.add(player);
            panel.revalidate();
            panel.repaint();

how can i make the old pacman disappears ?

A.khaled
  • 505
  • 1
  • 5
  • 13
  • 1
    Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Dec 09 '17 at 04:25

1 Answers1

1
player.setBackground(new Color(0, 0, 0, 0));

Don't use transparent colors. Swing does not handle transparency properly.

For full transparency there is a simple solution. Just make the component transparent:

player.setOpaque( false );

If you ever need partial transparency then check out Backgrounds With Transparency for a solution.

camickr
  • 321,443
  • 19
  • 166
  • 288