简体   繁体   English

如何在Java swing中用背景色填充整个面板?

[英]How to fill entire panel with background color in Java swing?

I have recently started learning Java, and am now trying to work with Swing, so I am still rather new to this. 我最近开始学习Java,现在尝试与Swing合作,所以我对此还很陌生。 I am trying to make a gridbaglayout with (in this example)1 row and 1 column, so I added a JPanel with some background color to the layout, however the background color seems to appear only for the length of the text, not for the entire panel. 我正在尝试使用(在此示例中)1行和1列制作gridbaglayout,因此我向布局中添加了具有某些背景颜色的JPanel,但是背景颜色似乎仅针对文本的长度而不是针对文本的长度出现。整个面板。 I would like for the background color to stay for the entire length of the row, 我希望背景色在整行中都保持不变,

also, i had to add a second column with a large weightx to make sure my panel didnt get automatically centred, is there a better way to implement that? 另外,我必须添加第二个具有较大weightx的列,以确保面板不会自动居中,是否有更好的方法来实现呢?

This is the code that I currently have, 这是我目前拥有的代码,

      public static void main(String args[]) {
            JFrame mainFrame = new JFrame();
            mainFrame.setSize(900, 600);
            mainFrame.setLayout(new GridBagLayout());

            JPanel roll = new JPanel();
            roll.setBackground(new Color(190, 177, 245));

            JLabel wageChangeTag = new JLabel("Change");

            GridBagConstraints gRoll = new GridBagConstraints();

            gRoll.gridx = 0;
            gRoll.gridy = 0;
            gRoll.weightx = 5;
            gRoll.anchor = GridBagConstraints.CENTER;
            roll.add(wageChangeTag, gRoll);

            ////////////// MAIN GRID//////////////////
            GridBagConstraints gc = new GridBagConstraints();
            gc.gridx = 0;
            gc.gridy = 0;
            gc.weightx = 5;
            gc.anchor = GridBagConstraints.FIRST_LINE_START;
            gc.weighty = 5;
            mainFrame.add(roll, gc);

            gc.gridx++;
            gc.weightx = 0.1;
            mainFrame.add(new JLabel(), gc);

            mainFrame.setVisible(true);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
}

What you see painted is actually all your JPanel, nothing to do with your label inside it. 您所看到的实际上是您所有的JPanel,与其中的标签无关。 You can see that for example by adding a border to it (right after you set the background : 您可以通过在其中添加边框(例如,在设置背景后立即看到它)来查看:

roll.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

Now to have it expand horizontally , try adding the below line in your JPanel GridBagConstraints : 现在要使其水平扩展,请尝试在JPanel GridBagConstraints中添加以下行:

gc.fill = GridBagConstraints.HORIZONTAL;

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

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