Pages

JComponents class

JComponent is an abstract class , is the root class of almost of all Swing's user-interface ("J") components. JComponent's root class is the Object class, which is defined in the java.lang.Object file. JComponent also inherits from the AWT Container and Component classes.


JButton class

The JButton class is used to create button that has platform-independent implementation.

Commonly used constructor

  • JButton() : Creates a button with no text and icon.
  • JButton(String s) : Creates a button with the specified Text.
  • JButton(Icon i) : Creates a button with the specified icon object

Commonly used Methods of AbstractButton class

  • public void setText(String s) : It is used to set specified text on button.
  • public String getText() : It is used to return the text of the button.
  • public void setEnabled(boolean b) : It is used to enable or disable the button.
  • public void setIcon(Icon b) : It is used to set the specified Icon on the button.
  • public Icon getIcon() : It is used to get the Icon of the button.
  • public void setMnemonic(int a) : It is used to set the mnemonic on the button.
  • public void addActionListener(ActionListener e) : It is used to add the action listener to this object.
Note : The JButton class extends AbstractButton class.

Exmaple of Displaying Image on the JButton

import java.awt.event.*;
import javax.swing.*;

class ImageButton
{
ImageButton()
{
JFrame f = new JFrame();
JButton b = new JButton(new ImageIcon("img.jpg"));
b.setBounds(130,100,100,40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
new ImageButton();
}
}


JToggleButton class

The Event Listener used in this case is an Item Listener. In this small example we show how a JToggleButton is instantiated just like a normal JButton, but with a different method for catching events.

Example of JToggleButton

import java.awt.*;
import javax.swing.*;

class JToggleButtonDemo
{
JToggleButtonDemo()
{
JFrame frame = new JFrame("hungry4java.blogspot.com");
frame.setLayout(null);
JToggleButton b1 = new JToggleButton("Click");
b1.setBounds(50,50,100,100);
frame.add(b1);

JToggleButton b2 = new JToggleButton("Focused");
b1.setBounds(200,50,100,100);
frame.add(b2);

JToggleButton b3 = new JToggleButton("Not selected");
b1.setBounds(350,50,120,100);
frame.add(b3);

frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
new JToggleButtonDemo();
}
}


JRadioButton class

Radio button allows to select only one radio button in each group at a time . Here single selection maximum can possible . If a radio button is selected , whatever the previous radio button is , it will be deselected. To work with radio button , we need two classes. First, we create the radio buttons with the JRadioButton class and then we create a group for the buttons with the ButtonGroup class.

Commonly used constructor of JRadioButton class

