为什么背景不显示?

时间:2016-09-25 13:59:32

标签: java jframe

我尝试了这段代码,所有显示的都是文字。主要脚本是:

import java.awt.Color;
import java.awt.DisplayMode;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JFrame;

public class Main extends JFrame{
    public static void main(String[] args) {
        DisplayMode dm = new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
        Main m = new Main();
        m.run(dm);

    }
    public void run(DisplayMode dm){
        setBackground(Color.PINK);
        setForeground(Color.WHITE);
        setFont(new Font("Arial",Font.PLAIN,24));
        Screen s = new Screen();
        try {
            s.setFullScreen(dm, this);
        try{
            Thread.sleep(5000);
        }catch(Exception ex){}
    }finally{
        s.RestoreScreen();
    }
    }
    public void paint(Graphics g){
        g.drawString("hello", 200, 200);
    }
}

另一个屏幕类是:

import java.awt.DisplayMode;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Window;

import javax.swing.JFrame;

public class Screen {
    private GraphicsDevice gc;
    public Screen(){
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = env.getDefaultScreenDevice();
    }
    public void setFullScreen(DisplayMode dm, JFrame window){
        window.setUndecorated(true);
        window.setResizable(false);
        gc.setFullScreenWindow(window);
        if (dm != null && gc.isDisplayChangeSupported()){
            try{
                gc.setDisplayMode(dm);
            }catch(Exception ex){}
        }
    }
    public Window getFullScreenWindow(){
        return gc.getFullScreenWindow();
    }
    public void RestoreScreen(){
        Window w = gc.getFullScreenWindow();
        if(w != null){
            w.dispose();
        }
        gc.setFullScreenWindow(null);
    }
}

我的代码是我所看到的教程的逐字逐句:

https://thenewboston.com/videos.php?cat=30&video=17934

和他的工作。此外,当我将其切换为16位图形时,paint方法甚至不起作用。请帮助!

2 个答案:

答案 0 :(得分:0)

在您的班级Main中,在public void run中输入:

Screen s = new Screen();
        try {
            s.setFullScreen(dm, this);
            try{
                Thread.sleep(5000);
            }catch(Exception ex){}
        }finally{
            s.RestoreScreen();
        }

答案 1 :(得分:0)

您忘了将JFrame设置为可见

在全屏方法中添加此

  

window.setVisible(真);