-1

I wrote a program, expecting it to be displayed in the middle of the screen by using getWidth() and getHeight() methods, but, instead, it appears on the upper left corner. So my question is aren't the getWidth() and getHeight() methods supposed to get the width and height of the whole screen?

/*
 * 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;
JackDee
  • 1
  • 1
  • 4
  • 5
    What are `GraphicsProgram`, `getHeight`, `getWidth`? These are not standard Java classes/methods... – assylias Jan 17 '14 at 10:51

2 Answers2

2

getWidth() / getHeight() are defined in Component, thus they return the size of the component you call them on (in your case this will be a component inside a window).

Check out the Swing tutorial http://docs.oracle.com/javase/tutorial/uiswing/components/ to get an understanding how components are combined to form user interfaces.

Do note that "the screen" is not a Swing object, and that the entire concept of "the screen" is an outdated thinking concept. I have two screens on my desk, and so has almost every one in my company. You may want to adapt your mental model to (current) reality.

Centering a window (on what?) is a non-trivial task in multiple screen setups. Refer to this question How to center a Window in Java? and its answers.

Community
  • 1
  • 1
Durandal
  • 19,919
  • 4
  • 36
  • 70
0

Use setLocationRelativeTo(null) line. This will make the component to open from middle.

Vighanesh Gursale
  • 921
  • 5
  • 15
  • 31