【问题标题】:Java Swing: How to specify location and size of components? [closed]Java Swing:如何指定组件的位置和大小? [关闭]
【发布时间】:2014-01-04 16:30:50
【问题描述】:

我还在大学学习 java,但我只是想知道如何将 JComponent 放在特定位置并指定它们的大小。

我见过setLocation() 和那种方法,但我真的很想知道如何在不使用那些布局管理器(流、网格、边框?)的情况下放置Component

下面是我想应用这些知识的代码:它们是显示相同窗口的两个重载方法。

public void addWelcome()
{
    setWindow();
    MaxDimension = new Dimension(WelcomeLabelDimensionWidth,WelcomeLabelDimensionHeight);
    getWindow().setMaximumSize(MaxDimension);
    MinDimension = new Dimension(WelcomeLabelDimensionWidth,WelcomeLabelDimensionHeight);
    getWindow().setMinimumSize(MinDimension);
    getWindow().setTitle("Bills");
    getWindow().setSize(WindowWidth,WindowHeight);
    getWindow().setDefaultCloseOperation(EXIT_ON_CLOSE);
    getWindow().setLayout(new GridLayout(5,1,2,0));
    getWindow().add(getWelcomeLabel());
    getWindow().add(getGreetLabel());
    getWindow().add(getDescriptionLabel());
    getWindow().add(getInstructionLabel());
    getWindow().add(getStartButton());  
    getWindow().pack();
    getWindow().setVisible(true);

}


public void addWelcome(final int Width, final int Height)
{
    setWindow();
    MaxDimension = new Dimension(Width,Height);
    getWindow().setMaximumSize(MaxDimension);
    MinDimension = new Dimension(Width,Height);
    getWindow().setMinimumSize(MinDimension);
    getWindow().setTitle("Bills");
    getWindow().setSize(WindowWidth,WindowHeight);
    getWindow().setDefaultCloseOperation(EXIT_ON_CLOSE);
    getWindow().setLayout(new GridLayout(5,1));
    getWindow().add(getWelcomeLabel());
    getWindow().add(getGreetLabel());
    getWindow().add(getDescriptionLabel());
    getWindow().add(getInstructionLabel());
    getWindow().add(getStartButton());
    getWindow().setVisible(true);
}

如果代码/问题不够清楚,请道歉。

提前致谢。

【问题讨论】:

  • 为什么不使用布局管理器?您迟早需要学习它们,因此请熟悉它们。甲骨文有一些good tutorials
  • 还可以尝试将您的问题缩小到与您的代码有关的更具体的问题。
  • 另一个问题 java noob 哈哈。这些布局有更多自定义组件定位的方法吗?并且假设它们在工业中被大量使用,对吗?
  • 是的,布局管理器非常频繁。不同的 LayouManager 有不同的规格。即有些保留首选尺寸,而有些则不保留。因此,您需要了解哪些可以,哪些不可以。对于更强大的定位精度,有像 GridBagLayout 这样的 LayoutMangers。我强烈建议您通读整个教程。并让他们感到舒适
  • 非常感谢您的帮助!我会毫无保留地阅读这些教程。谢谢:)

标签: java swing user-interface jcomponent


【解决方案1】:

您可以使用Absolute Layout,这让您负责定位所有内容。请注意,这也使得创建可用于不同屏幕和窗口大小的布局几乎是不可能的(所以,是的,学习使用正确的布局)。

【讨论】:

    【解决方案2】:

    是的,布局管理器是最好的解决方案

    Eclipse 或 netbeans 之类的 IDE 可以帮助您轻松地以不同的布局直观地定位组件。

    它会自动生成您可以轻松观察和学习的代码。

    如果您想自己编写代码,您可以在此链接中找到所有资源 http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

    【讨论】:

      猜你喜欢
      • 2011-09-03
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多