简体   繁体   English

JFrame背景颜色不起作用

[英]JFrame background color not working

My code 我的密码

public static void main(String[] args) throws InterruptedException {
    JFrame frame = new JFrame("Flappy bird");
    frame.setSize(1200, 800);
    FlappyBird game = new FlappyBird();
    frame.getContentPane().setBackground(Color.YELLOW);
    frame.add(game);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    frame.setResizable(false);
    while (true) {
            game.moveBall();
            game.gameOver();
            game.moveRect();
            game.repaint();
            Thread.sleep(14);
        }

}

Why isn't the frame.getContentPane().setBackground(Color.YELLOW); 为什么不是frame.getContentPane().setBackground(Color.YELLOW); working? 工作吗

I've tried to rearrange the order, like setting the color after making the frame visible. 我试图重新排列顺序,例如在使框架可见后设置颜色。

It works alright, but you cannot see the background color because your FlappyBird instance is drawn on top of it. 它可以正常工作,但是您看不到背景色,因为FlappyBird实例绘制在背景色之上。 You can easily verify this by replacing your game class with an empty canvas like so: 您可以通过用空白画布替换游戏类来轻松地验证这一点,如下所示:

public static void main(String[] args) throws InterruptedException {
    JFrame frame = new JFrame("Flappy bird");
    frame.setSize(1200, 800);
    //FlappyBird game = new FlappyBird();
    Canvas game = new Canvas();
    frame.getContentPane().setBackground(Color.YELLOW);
    frame.add(game);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    frame.setResizable(false);
    // while (true) {
    //         game.moveBall();
    //         game.gameOver();
    //         game.moveRect();
    //         game.repaint();
    //         Thread.sleep(14);
    // }
}

There are two things you can try: 您可以尝试两种方法:

  1. Setting the background color not of the frame's content pane but of game : 设置背景颜色不是game框架的内容面板,而是game
//frame.getContentPane().setBackground(Color.YELLOW);
game.setBackground(Color.YELLOW);
  1. Making sure that the frame's background color shows through the game instance by making the latter transparent: 通过使游戏实例透明来确保框架的背景色在游戏实例中显示:
game.setOpaque(false);

Removing the lines related to game, I was able to run this with the expected yellow result. 删除与游戏相关的行,我能够以预期的黄色结果运行该行。 The issue must be within the while loop 问题必须在while循环内

while (true) {
        game.moveBall();
        game.gameOver();
        game.moveRect();
        game.repaint();
        Thread.sleep(14);
    }

or 要么

frame.add(game);

Without the FlappyBird class it's impossible to say exactly what is causing the issue, but based on the method names I'd look at repaint(). 没有FlappyBird类,就不可能确切地说出是什么原因引起的,但是基于方法名称,我会看一下repaint()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM