0% found this document useful (0 votes)
13 views

Jsin Java

Jsin Code

Uploaded by

Tamiko Chiraki
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Jsin Java

Jsin Code

Uploaded by

Tamiko Chiraki
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

JProgressBar

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

JProgressBar class declaration


Let's see the declaration for javax.swing.JProgressBar class.

1. public class JProgressBar extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

JProgressBar() It is used to create a horizontal progress bar but no string text.

JProgressBar(int It is used to create a horizontal progress bar with the specified


min, int max) minimum and maximum value.

JProgressBar(int It is used to create a progress bar with the specified orientation,


orient) it can be either Vertical or Horizontal by using
SwingConstants.VERTICAL and SwingConstants.HORIZONTAL
constants.

JProgressBar(int It is used to create a progress bar with the specified orientation,


orient, int min, minimum and maximum value.
int max)
Commonly used Methods:

Method Description

void It is used to determine whether string should be


setStringPainted(boolean displayed.
b)

void setString(String s) It is used to set value to the progress string.

void setOrientation(int It is used to set the orientation, it may be either vertical


orientation) or horizontal by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.

void setValue(int value) It is used to set the current value on the progress bar.

Java JProgressBar Example


import javax.swing.*;
public class ProgressBarExample extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
}
}
public static void main(String[] args) {
ProgressBarExample m=new ProgressBarExample();
m.setVisible(true);
m.iterate();
}
}
Output:

Java Swing | JList with examples


JList is part of Java Swing package . JList is a component that displays a set of Objects
and allows the user to select one or more items . JList inherits JComponent class. JList
is a easy way to display an array of Vectors .
Constructor for JList are :
1. JList(): creates an empty blank list
2. JList(E [ ] l) : creates an new list with the elements of the array.
3. JList(ListModel d): creates a new list with the specified List Model
4. JList(Vector l) : creates a new list with the elements of the vector

Commonly used methods are :

METHOD EXPLANATION

returns the index of selected

getSelectedIndex() item of the list

returns the selected value of

getSelectedValue() the element of the list

setSelectedIndex(int i) sets the selected index of the


METHOD EXPLANATION

list to i

sets the background Color of

setSelectionBackground(Color c) the list

Changes the foreground

setSelectionForeground(Color c) color of the list

Changes the elements of the

setListData(E [ ] l) list to the elements of l .

Changes the

setVisibleRowCount(int v) visibleRowCount property

selects the specified object

setSelectedValue(Object a, boolean s) from the list.

changes the selection to be

the set of indices specified

setSelectedIndices(int[] i) by the given array.

constructs a read-only

ListModel from a Vector

setListData(Vector l) specified.

setLayoutOrientation(int l) defines the orientation of the


METHOD EXPLANATION

list

Changes the cell width of list

to the value passed as

setFixedCellWidth(int w) parameter.

Changes the cell height of

the list to the value passed

setFixedCellHeight(int h) as parameter.

returns true if the specified

isSelectedIndex(int i) index is selected, else false.

returns the origin of the

specified item in the list’s

indexToLocation(int i) coordinate system.

returns the tooltip text to be

getToolTipText(MouseEvent e) used for the given event.

returns a list of all the

getSelectedValuesList() selected items.

returns an array of all of the

selected indices, in

getSelectedIndices() increasing order


METHOD EXPLANATION

returns the smallest selected

cell index, or -1 if the

getMinSelectionIndex() selection is empty.

returns the largest selected

cell index, or -1 if the

getMaxSelectionIndex() selection is empty.

getListSelectionListeners() returns the listeners of list

returns the largest list index

getLastVisibleIndex() that is currently visible.

returns whether or not

automatic drag handling is

getDragEnabled() enable

addListSelectionListener(ListSelectionListener adds a listSelectionlistener to

l) the list

The Following programs will illustrate the use of JLists


1. Program to create a simple JList
// java Program to create a simple JList
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame
{
//frame
static JFrame f;
//lists
static JList b;
//main class
public static void main(String[] args)
{
//create a new frame
f = new JFrame("frame");
//create a object
solve s=new solve();
//create a panel
JPanel p =new JPanel();
//create a new label
JLabel l= new JLabel("select the day of the week");
//String array to store weekdays
String week[]= { "Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday","Sunday"};
//create list
b= new JList(week);
//set a selected index
b.setSelectedIndex(2);
//add list to panel
p.add(b);
f.add(p);
//set the size of frame
f.setSize(400,400);
f.show();
}
}

