JPanel inside another

青春壹個敷衍的年華 提交于 2019-12-04 00:57:24

问题


I have a problem with a JPanel inside another one. I don't know why, but the result is a simple square, but the dimensions aren't correct. Why is that?

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

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

public class jj extends JFrame {

    private JPanel painel3;
    private JPanel painel5;
    private Container container;

    public jj() {

        container = getContentPane();
        container.setLayout(null);

        painel5 = new JPanel();
        painel5.setBackground(Color.red);
        painel5.setBounds(120, 110, 100, 120);
        painel3 = new JPanel();
        painel3.setBackground(Color.white);
        painel3.add(painel5);
        painel3.setBounds(50, 50, 290, 220);

        container.add(painel3);

        // frame
        setSize(1000, 900);
        setLocation(200, 50);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
        new jj();
    }
}

回答1:


You need to set the layout for panel3 also to null otherwise the default FlowLayout is used:

panel3.setLayout(null);




回答2:


A couple of additional recommendation. Learn to use LayoutManagers. They might have a slight learning curve but it will definitely be worth it. Nice tutorial: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html

Also according to the Java Standards, class names should start with a capital letter. Doing this will help others read your code better.




回答3:


Even better though is to avoid use of null layouts and setBounds/setSize but rather let layout managers help you in laying out your GUI. You can read up on them here: Laying out components in a container




回答4:


Set the layout of painel3 to null before adding the painel5 panel.

painel3.setLayout(null); painel3.add(painel5);

I recommend to use LayoutManagers.



来源:https://stackoverflow.com/questions/4749725/jpanel-inside-another

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