  • JRadioButton() : It creates an unselected radio button with no text.
  • JRadioButton(String s) : It creates an unselected radio button with specified text.
  • JRadioButton(String s, boolean selected) : It creates a radio button with the specified Text and selected status.
Note: 
  • The JRadioButton class extends the JToggleButton class that extends AbstractButton class.
  • The ButtonGroup class can be used to group multiple buttons so that at a time only one button can be selected.

Example of JRadioButton class


import javax.swing.*;



class Radio

{
JFrame f;
Radio()
{
f = new JFrame();
JRadioButton r1 = new JRadioButton("A) Male");
JRadioButton r2 = new JRadioButton("A) Female");
r1.setBounds(50,100,70,30);
r2.setBounds(50,150,70,30);

ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);
f.setSize(300,300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String [] args)
{
new Radio();
}
}


JCheckBox class

JCheckBox class is a control that the user can click to either check or uncheck. Here multiple selection can possible.

Example of JCheckBox class

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class CheckRadio extends JFrame
{
JCheckBox oracle, c, java, cp;
JRadioButton male, female;
ButtonGroup bg;

public CheckRadio()
{
setLayout(new FlowLayout());

oracle = new JCheckBox("ORACLE");
c = new JCheckBox("Advance C");
java = new JCheckBox("Core JAVA");
cp = new JCheckBox("C++");

male = new JRadioButton("Male",true);
female= new JRadioButton("Female");

bg = new ButtonGroup();
bg.add(male);
bg.add(female);

add(oracle);
add(c);
add(cp);
add(java);
add(male);
add(female);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setTitle("Please Select");
setSize(300,300);
setVisible(true);
}

public static void main(String [] args)
{
new CheckRadio();
}

}


JMenuItem class, JMenu class and JMenuBar class

Example of Notepad (This Notepad doesn't act like actual Notepad. I will provide you complete program of Notepad Later in this tutorial.)

import javax.swing.*;
import java.awt.event.*;

public class Notepad implements ActionListener
{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;

Notepad()
{
f = new JFrame("Sample Notepad");
cut = new JMenuItem("cut");
copy = new JMenuItem("copy");
paste = new JMenuItem("paste");
selectAll = new JMenuItem("selectAll");

cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);

mb = new JMenuBar();
mb.setBounds(5,5,400,40);

file = new JMenu("File");
edit = new JMenu("Edit");
help = new JMenu("Help");

edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(selectAll);
mb.add(file);
mb.add(edit);
mb.add(help);

ta = new JTextArea();
ta.setBounds(5,30,460,460);

f.add(mb);
f.setLayout(null);
f.setSize(500,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==selectAll)
ta.selectAll();
}

public static void main(String[] args)
{
new Notepad();
}
}


JCheckBoxMenuItem class and JRadioButtonMenuItem class

Example of JCheckBoxMenuItem class and JRadioButtonMenuItem class

import javax.swing.*;

class MenuDemo
{
MenuDemo()
{
JFrame f = new JFrame();

JMenuBar mbr = new JMenuBar();
mbr.setBounds(0,0,400,30);
f.setLayout(null);
f.add(mbr);
f.setVisible(true);
f.setSize(300,300);
f.setTitle("My Notepad");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
mbr.add(file);
mbr.add(edit);

JMenuItem open = new JMenuItem("Open");
JMenuItem New = new JMenuItem("New");
JMenuItem close = new JMenuItem("Close");
file.add(open);
file.add(New);
file.add(new JSeparator()); //adds a line before close option
file.add(close);

JCheckBoxMenuItem cbm1 = new JCheckBoxMenuItem("Auto Complete");
file.add(cbm1);
JCheckBoxMenuItem cbm2 = new JCheckBoxMenuItem("Auto Correction");
file.add(cbm2);

JRadioButtonMenuItem jr1 = new JRadioButtonMenuItem("Male");
file.add(jr1);
JRadioButtonMenuItem jr2 = new JRadioButtonMenuItem("Female");
file.add(jr2);

ButtonGroup bg = new ButtonGroup();
bg.add(jr1);
bg.add(jr2);
}

public static void main(String[] args)
{
new MenuDemo();
}
}



JTextArea class, JTextField, JPasswordField class and JLabel class

The JTextArea class is used to create a text area. It is a multiline area that displays the  plain text only.

Commonly used constructors

  • JTextArea() : It creates a text area that displays no text initially.
  • JTextArea(String s) : It creates a text area that displays specified text initially.
  • JTextArea(int row, int column) : It creates a text area with the specified number of rows and columns that displays no text initially.
  • JTextArea(String s, int row, int column) : It creates a text area with the specified number of rows and columns that displays specified text.

Commonly used methods of JTextArea class

  • public void setRows(int rows) : It is used to set specified number of rows.
  • public void setColumns(int cols) : It is used to set specified number of columns.
  • public void setFont(Font f) : It is used to set the specified font.
  • public void insert(String s, int position) : It is used to insert the specified text on the specified position.
  • public void append(String s) : It is used to append the given text to the end of the document.

Example of  JTextArea class, JTextField, JPasswordField class and JLabel class

import java.awt.Color;
import javax.swing.*;

class TextComponentDemo
{
TextComponentDemo()
{
JFrame f = new JFrame("Enter to login");

JTextArea area = new JTextArea(300,200);
area.setBounds(10,30,150,200);
f.add(area);

JLabel lname = new JLabel("Enter username :");
JLabel lpass = new JLabel("Enter password :");
lname.setBounds(170,60,100,40);
lpass.setBounds(170,110,100,40);
f.add(lname);
f.add(lpass);

JTextField field = new JTextField(10);
field.setBounds(280,60,150,40);
f.add(field);

JPasswordField pass = new JPasswordField(10);
pass.setBounds(280,110,150,40);
f.add(pass);
area.setBackground(Color.gray);

f.setSize(500,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String [] args)
{
new TextComponentDemo();
}
}


JComboBox class

The JComboBox class is used to create the combobox (drop-down list). At a time only one Item can be selected from the Item list.

Commonly used Constructors of JComboBox class

