【问题标题】:getHeight() and getWidth() methodgetHeight() 和 getWidth() 方法
【发布时间】:2014-01-17 10:49:41
【问题描述】:

我写了一个程序,希望通过 getWidth() 和 getHeight() 方法显示在屏幕中间,但它却出现在左上角。所以我的问题是 getWidth() 和 getHeight() 方法不是应该获取整个屏幕的宽度和高度吗?

/*
 * This program displays Pascal's Triangle for 8 rows.
 */

import acm.graphics.*;
import acm.program.*;


public class combination extends GraphicsProgram {
    public void run() {
        for(int i = 0; i < NROWS; i++) {
            for (int n = 0; n <= i; n++) {

        add(new GLabel(Combination(i,n), x(i,n), y(i))); //the     coordination and the amount of labels are related to i;

        }       
    }
}

//method that adds labels on the screen.//
private String Combination(int i, int n) { //this method returns a string which   would be added to the screen.//

    return (String.valueOf(i) +","+ String.valueOf(n)); 
    }


//method that set the y coordination for the label//
private double y(int i) {
    double Height = getHeight()/NROWS;
    return i * Height + 9;

}

//method that set the x coordination for the label//
private double x(int i, int n)  {
    double Orgnx = getWidth() / 2;
    double HalfBase = getHeight() / NROWS / Math.sqrt(3);
    double Base = HalfBase * 2;
    return Orgnx - i * HalfBase + n * Base;
    }


/*The program displays 8 rows of pairs of number.*/
private static final int NROWS = 8;

【问题讨论】:

  • 什么是GraphicsProgramgetHeightgetWidth?这些不是标准的 Java 类/方法...

标签: java


【解决方案1】:

getWidth() / getHeight() 在 Component 中定义,因此它们返回您调用它们的组件的大小(在您的情况下,这将是 窗口内的组件)。 p>

查看 Swing 教程 http://docs.oracle.com/javase/tutorial/uiswing/components/,了解如何组合组件以形成用户界面。

请注意,“屏幕”不是 Swing 对象,“屏幕”的整个概念是一个过时的思维概念。我的办公桌上有两个屏幕,公司里几乎每个屏幕都有。您可能希望使您的心智模型适应(当前)现实。

将窗口居中(在什么位置?)在多屏幕设置中是一项非常重要的任务。请参阅此问题How to center a Window in Java? 及其答案。

【讨论】:

    【解决方案2】:

    使用setLocationRelativeTo(null) 行。这将使组件从中间打开。

    【讨论】:

      猜你喜欢
      • 2015-05-02
      • 2011-09-02
      • 2013-03-30
      • 2014-03-02
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2020-06-20
      • 2015-07-24
      相关资源
      最近更新 更多