Friday, March 18, 2011

How to create GUI in Java

In last post we have created a GUI. The basic to crate a GUI is consist of following steps.......

1.Create a class that extends JFrame/Jpanel/JApplet.

2.Create a default constructor, and a method void initComp() .In this method in first line set the layout of frame to null.

3.Call the initComp method in constructor, and in next line set the title of main window(this.setTitle("Title");) , then in next line set bounds, then set default close operation to EXIT_ON_CLOSE , then in next line setResizable.

4.Now write main method and write..(new <classname>().setVisible(true);).

5.Now your code is ready to run but this will only show a blank window.

6.To add component on this window firstly declare the objects of components. Now create a method for each component like..void myCompnent(). In this method first create object then set text,set bounds, set visible and then add to this frame. Now if you want to handle any event with this component write the event handler for the componet.

7.Now call these methods in the initComp method.

8.Now the code is complete you can use it.

The main problem in this code is to write event handler which I publish in next post.


Sample GUI class in Java

Java is specially designed for GUI programming. So we here start our chapter with making GUI........


To work with GUI we need a main window to work with. In Java we can use JFrame, JApplet, or JPanel  to create GUI. The best practice is to use JFrame.

Here we have a sample class which make a GUI with JFrame....


Sample GUI class in Java :

// package
        package mpc;
//  imports
    import java.awt.Color;
    import javax.swing.*;
    import java.awt.event.*;
// class extends jframe or jpanel
    public class App extends JFrame{
// constructors
    public App() {
    initComp();
    }
// main method
    public static void main(String[] args) {
    new App();
    }
// initComp method
    void   initComp() {
    this.myBtn();
    this.myLbl();
    this.setLayout(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);
    this.setBounds(10, 10, 300, 350);
    this.setVisible(true);
    }
// 1st component’s method
    void myBtn() {
    btn=new JButton();
    btn.setText("Click");
    btn.setBounds(5, 5, 100, 25);
    btn.setVisible(true);
    this.add(btn);
    btn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    myBtnActionPerformed(e);}
    });
    }
// 1st component’s event handler
    void  myBtnActionPerformed(ActionEvent e){
    lbl.setText("Hello.");
    }
// 2nd component’s method
    void myLbl() {
    lbl=new JLabel();
    lbl.setText("");
    lbl.setBounds(7, 30, 100, 35);
    lbl.setVisible(true);
    this.add(lbl);
    }
// variable and component dec.
    JLabel lbl;
    JButton btn;
    }
//end of class