Pages

Saturday, January 14, 2012

Java GUI Tutorial 1 - JFrame and JPanel

GUI = "Graphical User Interface"


JFrame and JPanel are simply two files included in Java to allow you to create displayable content.

Let's start with an understanding of the relationship between the JPanel and JFrame. (NEWCOMERS, DO NOT SKIP THIS).

First off, JFrames contain JPanels! This is important because if you tried to add an instance of JFrame to one of JPanel your program would not function as desired. Think of JFrame as a stretchable picture frame that can hold an as much visible content (JPanels, JButtons, JLabels,...) or even no visual elements what-so-ever.
The JPanel is like a canvas. It rests inside the JFrame and carries out its JPanel functions independently (mostly) of the JFrame. A JPanel without a JFrame (or other type of frame) would be invisible, which defeats the point of an application.

Example Code #1


import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* W7R.blogspot.com 
* GUI Tutorial Part 1: JFrame and JPanel
* Example Code #1
*
*/
 class Example {
   public static void main(String[] args){

      //Create a JFrame named frame1 with a title of "Frame Name"
     JFrame frame1 = new JFrame("Frame Name");

      //Create a JPanel names panel1 with no parameters
     JPanel panel1 = new JPanel();
   }
}
In the example code (#1), in the main method, I created a JFrame, "frame1" and a Jpanel, "panel1" Now you have two variables, 1 JPanel and 1 JFrame. We need to add the JPanel into the JFrame with a method in the JFrame class called "add." To make the window visible it will also be necessary to utilize the "show" method.
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* W7R.blogspot.com 
* GUI Tutorial Part 1: JFrame and JPanel
* Example Code #2
*
*/
 class Example{
   public static void main(String[] args){

      //Create a JFrame named frame1 with a title of "Frame Name" and 
      //set our JFrame to be 200 pixels wide and 200 pixels high.
     JFrame frame1 = new JFrame("Frame Name");
     frame1.setSize(200,200);
//Create a JPanel names panel1 with no parameters
     JPanel panel1 = new JPanel();
   
     frame1.add(panel1);
      
     frame1.show();
   }
}

In the example code (#2) We put the frame and panel together and display it.
You will notice that the window is incredibly small: this is because we haven't given it content to hold yet!




That is all for now, but I am eager to continue this subject in GUI Tutorial Part 2, but just to keep you on your toes: All of the JPanel Methods.

For example, you can play around with the setBackground method

panel1.setBackground(Color.BLUE);

No comments:

Post a Comment