  • JComboBox()
  • JComboBox(Object[] items)
  • JComboBox(Vector<?> items)

Commonly used methods of JComboBox class

  • public void addItem(Object anObject) : It is used to add an item to the item list.
  • public void removeItem(Object anObject) : It is used to delete an item to the item list.
  • public void removeAllItems() : It is used to remove all the items from the list.
  • public void setEditable(boolean b) : It is used to determine whether the JComboBox is editable.
  • public void addActionListener(ActionListener a) : It is used to add the ActionListener.
  • public void addItemListener(ItemListener i) : It is used to add the ItemListener.

Example of JComboBox class

import javax.swing.*;

class Combo
{
JFrame f;
Combo()
{
f = new JFrame("Combo Exmaple");
String country[] = {"India","Aus","U.S.A","England","Newzeland"};
JComboBox cb = new JComboBox(country);
cb.setBounds(50,50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args)
{
new Combo();
}
}



JList class and JScrollPane class

JList is a GUI element available in javax.swing package which allows selection of one or more element. JList elements are uneditable, JList does not support any rendering. VisibleRowCount property of JList is used to display number of rows when a JList is placed on Scrollpane. you can change it by using method setVisibleRowCount(). JScrollPane provides a scrollable view of a lightweight component.

Example of JList class and JScrollPane class

import javax.swing.*;
import java.awt.*;

class JListDemo
{
JListDemo()
{
JFrame f = new JFrame("JListDemo-hungry4java.blogspot.com");
f.setLayout(new FlowLayout());
String city[] = new String[] {"BBSR","CTC","BMP","RKL","BKSC","SBL","PURI","CRP","DHN"};
JList list = new JList(city);
list.setVisibleRowCount(4);
JScrollPane listPane = new JScrollPane(list);
f.add(listPane);
f.setSize(300,300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
new JListDemo();
}
}



JSpinner class

JSpinner are similar to JComboBoxes and JLists in that they let the user choose from a range of values. Like editable combo boxes, spinner allow the user to type in a value. Unlike combo boxes, spinner do not have a drop-down list that can cover up other components. Because spinners do not display possible values - only the current value is visible  - they are often used instead of combo boxes or list when the set of possible values is extremely large. However spinners should only be used when the possible values and their sequence are obvious.

Example of JSpinner class

import java.awt.*;
import java.util.*;
import javax.swing.*;

class JSpinnerDemo
{
JSpinnerDemo()
{
JFrame f = new JFrame("JSpinner Demo");

JLabel label1 = new JLabel("Select Number");
JSpinner spnNumber = new JSpinner();

label1.setBounds(100,100,100,20);
spnNumber.setBounds(100,130,40,20);

f.add(label1);
f.add(spnNumber);

JLabel label2 = new JLabel("Select color");
String[] colors = {"Red","Green","Blue"};
SpinnerModel snl = new SpinnerListModel(colors);
JSpinner spnList = new JSpinner(snl);

f.add(label2);
f.add(spnList);
label2.setBounds(100,200,100,20);
spnList.setBounds(100,230,70,20);

f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600,600);
f.setVisible(true);
}

public static void main(String [] args)
{
new JSpinnerDemo();
}
}



JScrollBar class

A scrollbar consists of a rectangular tab called slider or thumb located between two arrow buttons. Two arrow buttons control the position of the slider by increasing or decreasing a number of units. The area between the slider and the arrow buttons is known as paging area. The slider's position of scrollbar can be changed by:
  • Dragging the slider up and down or left and right.
  • Pushing on either of two arrow buttons.
  • Clicking the paging area.
To create a scrollbar in swing, you use JScrollBar class . You can create either vertical or horizontal scrollbar.

Constructor of JScrollBar

