Java - 将JFrame设置为全屏时,屏幕变黑

时间:2012-03-10 19:16:13

标签: java swing jframe awt fullscreen

我正在尝试在Canvas上绘制内容,将其添加到JFrame,然后将此JFrame设置为Fullscreen。我的问题是:在全屏模式下我只看到黑屏。 在屏幕变黑之前,我很快就会看到画布的粉红色背景。

直接在JFrame上绘图,然后将其设置为全屏工作完全正常,我可以看到testtext。我认为正确显示Canvas存在问题。

这是我的代码:

public class FullscreenTest extends Canvas {

    private JFrame mainFrame;

    public FullscreenTest(){
        this.mainFrame = new JFrame();
        JPanel contentPane = (JPanel) mainFrame.getContentPane();
        contentPane.add(this);
    }

    public void run(DisplayMode dm){
        setBackground(Color.PINK);
        setForeground(Color.WHITE);
        setFont(new Font("Arial", Font.PLAIN, 24));

        Screen s = new Screen();

        s.setFullScreen(dm, this.mainFrame);

        try {
            Thread.sleep(5000);
        } catch (InterruptedException exc) { exc.printStackTrace(); }

        s.closeFullScreenWindow();
    }

    public void paint(Graphics g){      
        g.drawString("This is some testtext", 200, 200);
    }

    public static void main(String[] args){
        DisplayMode dm = new DisplayMode(800, 600, 32, DisplayMode.REFRESH_RATE_UNKNOWN);
        FullscreenTest test = new FullscreenTest();
        test.run(dm);
    }
}

以下是Screen.setFullScreen(DisplayMode dm,JFrame窗口)方法的作用:

//graphicsDevice = GraphicsEnvironment.getLocalGraphicsEnvironment()
//                 .getDefaultScreenDevice();
public void setFullScreen(DisplayMode dm, JFrame window){
    window.setUndecorated(true);
    window.setResizable(false);
    graphicsDevice.setFullScreenWindow(window);

    if(dm != null && graphicsDevice.isDisplayChangeSupported()){
        graphicsDevice.setDisplayMode(dm);          
    }
}

有没有人知道为什么我没有在全屏中看到JFrame的内容?

3 个答案:

答案 0 :(得分:3)

1)你有三个一般性问题

  • 使用Thread.sleep(5000);使用Swing Timer代替,演示here

  • 永远不会阻止EDT
  • (如果没有非常重要的原因)请勿混合AWT with Swing其余为here,并使用JPanel代替Canvas(对于Canvas paintJPanel方法,paintComponentpublic void paint(Graphics g){

  • 您的JFrameCanvas而不是Thread.sleep(5000);并被invokeLater()锁定

2)Swing GUI关联应该包含在public static void main(String[] args){ 含义

{{1}}

Initial Thread

中的更多内容

3)in linked code example你可以找到如何在Swing中使用后台线程的演示

答案 1 :(得分:0)

我同意mKorbel(实际上,我的代码正在处理他建议的更正)。只需一个提示就可以进一步获得更可预测的结果:在paint()方法中控制颜色。背景的默认颜色可能因系统而异。在我的系统上,它在浅红色背景上绘制白色文本。但如果它在黑色背景上绘制黑色文本,测试将看起来像“不工作”。

答案 2 :(得分:0)

嘿,我有同样的问题,每次运行程序时屏幕都会变黑。 在paint方法的一部分中,你写道,我认为它来自Bucky教程,顺便说一句:

public void paint(Graphics g){      
        g.drawString("This is some testtext", 200, 200);
    }

您所要做的就是使用“超级”

public void paint(Graphics g){
        super.paint(g);
        g.drawString("This is some testtext", 200, 200);
    }

我自己尝试了,它工作得很好。