简体   繁体   English

奇怪的setBackground()错误 - Java Swing

[英]Strange setBackground() error - Java Swing

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

public class JFrameGUI extends JFrame 
{
    JLabel item1;
    public JFrameGUI(int l, int b , String Title)
    {
        setTitle(Title);
        setLayout(new FlowLayout());
        setSize(l, b);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        item1 = new JLabel("This is a Sentence.");
        item1.setToolTipText("This is gonna show up on hover.");
        add(item1);
    }

    public static void main(String[] args)
    {
        JFrameGUI g = new JFrameGUI(1280,720,"The End Of The Line");
        JPanel p = new JPanel();
        p.setBackground(Color.BLUE);
        g.add(p);
    }
}

When I execute this , all i get is a tiny Blue square nest to the "This is a sentence" string . 当我执行此操作时,我得到的是一个小的蓝色方形嵌套到“这是一个句子”字符串。 I've tried everything ! 我已经尝试了一切!

You need to set the layout of the frame to a layout that doesn't respect the preferred sizes of its children. 您需要将框架的布局设置为doesn't其子项的首选大小的布局。 FlowLayout does, and your JPanel has no preferred size without any components added to it, or specifying a preferred size. FlowLayout可以,并且您的JPanel没有首选大小而没有添加任何组件,或指定首选大小。

A simple fix, set the layout of the frame to BorderLayout , or not set a layout at all, since JFrame already has a default BorderLayout . 一个简单的修复,将框架的布局设置为BorderLayout ,或者根本不设置布局,因为JFrame已经有一个默认的BorderLayout Note though that you probably want to add the JLabel to the JPanel and not the JFrame . 请注意,您可能希望将JLabel添加到JPanel而不是JFrame Unless you do want to add it the JFrame and not the background JPanel , you need to specify a BorderLayout position for the one you don't want in the center. 除非想将其添加到JFrame ,而不是背景JPanel ,你需要指定一个BorderLayout你不想在中心的一个位置。

You can see this answer to see which layout managers respect preferred sizes and which don't 您可以看到此答案,以查看哪些布局管理器尊重首选大小,哪些不符合

See more at Layout out Components Withing a Container 有关容器的布局输出组件,请参阅更多信息

Also, setVisible(true) shoul be the last thing you do after adding all components. 此外, setVisible(true)应该是添加所有组件 最后做的事情。

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

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