Output :

2. Program to create a list and add itemListener to it (program to select your birthday
using lists) .
// (program to select your birthday using lists) .
import javax.swing.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ListSelectionListener
{
//frame
static JFrame f;
//lists
static JList b,b1,b2;
//label
static JLabel l1;
//main class
public static void main(String[] args)
{
//create a new frame
f = new JFrame("frame");
//create a object
solve s=new solve();
//create a panel
JPanel p =new JPanel();
//create a new label
JLabel l= new JLabel("select your bithday");
l1= new JLabel();
//String array to store weekdays
String month[]= { "January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October", "November", "December"};
//create a array for months and year
String date[]=new String[31],year[]=new String[31];
//add month number and year to list
for(int i=0;i<31;i++)
{
date[i]=""+(int)(i+1);
year[i]=""+(int)(2018-i);
}
//create lists
b= new JList(date);
b1= new JList(month);
b2= new JList(year);
//set a selected index
b.setSelectedIndex(2);
b1.setSelectedIndex(1);
b2.setSelectedIndex(2);
l1.setText(b.getSelectedValue()+" "+b1.getSelectedValue()
+" "+b2.getSelectedValue());
//add item listener
b.addListSelectionListener(s);
b1.addListSelectionListener(s);
b2.addListSelectionListener(s);
//add list to panel
p.add(l);
p.add(b);
p.add(b1);
p.add(b2);
p.add(l1);
f.add(p);
//set the size of frame
f.setSize(500,600);
f.show();
}
public void valueChanged(ListSelectionEvent e)
{
//set the text of the label to the selected value of lists
l1.setText(b.getSelectedValue()+" "+b1.getSelectedValue()
+" "+b2.getSelectedValue());

}
Output :

Java Swing | JSpinner


JSpinner is a part of javax.swing package . JSpinner contains a single line of input
which might be a number or a object from a ordered sequence . The user can manually
type in a legal data into the text field of the spinner . The spinner is sometimes preferred
because they do not need a drop down list . Spinners contains a upward and a
downward arrow to show the previous and the next element when it is pressed.
Constructors of JSpinner are:
1. JSpinner() : Creates an empty spinner with initial value set to zero and no
contraints
2. JSpinner( SpinnerModel model)
creates a spinner with a specified spinner model passed as argument .
Commonly used methods are :
1. SpinnerListModel(List l) : creates a spinner model with elements of list l . This
spinner model can be used to set as a model for spinner.
2. SpinnerNumberModel(int value, int max, int min, int step) : returns a spinner
model whose initial value is set to value, with minimum and maximum value, and a
definite step value.
3. setValue(Object v) : sets the value of the spinner to the object passed as
argument.
4. getValue() : returns the current value of the spinner.
5. getPreviousValue() : returns the previous value of the spinner.
6. getNextValue() : returns the next value of the spinner.

1. Program to create a simple JSpinner


// java Program to create a
// simple JSpinner
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class spinner extends JFrame {
// frame
static JFrame f;

// default constructor
spinner()
{
}

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("spinner");

// create a JSpinner
JSpinner s = new JSpinner();

// set Bounds for spinner


s.setBounds(70, 70, 50, 40);

// set layout for frame


f.setLayout(null);

// add panel to frame


f.add(s);

// set frame size


f.setSize(300, 300);

f.show();
}
}

