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

Adi*_*dil 0 java user-interface swing 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

mKo*_*bel 6

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

2)对于Swing paintComponent()而不是paint()

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