Sunday, May 18, 2014

how to use JPanel in java?





JPanel is a lightweight container which can hold components. The default layout of JPanel is FlowLayout. Using this we can add components like button, textfield etc. If it is requirement of adding components on JPanel, Then at first add components on JPanel and then finally add JPanel on JFrame because JPanel is itself a component.

To use JPanel using program:-



frme.java

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;

import java.awt.FlowLayout;

import java.awt.Container;

class frme extends JFrame

{  private Container c;

 frme()

 {    c=getContentPane();

  c.setLayout(new FlowLayout());

  setTitle("Using JPanel");

 /* create object of class 'panl' */

  panl pn=new panl();

 /* add panl's class object to container   */

  c.add(pn);

  setSize(400,200);

  setVisible(true);

  setDefaultCloseOperation(EXIT_ON_CLOSE);

  } //close of constructor of class frme

public static void main(String args[])

 {    new frme();

 }  } //close of class frme

 panl.java
class panl extends JPanel

{ 

JButton btnLogin,btnCancl;

 panl()

 {

 btnLogin=new JButton("Button1");

 btnCancl=new JButton("Cancle");

add(btnLogin); add(btnCancl); add(new panltxtbox()); 

 } //close of constructor of class panl



class panltxtbox extends JPanel

 {  

JTextField jf;

 panltxtbox()

  {   jf=new JTextField(10);

  add(jf);

  }

  } //close of class panltxtbox



} //close of class panl




Here is the Output:


No comments:

Post a Comment