Output :
2. Program to create a JSpinner and add ChangeListener to it ; Program to select
your date of birth using JSpinner)
// Java program to select your
// date of birth using JSpinner
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
class spinner1 extends JFrame implements ChangeListener {
// frame
static JFrame f;

// label
static JLabel l, l1;

// spinner
static JSpinner s, s1, s2;

// default constructor
spinner1()
{
}

// main class
public static void main(String[] args)
{
// create an object of the class
spinner1 sp1 = new spinner1();

// create a new frame


f = new JFrame("spinner");

// create a label
l = new JLabel("select your date of birth");
l1 = new JLabel("1 January 2000");

// create a JSpinner with a minimum, maximum and step value


s = new JSpinner();
s1 = new JSpinner(new SpinnerNumberModel(1, 1, 31, 1));

// setvalue of year
s.setValue(2000);

// store the months


String months[] = { "January", "February", "March",
"April", "May", "June", "July", "August",
"September", "October", "Novemeber", "December" };

// create a JSpinner with list values


s2 = new JSpinner(new SpinnerListModel(months));

// add change listener to spinner


s.addChangeListener(sp1);
s1.addChangeListener(sp1);
s2.addChangeListener(sp1);

// set Bounds for spinner


s.setBounds(70, 70, 50, 40);
s1.setBounds(70, 130, 50, 40);
s2.setBounds(70, 200, 90, 40);

// setbounds for label


l.setBounds(10, 10, 150, 20);
l1.setBounds(10, 300, 150, 20);

// set layout for frame


f.setLayout(null);

// add label
f.add(l);
f.add(l1);
f.add(s);
f.add(s1);
f.add(s2);

// add panel to frame


f.add(s);

// set frame size


f.setSize(400, 400);

f.show();
}

// if the state is changed


public void stateChanged(ChangeEvent e)
{
l1.setText(s1.getValue() + " " + s2.getValue() + " " + s.getValue());
}
}

Output :

Note : This program will not run in an online compiler please use an Offline IDE

Java Swing | JTable


The JTable class is a part of Java Swing Package and is generally used to display or
edit two-dimensional data that is having both rows and columns. It is similar to a
spreadsheet. This arranges data in a tabular form.
Constructors in JTable:
1. JTable(): A table is created with empty cells.
2. JTable(int rows, int cols): Creates a table of size rows * cols.
3. JTable(Object[][] data, Object []Column): A table is created with the specified
name where []Column defines the column names.
Functions in JTable:
1. addColumn(TableColumn []column) : adds a column at the end of the JTable.
2. clearSelection() : Selects all the selected rows and columns.
3. editCellAt(int row, int col) : edits the intersecting cell of the column number col
and row number row programmatically, if the given indices are valid and the
corresponding cell is editable.
4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’ for the
position row, col in the JTable.
Below is the program to illustrate the various methods of JTable:
// Packages to import
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableExamples {


// frame
JFrame f;
// Table
JTable j;

// Constructor
JTableExamples()
{
// Frame initiallization
f = new JFrame();

// Frame Title
f.setTitle("JTable Example");

// Data to be displayed in the JTable


String[][] data = {
{ "Kundan Kumar Jha", "4031", "CSE" },
{ "Anand Jha", "6014", "IT" }
};

// Column Names
String[] columnNames = { "Name", "Roll Number", "Department" };

// Initializing the JTable


j = new JTable(data, columnNames);
j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
// Frame Size
f.setSize(500, 200);
// Frame Visible = true
f.setVisible(true);
}

// Driver method
public static void main(String[] args)
{
new JTableExamples();
}
}

Output:
Java Swing | JFileChooser
JFileChooser is a part of java Swing package. The java Swing package is part of
JavaTM Foundation Classes(JFC) . JFC contains many features that help in building
graphical user interface in java . Java Swing provides components such as buttons,
panels, dialogs, etc . JFileChooser is a easy and an effective way to prompt the user to
choose a file or a directory .
In this article we will see how to use JFileChooser in java swing .
Constructors of JFileChooser are :
1. JFileChooser() – empty constructor that points to user’s default directory
// Using this process to invoke the contructor,
// JFileChooser points to user's default directory
JFileChooser j = new JFileChooser();

// Open the save dialog


j.showSaveDialog(null);
Output of the code snippet:

JFileChooser(String) – uses the given path


// Using this process to invoke the constructor,
// JFileChooser points to the mentioned path
JFileChooser j = new JFileChooser("d:");
// Open the save dialog
j.showSaveDialog(null);
Output of the code snippet:

JFileChooser(File) – uses the given File as the path


// Using this process to invoke the constructor,
// JFileChooser points to the mentioned path
// of the file passed
JFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New
folder\\"));

// Open the save dialog


j.showSaveDialog(null);
Output of the code snippet:

JFileChooser(String, FileSystemView) – uses the given path and the FileSystemView


// In this process argument passed is an object
// of File System View, and a path
JFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView());

// Open the save dialog


j.showSaveDialog(null);
Output of the code snippet:
JFileChooser(File, FileSystemView) – uses the given current directory and the
FileSystemView
Output of the code snippet:

