【问题标题】:Can only display one item at a time in GUI在 GUI 中一次只能显示一项
【发布时间】:2016-03-23 22:04:28
【问题描述】:

我正在尝试向我的 GUI 添加标签、按钮等,但程序只显示添加到窗口中的最后一项。我不明白他们为什么不一个接一个地去。几乎好像我把它们放在一起。附上我的代码。

import java.awt.*;
import java.awt.event.*;

public class ZooGUIStafford extends Frame {

    //Text fields for animal input
    TextField ani1, ani2, ani3, ani4, ani5;

    public ZooGUIStafford()
    {


        //Size of window
        this.setTitle("Zoo Database");
        this.setSize(400, 400);
        this.setVisible(true);

        //Welcome label
        Label welcome = new Label("Welcome to the Zoo Database!");
        this.add(welcome);

        Label an1 = new Label("Enter animal type 1: ");
        this.add(an1);



        addWindowListener(new MyWindowAdapter(this));

    }

    class MyWindowAdapter extends WindowAdapter{

        ZooGUIStafford myWindow = null;

        MyWindowAdapter(ZooGUIStafford myWindow)
        {
            this.myWindow = myWindow;
        }

        public void windowClosing(WindowEvent e)
        {
            myWindow.setVisible(false);
        }
    }



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

    }

}

【问题讨论】:

  • 您需要设置layout 以便组件跟随。 BoxLayout 或 FlowLayout 可能是您的最佳选择。
  • 如果您想手动定位项目(乏味但有时需要 IMO),您可以执行 setLayout(null);然后在你的构造函数中为你添加的每个组件设置边界。
  • 这就是我认为的问题所在。我正在阅读这本参考书,它表明流布局是默认设置。所以我假设如果你不使用布局,那么默认值会取而代之。谢谢!

标签: java user-interface


【解决方案1】:

请,

添加布局,

 this.setLayout(new FlowLayout());

输出:

【讨论】:

  • 谢谢!我自己假设布局会默认为流动。感谢您的帮助!
  • @NStafford 如果您对回答感到满意,请投票+接受我的回答。谢谢。
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 2022-11-27
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
  • 2019-06-11
  • 2019-02-22
  • 2020-01-27
相关资源
最近更新 更多