Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...