Note : The code given above are code snippets not the full code, the code snippets given
above should be used to invoke the constructor as per the need and discretion of the
programmer, the paths mentioned above are arbitrary. User should set the path according to
their need.

Java Swing | JColorChooser Class


JColorChooser provides a pane of controls designed to allow a user to manipulate and
select a color. This class provides three levels of API:
1. A static convenience method which shows a modal color-chooser dialog and
returns the color selected by the user.
2. A static convenience method for creating a color-chooser dialog
where ActionListeners can be specified to be invoked when the user presses one
of the dialog buttons.
3. The ability to create instances of JColorChooser panes directly (within any
container). PropertyChange listeners can be added to detect when the current
“color” property changes.
Constructors of the class:
1. JColorChooser(): Creates a color chooser pane with an initial color of white.
2. JColorChooser(Color initialColor): Creates a color chooser pane with the
specified initial color.
3. JColorChooser(ColorSelectionModel model): Creates a color chooser pane
with the specified ColorSelectionModel.
Commonly Used Methods:
METHOD DESCRIPTION

Sets the current color of the

color chooser to the

setColor(Color color) specified color.

Sets the current color of the

color chooser to the

setColor(int c) specified color.

Sets the current color of the

color chooser to the

setColor(int r, int g, int b) specified RGB color.

Shows a modal color-

showDialog(Component cmp, String title, Color chooser dialog and blocks

init_Color) until the dialog is hidden.

Notification from the

UIManager that the L&F has

updateUI() changed

setChooserPanels(AbstractColorChooserPanel[] Specifies the Color Panels

panels) used to choose a color


METHOD DESCRIPTION

value.

addChooserPanel(AbstractColorChooserPanel Adds a color chooser panel

panel) to the color chooser.

Sets the L&F object that

setUI(ColorChooserUI ui) renders this component.

setSelectionModel(ColorSelectionModel Sets the model containing

newModel) the selected color.

Sets the current preview

setPreviewPanel(JComponent preview) panel.

Creating a Custom Chooser Panel: The default color chooser provides five chooser
panels:
1. Swatches: For choosing a color from a collection of swatches.
2. HSV: For choosing a color using the Hue-Saturation-Value color representation.
Prior to JDK 7, It was known as HSB, for Hue-Saturation-Brightness.
3. HSL: For choosing a color using the Hue-Saturation-Lightness color
representation.
4. RGB: For choosing a color using the Red-Green-Blue color model.
5. CMYK: For choosing a color using the process color or four color model.
Below programs illustrate the use of JColorChooser class:
1. Java program to implement JColorChooser class using ChangeListener: In
this program, we first create a label at the top of the window where some text is
shown in which we will apply color changes. Set the foreground and background
color. Set the size and type of the font. Create a Panel and set its layout. Now set
up the color chooser for setting text color. Using stateChanged() method, event is
generated for change in color of the text by using getColor() method. Now create
the GUI, create a setup window. Set the default close operation of the window.
Create and set up the content Pane and add content to the frame and display the
window.
// Java program to implement JColorChooser
// class using ChangeListener
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;

public class ColorChooserDemo extends JPanel

implements ChangeListener {

protected JColorChooser Jcc;


protected JLabel label;

public ColorChooserDemo()
{
super(new BorderLayout());

// Set up the Label at the top of the window


label = new JLabel("Welcome to GeeksforGeeks",
JLabel.CENTER);

// set the foreground color of the text


label.setForeground(Color.green);

// set background color of the field


label.setBackground(Color.WHITE);
label.setOpaque(true);

// set font type and size of the text


label.setFont(new Font("SansSerif", Font.BOLD, 30));

// set size of the label


label.setPreferredSize(new Dimension(100, 65));

// create a Panel and set its layout


JPanel bannerPanel = new JPanel(new BorderLayout());
bannerPanel.add(label, BorderLayout.CENTER);
bannerPanel.setBorder(BorderFactory.createTitledBorder("Label"));

// Set up color chooser for setting text color


Jcc = new JColorChooser(label.getForeground());
Jcc.getSelectionModel().addChangeListener(this);
Jcc.setBorder(BorderFactory.createTitledBorder(
"Choose Text Color"));

add(bannerPanel, BorderLayout.CENTER);
add(Jcc, BorderLayout.PAGE_END);
}

public void stateChanged(ChangeEvent e)


{
Color newColor = Jcc.getColor();
label.setForeground(newColor);
}

// Create the GUI and show it. For thread safety,


// this method should be invoked from the
// event-dispatching thread.
private static void createAndShowGUI()
{

// Create and set up the window.


JFrame frame = new JFrame("ColorChooserDemo");

// set default close operation of the window.


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create and set up the content pane.


JComponent newContentPane = new ColorChooserDemo();

// content panes must be opaque


newContentPane.setOpaque(true);

// add content pane to the frame


frame.setContentPane(newContentPane);

// Display the window.


frame.pack();
frame.setVisible(true);
}

// Main Method
public static void main(String[] args)
{

// Schedule a job for the event-dispatching thread:


// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run()


{

createAndShowGUI();
}
});
}
}