  • JScrollBar() : It creates a vertical scrollbar.
  • JScrollBar(int orientation) : It creates a scrollbar with a given orientation.
  • JScrollBar(int orientation, int value, int extent, int min, int max)

Example of JScrollBar class

import javax.swing.*;
import java.awt.*;

class JScrollBarDemo extends Frame
{
JScrollBarDemo()
{
JScrollBar h = new JScrollBar(0,1,50,1,275);
JScrollBar v = new JScrollBar(1,1,20,1,275);

setLayout(null);
h.setBounds(100,100,200,20);
v.setBounds(150,130,20,200);

add(h);
add(v);
setTitle("JScrollBar Demo");
setSize(300,300);
setVisible(true);
}

public static void main(String[] args)
{
new JScrollBarDemo();
}
}



JProgressBar class

The JProgressBar class is used to display the progress of the task.

Commonly used Constructors of JProgressBar class

  • JProgressBar() : It is used to create a horizontal progress bar but no string text.
  • JProgressBar(int min, int max) : It is used to create a horizontal progress bar with the specified minimum and maximum value

  • JProgressBar(int orient) : It is used to create a progress bar with the specified orientation, it can be either vertical or horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.
  • JProgressBar(int orient, int min, int max) : It is used to create a progress bar with the specified orientation, minimum and maximum value.

Commonly used methods of JProgressBar class

  • public void setStringPainted (boolean b) : It is used to determine whether string should be displayed.
  • public void setString (String s) : It is used to set value to the progress string.
  • public void setOrientation (int orientation) : It is used to set the orientation, it may be either vertical or horizontal by using SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants.
  • public void setValue (int value) : It is used to set the current value on the progress bar.

Example of JProgressBar class

import javax.swing.*;

class MyProgress extends JFrame
{
JProgressBar jb;
int i=0, num=0;

MyProgress()
{
jb = new JProgressBar(0,2000);
jb.setBounds(40,40,200,30);

jb.setValue(0);
jb.setStringPainted(true);

add(jb);
setSize(400,400);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void iterate()
{
while(i<=2000)
{
jb.setValue(i);
i+=20;
try
{
Thread.sleep(150);
}
catch (Exception e)
{
}
}
}

public static void main(String[] args)
{
MyProgress m = new MyProgress();
m.setVisible(true);
m.iterate();
}
}

JSlider class

The JSlider is used to create the slider. By using JSlider a user can select a value from a specific range.

Commonly used Constructor of JSlider class

  • JSlider() : creates a slider with the initial value of 50 and range of 0 to100.
  • JSlider (int orientation) : creates a slider with the specified orientation set by either                              JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial                    value 50.
  • JSlider (int min, int max) : creates a horizontal slider using the given min, max.
  • JSlider (int min, int max, int value) : creates a horizontal slider using the given min, max and                value.
  • JSlider (int orientation, int min, int max, int value) : creates a slider using the given                                orientation, min, max and value.

Commonly used Methods of JSlider class

