JPanel fills all JFrame space

人盡茶涼 提交于 2019-12-02 03:46:27

问题


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?


回答1:


You have to use the appropriate Layout Manager. A JFrame by default has a BorderLayout.

Check out this tutorial for LayoutManagers:

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




回答2:


  1. You haven't set a LayoutManager on the frame. 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().
  2. You should use setPreferredSize(Dimension d), not setSize(int x, int y) - from what I recall the LayoutManagers prefer this.


来源:https://stackoverflow.com/questions/8914262/jpanel-fills-all-jframe-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!