Java program to implement JColorChooser class using ActionListener: Create a button


and a container and set the Layout of the container. Add ActionListener() to the button and add
a button to the container. ActionListerner() has one method actionPerformed() which is
implemented as soon as the button is clicked. Choose the color and set the background color of
the container.
// Java program to implement JColorChooser
// class using ActionListener
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class ColorChooserExample extends


JFrame implements ActionListener {

// create a button
JButton b = new JButton("color");

Container c = getContentPane();

// Constructor
ColorChooserExample()
{

// set Layout
c.setLayout(new FlowLayout());

// add Listener
b.addActionListener(this);

// add button to the Container


c.add(b);
}

public void actionPerformed(ActionEvent e)


{

Color initialcolor = Color.RED;

// color chooser Dialog Box


Color color = JColorChooser.showDialog(this,
"Select a color", initialcolor);

// set Background color of the Conatiner


c.setBackground(color);
}

// Main Method
public static void main(String[] args)
{

ColorChooserExample ch = new ColorChooserExample();


ch.setSize(400, 400);
ch.setVisible(true);
ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Note: The above programs might not run in an online IDE. Please use an offline compiler.
Java Swing | JMenuBar
JMenuBar, JMenu and JMenuItems are a part of Java Swing package. JMenuBar is an
implementation of menu bar . the JMenuBar contains one or more JMenu objects, when
the JMenu objects are selected they display a popup showing one or more
JMenuItems .
JMenu basically represents a menu . It contains several JMenuItem Object . It may also
contain JMenu Objects (or submenu).
Constructors :
1. JMenuBar() : Creates a new MenuBar.
2. JMenu() : Creates a new Menu with no text.
3. JMenu(String name) : Creates a new Menu with a specified name.
4. JMenu(String name, boolean b) : Creates a new Menu with a specified name
and boolean
value specifies it as a tear-off menu or not. A tear-off menu can be opened and
dragged away from its parent menu bar or menu.
Commonly used methods:

1. dd(JMenu c) : Adds menu to the menu bar. Adds JMenu object to the Menu bar.
2. add(Component c) : Add component to the end of JMenu
3. add(Component c, int index) : Add component to the specified index of JMenu
4. add(JMenuItem menuItem) : Adds menu item to the end of the menu.
5. add(String s) : Creates a menu item with specified string and appends it to the
end of menu.
6. getItem(int index) : Returns the specified menuitem at the given index

The following programs will illustrate the use of JMenuBar


1. Program to make a MenuBar and add menu items to it
// Java program to construct
// Menu bar to add menu items
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class menu extends JFrame {
// menubar
static JMenuBar mb;

// JMenu
static JMenu x;

// Menu items
static JMenuItem m1, m2, m3;

// create a frame
static JFrame f;
public static void main()
{

// create a frame
f = new JFrame("Menu demo");

// create a menubar
mb = new JMenuBar();

// create a menu
x = new JMenu("Menu");

// create menuitems
m1 = new JMenuItem("MenuItem1");
m2 = new JMenuItem("MenuItem2");
m3 = new JMenuItem("MenuItem3");

// add menu items to menu


x.add(m1);
x.add(m2);
x.add(m3);

// add menu to menu bar


mb.add(x);

// add menubar to frame


f.setJMenuBar(mb);

// set the size of the frame


f.setSize(500, 500);
f.setVisible(true);
}
}

Output :

2. Program to add a menubar and add


menuitems, submenu items and also add ActionListener to menu items
// Java program Program to add a menubar
// and add menuitems, submenu items and also add
// ActionListener to menu items
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class menu1 extends JFrame implements ActionListener {
// menubar
static JMenuBar mb;

// JMenu
static JMenu x, x1;

// Menu items
static JMenuItem m1, m2, m3, s1, s2;

// create a frame
static JFrame f;

// a label
static JLabel l;

// main class
public static void main()
{
// create an object of the class
menu1 m = new menu1();

// create a frame
f = new JFrame("Menu demo");

// create a label
l = new JLabel("no task ");

// create a menubar
mb = new JMenuBar();

// create a menu
x = new JMenu("Menu");
x1 = new JMenu("submenu");

// create menuitems
m1 = new JMenuItem("MenuItem1");
m2 = new JMenuItem("MenuItem2");
m3 = new JMenuItem("MenuItem3");
s1 = new JMenuItem("SubMenuItem1");
s2 = new JMenuItem("SubMenuItem2");

// add ActionListener to menuItems


m1.addActionListener(m);
m2.addActionListener(m);
m3.addActionListener(m);
s1.addActionListener(m);
s2.addActionListener(m);

// add menu items to menu


x.add(m1);
x.add(m2);
x.add(m3);
x1.add(s1);
x1.add(s2);

// add submenu
x.add(x1);

// add menu to menu bar


mb.add(x);

// add menubar to frame


f.setJMenuBar(mb);

// add label
f.add(l);

// set the size of the frame


f.setSize(500, 500);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();

// set the label to the menuItem that is selected


l.setText(s + " selected");
}
}

Output:

Note : The following program might not run in an online compiler, please use an offline
IDE.

Create JTabbedPane example


With this example we shall show you how to create a JTabbedPane component in a
Java Desktop Application. This is a very important GUI component in a graphical
application, because it lets you create very easy to use interfaces and enable
the user to provide input to the application easily and all in all it’s quite an
elegant way to create a GUI.
Basically to create a JTabbedPane component in Java, one should follow these
steps:
 Create a new JFrame .
 Call frame.getContentPane().setLayout(new GridLayout(1, 1) to set up grid layout for the
frame.
 Use JTabbedPane (JTabbedPane.TOP) to get a JTabbedPane .
 Use tabbedPane.addTab to add a tab.
 Use frame.getContentPane().add(tabbedPane) to add the JTabbedPane to the frame

Let’s see the code:


package com.javacodegeeks.snippets.desktop;

import java.awt.GridLayout;
import java.awt.Label;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class CreateJTabbedPaneExample {

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Split Pane Example");

// Display the window.


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

// set grid layout for the frame


frame.getContentPane().setLayout(new GridLayout(1, 1));

JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);

tabbedPane.addTab("Tab1", makePanel("This is tab 1"));


tabbedPane.addTab("Tab2", makePanel("This is tab 2"));

frame.getContentPane().add(tabbedPane);

private static JPanel makePanel(String text) {


JPanel p = new JPanel();
p.add(new Label(text));
p.setLayout(new GridLayout(1, 1));
return p;
}

public static void main(String[] args) {

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

});
}

}
This was an example on how to create a JTabbedPane component in Java.

