repaint()方法不会重绘我的屏幕

时间:2011-11-14 17:11:58

标签: java swing user-interface paint

我在这里尝试做的是从repaint()方法中调用loadbg()方法。但是,repaint()无效,我的图片(存储在var bg中)不会加载到屏幕上。关于为什么这不起作用的任何建议?

package core;

/*** @author Adil

 * 2DPlatformer
 * Written by Adil
 * Built upon the player-core framework (written by Adil)
 * GNU Licensed

 */
import java.awt.*;

import javax.swing.JFrame;

import javax.swing.ImageIcon;

@SuppressWarnings("serial") //Suppress serial warning ID
public class Core extends JFrame {

    public static void main(String[] args) {
        DisplayMode dm = new DisplayMode(800, 600, 16, 
                DisplayMode.REFRESH_RATE_UNKNOWN); 
        //new display with parameters 800x600 + 16 bit color depth
        Core i = new Core(); //new core class var 
        i.run(dm);
    }
//variables for image loading below
    public Screen s;
    public Image bg;
    public boolean loaded = false;

//run method below
    public void run(DisplayMode dm) {
        setBackground(Color.BLACK);
        setForeground(Color.WHITE);
        setFont(new Font("Ubuntu", Font.PLAIN, 24));
        s = new Screen();
        loaded = false;
        try {
            s.setScreenSize(dm, this);
            loadbg();
            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
            }
        } finally {
            s.RestoreScreen();
        }
    }

    public void loadbg() {
        bg = new ImageIcon(
                "file:\\\\home\\adil\\Desktop\\pack_2\\bgame.jpg").getImage();
        loaded = true;
        s.repaint();//s is my screen object, but it won't repaint.
    }

    public void paint(Graphics g) {
        if (g instanceof Graphics2D) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                    RenderingHints.VALUE_ANTIALIAS_ON);
        }
        if (loaded) {
            g.drawImage(bg, 0, 0, null);
        }
    }
}

1 个答案:

答案 0 :(得分:6)

1)更好的方法是将Icon/ImageIcon放到JLabel,而不是使用Image

绘制paint()

2)对于Swing,paintComponent()代替paint()

3)不要使用Thread.sleep(int)代替Swing GUI使用javax.swing.Timer,因为在Thread.sleep(int)期间,GUI只是冻结,没有别的