Desktop Java 8 – part 1- creating simple window application

This topic describes how create simple  window in Java for desktop application.

The code in this post creates white window with 400 px width and 200 px heigth. Begin with creating JFrame object with parameter of String datatype. It is title this window. Call setSize method of JFrame class. This method get two parameters: width and heigth of window. They are necessary to determine size of window.  You may either change background color this window. For JFrame object call getContentPane method and for it call setBackground method with Color parameter. Color object with white static variable set white color for component. At the end You need allow users for close window. This operation is possible if the setDefaultCloseOperartion method is call with JFrame.EXIT_ON_CLOSE parameter. The window will be visible if You call setVisible method with true parameter.

package doraprojects;

import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;

public class MyWindow 
{
    
public static final int WIDTH_WINDOW = 400;
public static final int HEIGHT_WINDOW = 200;

    public static void main(String[] args) 
    {
        
    EventQueue.invokeLater(new Runnable(){
     public void run()
     {    
        JFrame f = new JFrame("My window");
        f.setSize(WIDTH_WINDOW, HEIGHT_WINDOW); 
        f.getContentPane().setBackground(Color.white);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      }
        }); 
   }
}

The result run this code:
ww11

If You omitt setSize method You see only title bar Your window:

...
        JFrame f = new JFrame("My window");

        f.getContentPane().setBackground(Color.white);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
...

Result:

But if You don’t call for JFrame setVisible method the window don’t appear.