JPanels Flickering during overlap

179 Views Asked by At

I am trying to make a program that randomly displays JPanels at the top of the screen. These JPanels contain a PNG BufferedImage of a smiley face (by overriding PaintComponent). Unfortunately, whenever I run the program and the panels are drawn in locations with any overlap at all, the images will begin flickering (seemingly to try and display themselves at the same time instead of compositing). I did some research and tried to fix the problem but it did not work. my code is below:

public class MainScreen extends JFrame{

public MainScreen ms;
private Smiley smileyPanel;
private int randomPosition;
public AlphaComposite ac;
private Graphics2D graphicsPane;


//main method
public static void main (String[] args){
    MainScreen ms = new MainScreen();
}

//this is my attempted fix to the program
protected void Paint (Graphics g){
    Graphics2D graphicsPane = (Graphics2D) g;
    ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
    graphicsPane.setComposite(ac);

    super.paint(g);
    }

//this creates the main frame and also starts creating smileys at the top
public MainScreen(){
    super("Main Screen Window");
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    this.setSize(500,800);
    this.getContentPane().setBackground(Color.black);
    this.setLayout(null);

    createSmiley(); createSmiley(); createSmiley(); createSmiley(); createSmiley(); createSmiley();

    this.setVisible(true);
}
//random number generator used to place an image at the top

public void setRandomPosition(){
    Random generator = new Random();
    randomPosition = generator.nextInt(473);
}

//this is the method to create an image at a random location at the top
public void createSmiley(){
    smileyPanel = new Smiley();
    this.add(smileyPanel);
    setRandomPosition();
    smileyPanel.setBounds(randomPosition, 0, 28, 29);
}
}

and my other class:

public class Smiley extends JPanel{

private BufferedImage smileyFace;
private Dimension smileyPosition;
private File smileyFile;

public Smiley() {
    //this is the code to retrieve the smiley file
    try{
    smileyFile = new File("C:\\Users\\Devon\\Desktop\\smiley.png");
    smileyFace = ImageIO.read(smileyFile);
    } 
    catch (Exception e){
        System.out.println("There was an error finding or reading the file \" smiley.png.\"");
    }
}

//override of paintComponent method in order to display the grabbed image file onto a JPanel
@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(smileyFace, 0, 0, null);
    super.setBackground(null);
    super.setSize(28,29);
}
}
1

There are 1 best solutions below

0
On
  1. Painting methods are for painting only. You should NOT be setting the properties of the component in the painting method.

  2. Why are you even doing custom painting? You can just use a JLabel with an Icon.