未在Java中设置背景色
我正在尝试将屏幕的背景色设置为绿色 到目前为止,我的代码是:未在Java中设置背景色,java,swing,jframe,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_
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);
为什么在我运行程序时背景没有设置为绿色?您需要添加对
super.paint(g)的调用在paint()
方法中的code>
@Override
public void paint(Graphics g){
super.paint (g);
g.drawString("Check Screen", 200, 200);
}
这将确保组件正确地绘制自身,包括背景色,然后绘制文本。一般来说,整个方法非常糟糕。即使它与getContentPane().setBackground(Color.GREEN)
一起工作,它也可能无法工作,因为您正在调用线程.sleep(5000)
onEDT
(或者您很快或稍后会遇到问题)。为重复任务(刷新屏幕)使用适当的组件:
与其重写JFrame的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);
}
}
}
您是否尝试过this.getContentPane().setBackground(Color.GREEN)
?按照您的说法,您似乎想将屏幕设置为绿色,但在代码中将JFrame设置为绿色…?请参阅[已问相同问题的答案][1][1]:我尝试过this.getContentPane().setBackground(Color.GREEN)
但屏幕仍然是黑色的。如果注释掉paint()
的定义会发生什么?加入this.getContentPane().setBackground(Color.GREEN)
行,它会使您的框架变为绿色吗?