简体   繁体   English

JPanel会填充所有JFrame空间

[英]JPanel fills all JFrame space

I have write this code for displaying some set of colors from panel: 我已经编写了这段代码来显示面板上的一些颜色:

import java.util.ArrayList;
import java.util.List;

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

public class Palette {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Panel");

        palette.add(new Color(255, 0, 0));
        palette.add(new Color(0, 255, 0));
        palette.add(new Color(0, 0, 255));

        int width = 100;
        int height = 250;
        int x = 0;
        for (Color color : palette) {
            JPanel panel = new JPanel();

            panel.setSize(width, height);
            panel.setLocation(x, 750);
            panel.setBackground(new java.awt.Color(color.getColor()));

            frame.add(panel);

            x+=width;
        }
        frame.pack();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1000, 1000);
        frame.setVisible(true);
    }

}

Two first panels in the right place and with right dimensions. 正确位置和正确尺寸的两个第一面板。 But the last one fills all frame in blue color. 但是最后一个将所有帧填充为蓝色。 What's wrong? 怎么了?

You have to use the appropriate Layout Manager. 您必须使用适当的布局管理器。 A JFrame by default has a BorderLayout . 默认情况下,JFrame具有BorderLayout

Check out this tutorial for LayoutManagers: 查看本教程的LayoutManagers:

http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

  1. You haven't set a LayoutManager on the frame. 您尚未在框架上设置LayoutManager。 I'm not sure what the default LayoutManager is in Swing, but it's likely the LayoutManager is just stacking the components in Z order when you call pack(). 我不确定Swing中默认的LayoutManager是什么,但是当您调用pack()时,LayoutManager可能只是按照Z顺序堆叠组件。
  2. You should use setPreferredSize(Dimension d), not setSize(int x, int y) - from what I recall the LayoutManagers prefer this. 您应该使用setPreferredSize(Dimension d),而不要使用setSize(int x,int y)-从我回忆起LayoutManagers更喜欢此方法。

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

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