1. Java Add a scroll bar to a JTabbedPane


2. Java Add buttons to each tab
3. Java Add Image Icon to JTabbedPane title tab
4. Java Add JProgressBar in a JTabbedPane tab title
5. Java Add Mnemonic key to JTabbedpane
6. Java Add new tab to JTabbedPane
7. Java Add Spacing Between JTabbedPane
8. Java Add tab in JTabbedPane like google chrome
9. Java Align Vertical orientation of JTabbedPane titles when the the tab
placement is set to LEFT
10.Java Call a certain function when click on a Tab
11.Java Change background color of JFrame
12.Java Change background color of JTabbedPane
13.Java Change focus via KeyListener when switch between tabs in
JTabbedPane
14.Java Change Java JTabbedPane Inset Color
15.Java Change Tabs' position of JTabbedPane
16.Java Change Tab layout policy for JTabbedPane
17.Java Change tab name for JTabbedPane
18.Java Change the colour of the JTabbedPane header
19.Java Create Closeable JTabbedPane - alignment of the close button
20.Java Create JTabbedPane within JScrollPane
21.Java Create JTabbedPane with a label on top the same line with tab
22.Java Custom JTabbedPane UI
23.Java Disable and enable tabs in JTabbedPane
24.Java Extend JTabbedPane to always have an "Add Tab" tab
25.Java Fire stateChanged event on JTabbedPane
26.Java Gain focus on JTextArea when selecting a new JTabbedPane
27.Java Handle JTabbedPane tab changed event with ChangeListener
28.Java Handle Tab switched event for JTabbedPane
29.Java Handle the height of the tab title in JTabbedPane
30.Java JTabbedPane: change tab size when change tab title
31.Java Place text (image) in a tab in JTabbedPane with JLabel
32.Java Put JScrollPane inside JPanel inside a JTabbedPane
33.Java Remove last tab of JTabbedPane
34.Java Re fire mouse event from tab in JTabbedPane
35.Java Set a background image in JTabbedPane
36.Java Set JTabbedPane to position tab headers bottom right to left
37.Java Tell if the tab that is the active tab in JTabbedPane
38.Java Update JTabbedPane when new tab is added

