-1

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

到目前为止我的代码:

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);
    }
}

当我运行程序时,我得到了这个:

打印屏幕

屏幕应该是绿色的线:

setBackground(Color.GREEN);

为什么我运行程序时背景没有设置为绿色?

4

2 回答 2

1

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

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

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

于 2013-10-11T15:56:25.223 回答
1

一般来说,整个方法非常糟糕。即使它与getContentPane().setBackground(Color.GREEN)它一起使用也可能无法正常工作,因为您正在调用Thread.sleep(5000)on 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);
        }
    }

}
于 2013-10-11T16:11:28.540 回答