【问题标题】:JFrame background color not workingJFrame背景颜色不起作用
【发布时间】:2016-11-17 17:58:44
【问题描述】:

我的代码

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

}

为什么frame.getContentPane().setBackground(Color.YELLOW); 不起作用?

我尝试重新排列顺序,例如在使框架可见后设置颜色。

【问题讨论】:

  • 我投票决定将此问题作为题外话来结束,因为问题是为什么核心 java 的组件是以它原来的方式实现的,而不是其他方式。就是这样
  • @ControlAltDel 我不同意,原因是不同的。请在下面查看我的答案。
  • @Thomas 我已更正:)
  • @ControlAltDel 不用担心 ;-)

标签: java swing colors jframe


【解决方案1】:

它工作正常,但您看不到背景颜色,因为您的 FlappyBird 实例被绘制在它上面。您可以通过将游戏类替换为空画布来轻松验证这一点,如下所示:

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

您可以尝试两件事:

  1. 设置背景颜色不是框架的内容窗格而是game
//frame.getContentPane().setBackground(Color.YELLOW);
game.setBackground(Color.YELLOW);
  1. 通过使游戏实例透明来确保框架的背景颜色通过游戏实例显示:
game.setOpaque(false);

【讨论】:

    【解决方案2】:

    删除与游戏相关的行,我能够以预期的黄色结果运行它。问题必须在while循环内

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

    frame.add(game);
    

    如果没有 FlappyBird 类,就不可能确切地说出导致问题的原因,但根据方法名称,我会查看 repaint()。

    【讨论】:

      猜你喜欢
      • 2012-02-20
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 2012-09-30
      • 2014-04-21
      • 2016-06-11
      相关资源
      最近更新 更多