简体   繁体   English

Java如何设置JFrame后台

[英]Java how to set JFrame background

I simplified my original code to this problematic part.我将我的原始代码简化为这个有问题的部分。 I know it seems quite simple, that's why it confused me when it doesn't work as I intended.我知道这看起来很简单,这就是为什么当它没有按我的预期工作时它让我感到困惑。 It has no compilation or runtime errors yet I have failed to set the background color anything other than default.它没有编译或运行时错误,但我未能将背景颜色设置为默认值。 I've tried to create a new Color instance and invert the setVisible and setBackground methods, which wouldn't make a difference and my Google search wouldn't show anything different than I have done.我试图创建一个新的 Color 实例并反转 setVisible 和 setBackground 方法,这不会产生任何影响,而且我的 Google 搜索不会显示与我所做的任何不同的事情。

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

public class Main extends MyFrame{
    public static void main(String[]args){
        //new MyFrame();
        JFrame frame=new JFrame("Title");
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.red);
        frame.setVisible(true);
    }
}

Code:代码:

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

public class Main extends MyFrame {
    
    public static void main(String[]args){
        JFrame frame = new JFrame("Title");
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.RED); // <-----
        frame.setVisible(true);
    }
}

Result:结果:

在此处输入图像描述

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

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