日期:2014-05-20  浏览次数:20585 次

GUI,为什么组件绘图绘制了两次
Java code

import java.awt.*;
import javax.swing.*;
public class MainApp {
    public static void main(String args[]){
        GameControl gameControl = new GameControl();
        Environment gameBackground = new Environment();
        JFrame frame = new JFrame();
        frame.add(gameBackground,BorderLayout.CENTER);
        frame.setResizable(false);
        frame.setVisible(true); 
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(475,494);
        frame.setTitle("是男人就下一百层");
    }
}
class Environment extends JPanel{
    private Image background = new ImageIcon("backgroud.gif").getImage();
    Environment(){  
        setLayout(null);
        add(GameControl.boardPanel);  //注释了这行再运行的效果是我想达到的效果。。。
        //想知道为什么会出现这个BUG,而不仅仅是怎么修复这个bug
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(background,0,0,getWidth(),getHeight(),this);
    }
}
class BoardPanel extends JPanel{
    BoardPanel(){
        setBounds(24,67,422,379);
    }
    public void paint(Graphics g){}
}
class GameControl implements Runnable{
    public static BoardPanel boardPanel = new BoardPanel(); 
    GameControl(){
        new Thread(this).start();
    }
    public void run(){
        while(true){
            try{
                Thread.sleep(30);
            }
            catch(InterruptedException e){
            }
            boardPanel.repaint();
        }
    }
}



------解决方案--------------------
把这里的代码也执行过了,表示没有发现 bug 现象
你这是 gif 图,该图是否有动画效果?
另外值得一说的是,你这样读取图片的方式,
打成 jar 包后,如果该图片也在 jar 包中,是无法正常运行的

------解决方案--------------------
在对你的 bug 进行像素对比后
可以确定,你的这个 bug 肯定是在 BoardPanel 中也把这个底图绘制了一遍