简体   繁体   English

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

[英]repaint() method won't repaint my screen

What I'm trying to do here is call the repaint() method from within my loadbg() method. 我在这里要做的是从我的loadbg()方法中调用repaint() loadbg()方法。 However, repaint() isn't working, and my image (stored in the var bg ) won't load onto the screen. 但是, repaint()无法正常工作,并且我的图像(存储在var bg )不会加载到屏幕上。 Any suggestions as to why this won't work? 有什么建议为什么不起作用?

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) better way would be put Icon/ImageIcon to JLabel , rather than paint Image by using paint() 1)更好的方法是将Icon / ImageIcon放置到JLabel ,而不是通过使用paint()绘制Image

2) for Swing is there paintComponent() instead of paint() 2)对于Swing,有paintComponent()而不是paint()

3) don't use Thread.sleep(int) for Swing GUI use javax.swing.Timer instead, because during Thread.sleep(int) you GUI simply freeze, nothing else 3)不要在Swing GUI中使用Thread.sleep(int) ,而应使用javax.swing.Timer ,因为在Thread.sleep(int)期间,您的GUI只会冻结,没有别的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM