-3

我正在尝试创建一个带有多个按钮的显示器。但是,只显示一个按钮。为什么会这样?与布局管理器有关吗?我哪里做错了?

我的代码:

import java.awt.*;
class ButtonDemo extends Frame 
{
    Button[] b;Frame frame;
    ButtonDemo()
    {
        int i=0;
        b=new Button[12];
        frame=new Frame();
        frame.setLayout(new BorderLayout());
        for (i=0;i<12;i++)
        {
            b[i] = new Button("Hello"+i);frame.add(b[i]);
        }
        frame.add(new Button("Hello"));
        frame.add(new Button("polo"));
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String args[])
    {
        ButtonDemo bd = new ButtonDemo();
    }
}
4

3 回答 3

3

这是预期的行为BorderLayout

BorderLayout将只允许单个组件驻留在其 5 个可用位置中的每一个中。

您将两个按钮添加到同一位置,因此只会显示最后一个。

尝试...

  • BorderLayout.NORTHBorderLayout.SOUTH位置添加一个按钮
  • 使用不同的布局管理器

查看A Visual Guide to Layout Managers and Layout Components within a Container了解更多详细信息...

于 2013-08-16T03:07:11.613 回答
1

就像MadProgrammer说的那样,这是因为BorderLayout 只需声明另一个布局,它应该可以工作:

import java.awt.*;
class ButtonDemo extends Frame 
{
    Button[] b;Frame frame;
    ButtonDemo()
    {
        int i=0;
        b=new Button[12];
        frame=new Frame();
        frame.setLayout(new BorderLayout());
        for (i=0;i<12;i++)
        {
            b[i] = new Button("Hello"+i);frame.add(b[i]);
        }
        frame.add(new Button("Hello"));
        frame.add(new Button("polo"));
        setLayout(new FlowLayout());
        frame.pack();
        frame.setVisible(true);

    }

    public static void main(String args[])
    {
        ButtonDemo bd = new ButtonDemo();
    }
}
于 2017-12-27T10:11:19.030 回答
0

首先,建议不要将组件添加到框架中,而是添加到它的Container中。最简单的方法是将 JPanel 添加到框架的 Container 中,然后将任何后续组件添加到此 JPanel。

例如

    JFrame customFrame = new JFrame();
    JPanel customPanel = new JPanel();
    customPanel.setLayout(new BorderLayout());
    customFrame.getContentPane().add(customPanel);
    //add your buttons to customPanel

其次,您创建了一个扩展 Frame 的自定义类 ButtonDemo,那么为什么还要在其中创建一个框架?在您的情况下,您可以直接说

setLayout(new BorderLayout()); // equivalent to this.setLayout(new BorderLayout());
 add(new Button("polo"));

而不是创建一个单独的框架并向其添加组件/布局。

您将框架的布局设置为 BorderLayout 但不使用它的任何功能。

frame.setLayout(new BorderLayout());

如果您希望按钮位于您想要的位置(例如 NORTH),您必须指定

frame.add(new Button("Hello"),BorderLayout.NORTH);

同样,如果您想在 NORTH 位置使用多个按钮,则使用带有BoxLayout的面板(水平或垂直,无论您的要求是什么),然后将您的按钮添加到其中。

于 2013-08-16T03:57:19.070 回答