背景颜色未在Java中设置

时间:2013-10-11 15:35:07

标签: java swing jframe

我正在尝试将屏幕背景颜色设置为绿色。

到目前为止我的代码:

package game;

import java.awt.*;
import javax.swing.JFrame;


public class Game extends JFrame {

    public static void main(String[] args) {
        DisplayMode dm = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
        Game g = new Game();
        g.run(dm);

    }

    public void run(DisplayMode dm) {
        setBackground(Color.GREEN);
        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 E) {
            }
        } finally {
            s.restoreScreen();
        }
    }

    @Override
    public void paint(Graphics g){
        g.drawString("Check Screen", 200, 200);
    }
}

当我运行程序时,我明白了:

printScreen

根据行显示屏幕应为绿色:

setBackground(Color.GREEN);

为什么运行程序时后台没有设置为绿色?

2 个答案:

答案 0 :(得分:1)

您需要在super.paint (g);方法中添加对paint ()的调用。

@Override
public void paint(Graphics g){
    super.paint (g);
    g.drawString("Check Screen", 200, 200);
}

这将确保组件正确绘制,包括背景颜色,然后绘制文本。

答案 1 :(得分:1)

一般来说,整体方法非常糟糕。即使它适用于getContentPane().setBackground(Color.GREEN),它也可能无法正常工作,因为您在Thread.sleep(5000)上呼叫EDT(或者您很快就会遇到问题)。使用适当的组件进行重复性任务(刷新屏幕):Swing Timer

不是覆盖JFrame's paint方法,而是使用JPanel并覆盖它的paintComponent方法要好得多。所以,像这样:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Game extends JFrame {

    JFrame frame = new JFrame();

    public Game() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new Panel());
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Game();
            }
        });
    }

    class Panel extends JPanel {
        Timer timer;

        Panel() {
            setBackground(Color.BLACK);
            setForeground(Color.WHITE);
            refreshScreen();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setFont(new Font("arial", Font.PLAIN, 24));
            g.drawString("Check Screen", 200, 200);
        }

        public void refreshScreen() {
            timer = new Timer(0, new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    repaint();
                }
            });
            timer.setRepeats(true);
            //Aprox. 60 FPS
            timer.setDelay(17);
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(650, 480);
        }
    }

}