Java Swing:如何指定组件的位置和大小?

时间:2014-01-04 16:30:51

标签: java swing user-interface jcomponent

我还在大学学习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);
}

如果代码/问题不够明确,请道歉。

提前致谢。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

是布局管理器是最佳解决方案

像eclipse或netbeans这样的IDE可以帮助您轻松地以不同的布局直观地定位组件。

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

如果您想自己编码,请在此链接中拥有所有资源 http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

相关问题