没有设置背景颜色的Java窗口? [英] Java window not setting background color?

查看:197
本文介绍了没有设置背景颜色的Java窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常愚蠢的错误,但iv'e刚开始学习的.awt包。我也跟着教程的信,在视频他的窗口的背景是红色的,也有我的code没有错误但它不会改变背景颜色。
感谢您的帮助!

 进口java.awt.Color中;
进口的javax.swing *。
公共类的测试{    公共静态无效的主要(字串[] args){
        // TODO自动生成方法存根
JFrame的F =新的JFrame();
f.setVisible(真);
f.setSize(350350);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle(窗口);
f.setBackground(Color.RED);
    }}


解决方案

1)的JFrame 不能做到这一点,你必须改变颜色内容窗格中如

  JFrame.getContentPane()的setBackground(myColor)

2)你需要用GUI相关code(在的方法),的invokeLater

例如:

 进口java.awt中的*。
java.awt.event中导入*。
进口的javax.swing *。公共类GUI {    公共GUI(){
        JFrame的帧=新的JFrame();
        frame.setTitle(测试背景);
        frame.setLocation(200,100);
        frame.setSize(600,400);
        frame.addWindowListener(新WindowAdapter的(){            @覆盖
            公共无效的windowClosing(WindowEvent五){
                System.exit(0);
            }
        });
        。frame.getContentPane()的setBackground(Color.BLUE);
        frame.setVisible(真);
    }    公共静态无效的主要(字串[] args){
        javax.swing.SwingUtilities.invokeLater(新的Runnable(){            公共无效的run(){
                桂=新的GUI();
            }
        });
    }
}

This is probably a really stupid error but iv'e just started learning the .awt package. I followed a tutorial to the letter, in the video his window's background is red, there are no errors in my code yet it won't change the background color. Thanks for any help!

import java.awt.Color;
import javax.swing.*;
public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(350,350);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Window");
f.setBackground(Color.RED);
    }

}

解决方案

1) JFrame can't do that, you have to change Color for content pane e.g.

JFrame.getContentPane().setBackground(myColor)

2) You need to wrap GUI related code (in main method) to the invokeLater

For example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GUI {

    public GUI() {
        JFrame frame = new JFrame();
        frame.setTitle("Test Background");
        frame.setLocation(200, 100);
        frame.setSize(600, 400);
        frame.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        frame.getContentPane().setBackground(Color.BLUE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                GUI gUI = new GUI();
            }
        });
    }
}

这篇关于没有设置背景颜色的Java窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