2

我正在尝试将标签添加到面板的北部和南部,并将面板添加到框架的中心。如果我不自己指定标签的大小,程序是完美的,但是当我给它们特定的尺寸时:

label.setPreferredSize(di);
label2.setPreferredSize(di);

它变得一团糟!但是面板和框架的尺寸更大,有(100,100)什么想法吗?

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;


import javax.swing.JFrame;

public class BorderLayoutDemo2 {

    public static void main(String args[])
    {
        Frame frame = new Frame();
    }
}

class Frame extends JFrame
{

    private static final long serialVersionUID = 1L;

    public Frame(){
        setSize(500,500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Dimension di = new Dimension(50,50);
        Dimension dim = new Dimension(200,200);

        JPanel panel = new JPanel();
        panel.setPreferredSize(dim);

        JLabel label = new JLabel("Here is my label");
        JLabel label2 = new JLabel("Here is my label2");



        JMenuBar menu = new JMenuBar();
        JMenu setting = new JMenu("Setting");
        JMenuItem exit = new JMenuItem("Exit");
        JMenuItem add = new JMenuItem("Add");
        setting.add(add);
        setting.add(exit);
        menu.add(setting);

        label.setPreferredSize(di);
        label2.setPreferredSize(di);

        panel.add(label,BorderLayout.NORTH);
        panel.add(label2,BorderLayout.SOUTH);

        add(menu,BorderLayout.NORTH);
        add(panel,BorderLayout.CENTER);


        pack();
        setVisible(true);
    }

}
4

1 回答 1

4

您假设面板的布局是BorderLayout在您添加组件时,即:panel.add(label,BorderLayout.NORTH);. 但是您没有设置默认的布局和JPanel用途。你可以像这样修复它:FlowLayout

JPanel panel = new JPanel(new BorderLayout());
于 2012-09-26T04:50:42.797 回答