使用GridLayout时出现意外的布局问题

时间:2013-07-14 04:33:22

标签: java swing awt layout-manager grid-layout

我试图让JPanel填满它的给定空间,但它不会。 这段代码应该是解释性的......

    JPanel memWindow = new JPanel();
    memWindow.setLayout(new GridLayout(1, 4));
    memWindow.add(memField = new JTextField(10));
    memWindow.add(memView = new JButton("VM"));
    memWindow.add(memAdd = new JButton("M+"));
    memWindow.add(memSub = new JButton("M-"));

    JPanel memWindow2 = new JPanel();
    memWindow.setLayout(new GridLayout(1, 4));
    memWindow.add(mem2Field = new JTextField(10));
    memWindow.add(mem2View = new JButton("VM"));
    memWindow.add(mem2Add = new JButton("M+"));
    memWindow.add(mem2Sub = new JButton("M-"));

    JPanel memWindows = new JPanel();
    memWindows.setLayout(new GridLayout(2, 1));
    memWindows.add(memWindow, BorderLayout.SOUTH);
    memWindows.add(memWindow2, BorderLayout.NORTH);

    add(displayWindow, BorderLayout.NORTH);
    add(memWindows);
    add(inputWindow, BorderLayout.SOUTH);

这是我得到的GUI ......

enter image description here

1 个答案:

答案 0 :(得分:2)

您的代码有什么问题?

1.您能先解释下面的代码吗?

JPanel memWindow2 = new JPanel();
memWindow.setLayout(new GridLayout(1, 4));
memWindow.add(mem2Field = new JTextField(10));
memWindow.add(mem2View = new JButton("VM"));
memWindow.add(mem2Add = new JButton("M+"));
memWindow.add(mem2Sub = new JButton("M-"));

我认为应该是这样的:

JPanel memWindow2 = new JPanel();
memWindow2.setLayout(new GridLayout(1, 4));
memWindow2.add(mem2Field = new JTextField(10));
memWindow2.add(mem2View = new JButton("VM"));
memWindow2.add(mem2Add = new JButton("M+"));
memWindow2.add(mem2Sub = new JButton("M-"));

2.如果要使用BorderLayout.XXX指定组件的位置,则应使用BorderLayout,如下所示:

JPanel memWindows = new JPanel();
memWindows.setLayout(new BorderLayout());
memWindows.add(memWindow, BorderLayout.SOUTH);
memWindows.add(memWindow2, BorderLayout.NORTH);