【问题标题】:JFrame Background Colors Not ShowingJFrame背景颜色不显示
【发布时间】:2014-10-07 12:27:58
【问题描述】:

好的, 我对 awt api 不是很熟悉,所以这对我来说是相当新的东西。我有这些方法从我的主类运行来创建我的 jframe。在我的 createframe 方法下,背景颜色似乎没有应用于框架。有什么帮助吗?

这是我的框架类

import java.awt.Color;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class FrameClass {

        JFrame frame;

        public FrameClass(String framename) {
                frame = new JFrame(framename);
        }

        public void CreateFrame() {
            Color c = new Color(0,255,0);
            Container con = frame.getContentPane();
            con.setBackground(c);
            frame.getContentPane().setBackground(c);
                frame.setSize(400, 250); // Set the JFrame size when it is on the login screen
                frame.setLocationRelativeTo(null); // Center the JFrame

                /* Display the frame */
                frame.setVisible(true);
        }

        public void AddPanel() {
                JPanel ButtonsPanel = new JPanel();
                ButtonsPanel.setVisible(true);
                frame.add(ButtonsPanel);
        }
}

这是我的主要课程

public class Admin {

    public static FrameClass FrameObject = new FrameClass("ITWebKit Admin Panel");
    public static Database DatabaseObject = new Database();

    public static void main(String args[]) {
        FrameObject.CreateFrame();
        FrameObject.AddPanel();
    }
}

【问题讨论】:

    标签: java swing jframe jpanel layout-manager


    【解决方案1】:

    您的ButtonsPanel 覆盖了框架的内容窗格(您将其设置为背景)。您可以将ButtonsPanelopaque 属性设置为false,或者将背景设置为ButtonsPanel

    为什么会发生这种情况

    默认情况下,内容窗格有一个BorderLayoutBorderLayout 将拉伸 ButtonPanel 以适应它的大小。如果您要将内容窗格/框架的布局管理器更改为 FlowLayout(这不会拉伸面板),您将看到背景。

    其他说明:

    • FrameObject.CreateFrame(); FrameObject.AddPanel();。这将在添加组件之前设置框架可见。一般你要添加组件,然后设置框架可见。

    • 遵循 Java 命名约定。方法名和变量名以小写字母开头。

    • Swing 程序应在事件调度线程 (EDT) 上启动。见Initial Threads

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 2014-09-10
      • 2012-09-30
      • 2014-04-21
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      相关资源
      最近更新 更多