What does this piece of code mean?

Asked

Viewed 441 times

0

Recently I came across a stone in the shoe, I was going to comment on a code, but I realized I was filling sausage when commenting on it, because I do not know what is the actual use of the code below:

Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
lblResolucao.setText(+d.width +" x " +d.height);

In this case it’s a Swing code to capture the device resolution, but I have no idea why they’re there (it’s confusing even to explain).

I would like you to explain the first 2 lines IN DETAIL so that I can really understand the code.

2 answers

3

To Toolkit is a super class that contains information about the most diverse types of windows and frames in Java. Understand as if it contains a lot of raw information about windows, as it is not advised to access this information directly you use other classes to obtain the refined information of this first.

In your case you use the class Dimension for information on the size of your device window. For more information see the class documentation Toolkit.

http://docs.oracle.com/javase/6/docs/api/java/awt/Toolkit.html

3


Reading of the code:

On the line Toolkit tk = Toolkit.getDefaultToolkit(); you make use of the static method getDefaultToolkit() to return the Toolkit platform-specific Toolkit being a superclass of all current implementations of Abstract Window Toolkit(AWT), and saved in reference tk, of the kind Toolkit.

On the line Dimension d = tk.getScreenSize(); you access the method getScreenSize() of your object tk, which returns an object of the type Dimension, that encapsulates the values width and height with the width and height of the screen.

/*
 * Output:
Screen width = 1280
Screen height = 1024
 */

import java.awt.Dimension;
import java.awt.Toolkit;

public class MainClass {
  public static void main(String[] args) {
    Toolkit tk = Toolkit.getDefaultToolkit();
    Dimension d = tk.getScreenSize();
    System.out.println("Screen width = " + d.width);
    System.out.println("Screen height = " + d.height);

  }
}
  • AWT is not a class.

  • Okay. I’ll fix it. This error was a mistaken and mistaken translation of the excerpt "This class is the Abstract superclass of all current implementations of the Abstract Window Toolkit. Subclasses of the Toolkit class are used to bind the Various Components to particular Native Toolkit implementations. " of the Toolkit class documentation.

  • Another thing, what with height encapsula? It became very vague.

  • Fixed. Encapsulates screen width and height values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.