Wednesday, January 26, 2011

How To Create a JFrame in Java



This post will teach you how to create a Java Frame using the swing library. It's been a while now since I got to play with Java swing because I've been working with web, of course using the Java Programming Language.

I guess you know Java because you came across to this site. Somehow looking for a simple program to start. Maybe you got a mini-school project or an assignment you want to work on.

Open your Eclipse IDE and let's get started. Create a java project (File>New>Java Project). Name your project in any way you want it, mine is JavaSwing. Don't forget to create a pachage.

To create a simple frame in java, you need to import javax.swing.JFrame. See code below.

package com.javaswing;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class JavaSwing {
  public static void main(String []argv){     
   SwingUtilities.invokeLater(new Runnable(){
    public void run(){
      JFrame frame = new JFrame("Example Frame");
      frame.setSize(300, 300);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
    }
   });
  }
}
Code in Eclipse
Run as Java Application
The frame
Your application should use SwingUtilities.invokeLater because it is the proper way. Your application should always be thread safe.

Learn More:

No comments:

Post a Comment