  • public void setMinorTickSpacing (int n) : It is used to set the minor tick spacing to the                               slider.
  • public void setMajorTickSpacing (int n)  : It is used to set the major tick spacing to the                               slider.
  • public void setPaintTicks (boolean b) : It is used to determine whether tick marks are                                  painted.
  • public void setPaintLabels (boolean b) : It is used to determine whether labels are painted.
  • public void setPaintTracks (boolean b) : It is used to determine whether track is painted.

Example of JSlider class


import javax.swing.*;

class JSliderDemo extends JFrame
{
public JSliderDemo()
{
JSlider slider = new JSlider(JSlider.HORIZONTAL,0,50,25);
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
JPanel panel = new JPanel();
panel.add(slider);
add(panel);
}

public static void main(String[] args)
{
JSliderDemo frame = new JSliderDemo();
frame.pack();
frame.setVisible(true);
frame.setTitle("JSlider Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}





JPopupMenu class

Popup menu represents a menu which can be dynamically popped up at a specified position within a component. A popup menu appears anywhere on the screen when a right mouse button is clicked.

Example of JPopupMenu class

import javax.swing.*;
import java.awt.event.*;

class PopUpMenu
{
JPopupMenu pmenu;
JMenuItem menuItem;
public static void main(String[] args)
{
PopUpMenu p = new PopUpMenu();
}

public PopUpMenu()
{
JFrame frame = new JFrame("hungry4java popup Menu");
pmenu = new JPopupMenu();
menuItem = new JMenuItem("Cut");
pmenu.add(menuItem);

menuItem = new JMenuItem("Copy");
pmenu.add(menuItem);

menuItem = new JMenuItem("Paste");
pmenu.add(menuItem);

menuItem = new JMenuItem("Delete");
pmenu.add(menuItem);

menuItem = new JMenuItem("Undo");
pmenu.add(menuItem);

frame.addMouseListener (new MouseAdapter()
{
public void mouseReleased(MouseEvent Me)
{
if(Me.isPopupTrigger())
{
pmenu.show(Me.getComponent(), Me.getX(), Me.getY());
}
}
});
frame.setSize(400,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}




JTree class

A control that displays a set of hierarchical data as an outline.

Example of JTree class with default constructor

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class TreeExample extends JFrame
{
public TreeExample()
{
//set the frame characteristics
setTitle("Simple Tree Application");
setSize(300,400);
setBackground(Color.red);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create a new tree control
JTree tree = new JTree();

add(tree);
}

public static void main(String[] args)
{
TreeExample mainFrame = new TreeExample();
mainFrame.setVisible(true);
}
}


JTable class

The JTable class is used to display the data on two dimentional table of cells.

Commonly used Constructors of JTable class

  • JTable () : creates a table with empty cells.
  • JTable (Object[][] rows, Object[] columns) : creates a table with the specified data.

Example of JTable class

import javax.swing.*;

class MyTable
{
JFrame f;

MyTable()
{
f = new JFrame("hungry4java.blogspot.com Table");
String data[][] = {{"101","Amit","670000"},{"102","jai","780000"},{"103","Sachin","700000"}};
String column[] = {"ID","NAME","SALARY"};

JTable jt = new JTable(data,column);
jt.setBounds(30,40,200,300);

JScrollPane sp = new JScrollPane(jt);
f.add(jt);

f.setSize(300,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args)
{
new MyTable();
}
}




JColorChooser class

The JColorChooser class is used to create a color chooser dialog box so that user can select any color.

Commonly used Constructor of JColorChooser class

  • JColorChooser () : It is used to create a color chooser pane with white colorinitially.
  • JColorChooser (Color initialColor) : It is used to create a color chooser pane with the                                   specified color initially.

Commonly used methods of JColorChooser class

  • public static Color showDialog (Component c, String title, Color initialColor) : It is used to                          show the color - chooser dialog box.

Example of JColorChooser class

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

class JColorChooserDemo extends JFrame implements ActionListener
{
JButton b;
Container c;
JColorChooserDemo()
{
c = getContentPane();
c.setLayout(new FlowLayout());
b = new JButton("Color");
b.addActionListener(this);
c.add(b);
}

public void actionPerformed(ActionEvent e)
{
Color initialcolor = Color.RED;
Color color = JColorChooser.showDialog(this,"Select a color",initialcolor);
c.setBackground(color);
}

public static void main(String[] args)
{
JColorChooserDemo ch = new JColorChooserDemo();
ch.setSize(400,400);
ch.setVisible(true);
ch.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}




JFileChooser class

JFileChooser provides a GUI for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser.

Example of JFileChooser class

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class OpenMenu extends JFrame implements ActionListener
{
JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
OpenMenu()
{
open = new JMenuItem("Open file");
open.addActionListener(this);

file = new JMenu("File");
file.add(open);

mb = new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);

ta = new JTextArea(800,800);
ta.setBounds(0,20,800,800);

add(mb);
add(ta);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource() == open)
{
openFile();
}
}

void openFile()
{
JFileChooser fc = new JFileChooser();
int i = fc.showOpenDialog(this);

if(i==JFileChooser.APPROVE_OPTION)
{
File f = fc.getSelectedFile();
String filepath =f.getPath();

displayContent(filepath);
}
}

void displayContent(String fpath)
{
try
{
BufferedReader br = new BufferedReader (new FileReader(fpath));
String s1="",s2="";

while((s1=br.readLine())!= null)
{
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}

public static void main(String[] args)
{
OpenMenu om = new OpenMenu();
om.setSize(800,800);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}




JOptionPane class

JOptionPane pop up  a standard dialog box that prompts users for a value of informs them of something.

Commonly used Methods of JOptionPane class

  • showConfirmDialog : Asks a confirming question, like yes/no//cancel.
  • showInputDialog : prompt for some input.
  • showMessageDialog : Tell the user about something that has happened.
  • showOptionDialog : The Grand Unification of the above three.

Example of JOptionPane class

import javax.swing.*;
import java.awt.*;

class JOptionPaneDemo extends JFrame
{
JOptionPaneDemo()
{
setSize(300,300);
setVisible(true);
setLocation(500,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JOptionPane.showMessageDialog(null,"Hello welcome to hungry4java.blogspot.com");
JOptionPane.showMessageDialog(null,"alert","alert",JOptionPane.ERROR_MESSAGE);
JOptionPane.showConfirmDialog(null,"Do you Like hungry4java.blogspot.com","Do you Like hungry4java.blogspot.com",JOptionPane.YES_NO_OPTION);
Object[] option = {"OK","CANCEL"};
JOptionPane.showOptionDialog(null,"Click OK to continue","Warning",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null,option,option[0]);
}

public static void main(String [] args)
{
new JOptionPaneDemo();
}
}




JSplitPane class

A JSplitPane displays two components, either side by side or one on top of the other. By dragging the divider that appears between the components, the user can specify how much of the split pane's total area goes to each component. You can divide screen space among three or more components by putting split panes inside of split panes.

Example of JSplitPane class

import java.awt.*;
import javax.swing.*;

class SwingSplitDemo 
{
public static void main(String[] args)
{
JFrame frame = new JFrame("JSplitPane Sample");
JSplitPane splitPane = new JSplitPane();
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
frame.add(splitPane);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,200);
frame.setVisible(true);
frame.setLayout(null);
}
}



JRootPane class

In general, you don't directly create a JRootPane object. Instead, you get a JRootPane (whether you want it or not!) when you instantiate JInternalFrame or one of the top - level Swing containers, such as JApplet, JDialog, and JFrame.

Example of JRootPane class

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JRootPane;

public class RootExample
{
public static void main(String [] args)
{
JFrame f = new JFrame("MY RootPane");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRootPane root = f.getRootPane();

//Create a menu bar
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
bar.add(menu);
menu.add("OPen");
menu.add("Close");
root.setJMenuBar(bar);

//Add a button to the content pane
root.getContentPane().add(new JButton("Hello friends!! How are you??"));

//Display the UI
f.pack();
f.setVisible(true);
}
}



JTabbedPane class

With the JTabbedPane class, you can have several components, such as panels, share the same space. The user chooses which component to view by selecting the tab corresponding to the desired component. If you want similar functionality without the tab interface, you can use a card layout instead of a tabbed pane.

Example of JTabbedPane class

import java.awt.*;
import javax.swing.*;

class TabbedPaneDemo
{
JTabbedPane tp;
JPanel panel1;
JPanel panel2;
JPanel panel3;

TabbedPaneDemo()
{
JFrame f = new JFrame("Tabbed pane Application");
f.setSize(300,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
f.add(topPanel);

//Create the tab pages
createPage1();
createPage2();
createPage3();

//Create a tabbed pane
tp = new JTabbedPane();
tp.addTab("Page1",panel1);
tp.addTab("page2",panel2);
tp.addTab("page3",panel3);
topPanel.add(tp,BorderLayout.CENTER);
}

public void createPage1()
{
panel1 = new JPanel();
panel1.setLayout(null);

JLabel label1 = new JLabel("Username :");
label1.setBounds(10,15,150,20);
panel1.add(label1);


JTextField field = new JTextField();
field.setBounds(10,35,150,20);
panel1.add(field);

JLabel label2 = new JLabel("Password :");
label2.setBounds(10,60,150,20);
panel1.add(label2);


JTextField fieldpass = new JTextField();
fieldpass.setBounds(10,80,150,20);
panel1.add(fieldpass);


}

public void createPage2()
{
panel2 = new JPanel();
panel2.setLayout(new BorderLayout());

panel2.add(new JButton("North"),BorderLayout.NORTH);
panel2.add(new JButton("South"),BorderLayout.SOUTH);
panel2.add(new JButton("East"),BorderLayout.EAST);
panel2.add(new JButton("West"),BorderLayout.WEST);
panel2.add(new JButton("Center"),BorderLayout.CENTER);
}

public void createPage3()
{
panel3 = new JPanel();
panel3.setLayout(new GridLayout(3,2));

panel3.add(new JLabel("Field 1:"));
panel3.add(new TextArea());
panel3.add(new JLabel("Field 2:"));
panel3.add(new TextArea());
panel3.add(new JLabel("Field 3:"));
panel3.add(new TextArea());
}

public static void main(String[] args)
{
new TabbedPaneDemo();
}
}



JToolBar class

A JToolBar is acontainer that groups several components - usually buttons with icons - into a row or column. Often, tool bars provide easy access to functionality that is also in menus.

Example of JToolBar class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ToolBar extends JFrame
{
private JPanel topPanel;
private JButton bn ;
private JButton bo ;
private JButton bs ;
private JButton bc ;
private JButton bcu ;
private JButton bp ;

public ToolBar()
{
setTitle("Basic Toolbar Application");
setSize(400,450);
setBackground(Color.gray);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
add(topPanel);

//create a new toolbar
JToolBar t1 = new JToolBar();
topPanel.add(t1,BorderLayout.NORTH);

//Add some buttons to the toolbar
bn = addToolbarButton(t1,false,"New","new","Create a new document");
bo = addToolbarButton(t1,true,"Open","open","Open an existing document");
bs = addToolbarButton(t1,true,"Save","save","Save the document");
t1.addSeparator();
bc = addToolbarButton(t1,true,null,"copy","Copy selection to the clipboard");
bcu = addToolbarButton(t1,true,null,"cut","Cut the selection to the clipboard");
bp = addToolbarButton(t1,true,null,"paste","Pase the selection from the clipboard");

//Add a text area just to fill up the space
JTextArea ta = new JTextArea();
topPanel.add(ta,BorderLayout.CENTER);
}

//helper method to create new toolbar buttons
public JButton addToolbarButton(JToolBar toolbar, boolean bUseImage, String sButtonText, String sButton, String sToolHelp)
{
JButton b1;

if(bUseImage)
b1 = new JButton(new ImageIcon(sButton+".png"));
else
b1 = (JButton)toolbar.add(new JButton());

//Add the button to the toolbar
toolbar.add(b1);

//Add optional button text
if(sButtonText!=null)
b1.setText(sButtonText);
else 
{
//only a graphic, so make the button smaller
b1.setMargin(new Insets(0,0,0,0));
}

//Add optional tooltip help
if(sToolHelp!=null)
b1.setToolTipText(sToolHelp);

return b1;
}

public static void main(String[] args)
{
ToolBar mainFrame = new ToolBar();
mainFrame.setVisible(true);
}

}



JInternalFrame class

With the JInternalFrame class you can display a JFrame like window within another window.

Example of JInternalFrame class

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class JInternalFrameDemo extends JFrame
{
public JInternalFrameDemo()
{
MyFrame mf = new MyFrame();
Container contentPane = getContentPane();
contentPane.add(mf, BorderLayout.CENTER);
mf.display(mf);

setTitle("hungry4java Internal Frame");
setSize(300,500);
setVisible(true);
}

public static void main(String args[])
{
new JInternalFrameDemo();
}
}

class MyFrame extends JDesktopPane
{
int numFrames = 5, x =30, y = 30;

public void display(MyFrame dp)
{
for (int i=0;i<numFrames ;i++ )
{
JInternalFrame jif = new JInternalFrame("Internal Frame"+i,true,true,true,true);

jif.setBounds(x,y,250,85);
Container c1 =jif.getContentPane();
JLabel msg = new JLabel("Abhishek jha, NMIET, Bhubaneswar");
c1.add(msg);
dp.add(jif);
jif.setVisible(true);
y+=85;
}
}
}

1 comment:

  1. I liked this article very much. The content is very good. Keep posting.
    Visit us: Java Training
    Visit us: Java Course

    ReplyDelete