JCalendar
Introduction
JCalendar is a Java date chooser bean for graphically picking a date. JCalendar is composed of
several other Java beans, a JDayChooser, a JMonthChooser and a JYearChooser. All these beans
have a locale property, provide several icons (Color 16×16, Color 32×32, Mono 16×16 and
Mono 32×32) and their own locale property editor. So they can easily be used in GUI builders.
Also part of the package is a JDateChooser, a bean composed of an IDateEditor (for direct date
editing) and a button for opening a JCalendar for selecting the date.
License
This program is free software; you can redistribute it and/or modify it under the terms of
the GNU Lesser General Public License as published by the Free Software Foundation. If you
like and use it, just let me know. If you prefer a commercial license without any of the LGPL
restrictions, please contact Kai Toedter.

Installation
The installation is very easy, just put jcalendar.jar in your class path. If you want to run the
JCalendar demos (see below) or just use the great JGoodies Looks Look and Feel, put also
jgoodies-looks-2.4.1.jar in your class path. Both are in the lib directory of this JCalendar
distribution.

Running the Demos


To run the JCalendar demo applet in your browser, you must have installed the Java Plug-in.
Click here to run the applet. If you have the distribution installed locally on your computer,
there’s several ways to run the demos. To start the JCalendar demo Windows
Vista/XP/2000/NT/98 users can just right click the jcalendar.jar and open it with “javaw” or
execute the “runJCalendarDemo.bat” batch file in the bin directory of this distribution. For all
other operating systems, just put “jcalendar.jar” and “jgoodies-looks-2.4.1.jar” (both in the lib
directory of the distribution) in your class path and start Java to execute the
com.toedter.calendar.JCalendarDemo class.

Components
The following table shows a list of used components (all Java Beans). All the screen shots use
the great Plastic 3D Look and Feel (included in JGoodies Looks by JGoodies), which is bundled
with the JCalendar bean.

Icon Icon
Component Description
16×16 32×32
JDateChooser allows you to pick a date. You could either edit
the date directly or click the image to popup a JCalendar to
choose the date. The default date editor provides coloring of
invalid dates as well as optional showing a mask. Also a
JSpinnerDateEditor is provided that uses a JSpinner to display
the date.
JCalendar allows you to choose a year, a month and a day.
Depending on the locale, the month names and the weekday
names change. The foreground of “today” is painted red.
JCalendar is composed of several other beans described below.

JYearChooser is a JSpinField (see below) that allows you


to choose a year by either typing the year in or using the
spin buttons to increase or decrease the value.

JMonthChooser is a JComboBox that allows you to


choose a month by either using the combo box or the spin
buttons. The language of the month names is defined by
the locale property.
JDayChooser lets you choose a day by clicking on the
day number. Depending on the locale, the weekday
names and the first days of the week change. The
foreground of “today” is painted red. For navigation you
can use the cursor and tab keys.

JSpinField lets you choose a numeric value. Properties


for minimum and maximum values are provided. The
value can be typed in directly or increased and decreased
by the spin buttons. If you have typed in an incorrect
value, the foreground color changes to red. Correct
values are displayed green. After pressing the enter key
the value will be set and displayed black. Since version
1.1.4 the preferred with of the value field is adjusted to
the maximum of the width of minimum or maximum.
JLocaleChooser is a JComboBox that allows you to
choose a locale. It can be used to test or set the locales
of the beans above.

Requirements
All beans use Swing components, so you need to have the Java SE installed. All beans also work with Java SE
1.4.x and 5.

You might also like