2014-01-13 41 views
0

我想制作一个随机显示屏幕顶部的JPanel的程序。这些JPanel包含一个笑脸的PNG BufferedImage(通过覆盖PaintComponent)。不幸的是,无论何时我运行程序并且面板都在任何重叠的位置绘制,图像将开始闪烁(看起来试图同时显示自己而不是合成)。我做了一些研究,并试图解决这个问题,但没有奏效。我的代码如下:JPanels在重叠期间闪烁

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

和我的其他类:

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

__Stop now and rethink__ - 您是否真的了解Swing的基本知识,并开始尝试使用Graphics。由于真正的基础建议 - __首先将所有组件添加到顶层容器,然后将其设置为可见_尽管在提供的代码中,我很失望地看到其他情况。此外,你说你重写了'paintComponent'方法,尽管我无法看到粘贴的代码中发生了这种情况。这个'Paint'方法是什么?谁在调用这个方法? 'paint()'方法中'super.paint(g)'是做什么的? 'EDT-Event Dispatcher Thread'在哪里? –

+0

'protected void Paint(Graphics g){'Use'@ Override' notation for an informative compiler error .. –

回答

3
  1. 绘画方法仅用于绘画。您不应该在绘画方法中设置组件的属性。

  2. 为什么你甚至在做自定义绘画?你可以使用带有图标的JLabel。