无法留下垂直间隙

时间:2011-05-04 12:01:14

标签: java swing user-interface

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.URI;

class MainPageTypo {
    JFrame fr;
    JButton easy, medium, tough;
    JLabel Contact;

    MainPageTypo() {
        buildGUI();
        hookUpEvents();
    }

    public void buildGUI() {
        fr = new JFrame("TypoMaster");
        JPanel mainP = new JPanel();
        mainP.setLayout(new FlowLayout());
        JPanel LevelPanel = new JPanel();
        LevelPanel.setLayout(new GridLayout(3, 0, 50, 50));
        easy = new JButton("Easy");
        medium = new JButton("Medium");
        tough = new JButton("Tough");
        Contact = new JLabel("Visit my Blog");
        fr.add(mainP);
        LevelPanel.add(easy);
        LevelPanel.add(medium);
        LevelPanel.add(tough);
        LevelPanel.setBackground(Color.magenta);
        LevelPanel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
        mainP.add(LevelPanel);
        mainP.setBackground(Color.lightGray);
        fr.setSize(500, 500);
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr.setVisible(true);
        // fr.setResizable(false);
    }

    public void hookUpEvents() {

    }

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

这是我的完整代码。我想从JPanel()顶部留下垂直空间。我使用LevelPanel.setBorder(BorderFactory.createEmptyBorder(50,50,50,50)); 但无法获得垂直间隙。我怎么能得到这个?

2 个答案:

答案 0 :(得分:4)

根据你所说的,我只是猜测你可能会通过在主面板上设置边框来获得你所获得的东西:

mainP.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));

请提供更多详情。因为你正在缩小差距。也许画出一幅快速而讨厌的画面。 :)

<强>建议 请遵循Java命名约定,即变量名称应以小写字母开头。

答案 1 :(得分:2)

基本上,你必须了解谜题的哪个部分负责什么

  • 在容器上设置边框(此处为levelPanel)空间要求添加到容器本身(如@Boro已经解释过):LayoutManager应用于该容器将布局子容器容器只在边框请求的insets内部。这就是你在levelPanel中看到的,第一个按钮上方的红色,最后一个按钮下方(以及所有按钮的两侧)

  • 在支持此功能的LayoutManager中设置x / y间隙属性,其效果完全取决于管理器本身的决定,无法读取具体管理器的api文档。

GridLayout的API文档:

 * In addition, the horizontal and vertical gaps are set to the 
 * specified values. Horizontal gaps are placed between each
 * of the columns. Vertical gaps are placed between each of
 * the rows. 

FlowLayout的API文档:

 * @param      hgap    the horizontal gap between components
 *                     and between the components and the 
 *                     borders of the <code>Container</code>
 * @param      vgap    the vertical gap between components
 *                     and between the components and the 
 *                     borders of the <code>Container</code>

从您的代码中,我猜您希望实现GridLayout与FlowLayout具有相同的差距行为: - )

由于levelPanel的父级(parent == mainP)的LayoutManager是FlowLayout,您可以 - 作为将边框设置为mainP的替代方法 - 设置FlowLayout的间隙:

 mainP.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 50));