Friday, May 10, 2013

Screen size

The ScreenSize program gets the size or dimension of the screen by using the getScreenSize method of the Toolkit class. Based the screen size, a new dimension is constructed for the JFrame window component. The size of JFrame window component is  one-fourth of the  screen size.

ScreenSize source code:

import java.awt.*;
import javax.swing.*;

class ProgramWindow extends JFrame{
1                      Dimension ds=getToolkit().getScreenSize();
2                      int scWidth=(int)ds.getWidth();
3                      int scHeight=(int)ds.getHeight();
4                      Dimension newds=new Dimension(scWidth/2,scHeight/2);
5                      setPreferredSize(newds);
6                      setDefaultCloseOperation(EXIT_ON_CLOSE);
7                      setTitle("Screen Size: width="+scWidth+", height="+scHeight);
8                      setVisible(true);
9                      pack();
public class ScreenSize{
public static void main(String args[]){
            new ProgramWindow();


Screen Size in Java

Code Explanation
1. Get the size or dimension (width and height) of the screen.
2. Read the width of the screen from dimension object ds.
3. Read the height of the screen from dimension object ds.
4. Construct a new dimension newds which is one-fourth of the screen size.
5. Set the size of the JFrame window component by using the setPreferredSize method.
6. Allow the JFrame widnow component to close when the close button is clicked.
7. Set the title of the JFrame window component.
8. Make sure the JFrame window visible.
9. Make sure the JFrame window resized to fit its preferred size by using the pack method.

No comments:

Post a Comment