0% found this document useful (0 votes)
36 views166 pages

Java Swing Tutorial and Examples

The Java Swing tutorial covers the Java Foundation Classes (JFC) used for creating window-based applications, highlighting its platform-independent and lightweight components compared to AWT. It provides an overview of various Swing components, their methods, and examples of creating GUI applications using JButton, JLabel, and JTextField. Additionally, it discusses the differences between AWT and Swing, and includes practical examples demonstrating how to use Swing components effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views166 pages

Java Swing Tutorial and Examples

The Java Swing tutorial covers the Java Foundation Classes (JFC) used for creating window-based applications, highlighting its platform-independent and lightweight components compared to AWT. It provides an overview of various Swing components, their methods, and examples of creating GUI applications using JButton, JLabel, and JTextField. Additionally, it discusses the differences between AWT and Swing, and includes practical examples demonstrating how to use Swing components effectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Swing Tutorial

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API
and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The [Link] package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components


are platform-independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.

4) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model View Swing follows MVC.


Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

Do You Know
o How to create runnable jar file in java?
o How to display image on a button in swing?
o How to change the component color by choosing a color from ColorChooser ?
o How to display the digital watch in swing tutorial ?
o How to create a notepad in swing?
o How to create puzzle game and pic puzzle game in swing ?
o How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager sets the layout manager for the component.
m)

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.

File: [Link]

1. import [Link].*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. [Link](130,100,100, 40);//x axis, y axis, width, height
8.
9. [Link](b);//adding button in JFrame
10.
11. [Link](400,500);//400 width and 500 height
12. [Link](null);//using no layout managers
13. [Link](true);//making the frame visible
14. }
15. }

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the
java constructor.

File: [Link]

1. import [Link].*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating instance of JFrame
6.
7. JButton b=new JButton("click");//creating instance of JButton
8. [Link](130,100,100, 40);
9.
10. [Link](b);//adding button in JFrame
11.
12. [Link](400,500);//400 width and 500 height
13. [Link](null);//using no layout managers
14. [Link](true);//making the frame visible
15. }
16.
17. public static void main(String[] args) {
18. new Simple();
19. }
20. }

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that
sets the position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame
class explicitly.

File: [Link]
1. import [Link].*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. [Link](130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
download this example
What we will learn in Swing Tutorial
o JButton class
o JRadioButton class
o JTextArea class
o JComboBox class
o JTable class
o JColorChooser class
o JProgressBar class
o JSlider class
o Digital Watch
o Graphics in swing
o Displaying image
o Edit menu code for Notepad
o OpenDialog Box
o Notepad
o Puzzle Game
o Pic Puzzle Game
o Tic Tac Toe Game
o BorderLayout
o GridLayout
o FlowLayout
o CardLayout

Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.

JButton class declaration


Let's see the declaration for [Link] class.

1. public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.


void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton Example


1. import [Link].*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton("Click Here");
6. [Link](50,100,95,30);
7. [Link](b);
8. [Link](400,400);
9. [Link](null);
10. [Link](true);
11. }
12. }

Output:

Java JButton Example with ActionListener


1. import [Link].*;
2. import [Link].*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new JTextField();
7. [Link](50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. [Link](50,100,95,30);
10. [Link](new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. [Link]("Welcome to Javatpoint.");
13. }
14. });
15. [Link](b);[Link](tf);
16. [Link](400,400);
17. [Link](null);
18. [Link](true);
19. }
20. }

Output:

Example of displaying image on the button:


1. import [Link].*;
2. public class ButtonExample{
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton(new ImageIcon("D:\\[Link]"));
6. [Link](100,100,100, 40);
7. [Link](b);
8. [Link](300,400);
9. [Link](null);
10. [Link](true);
11. [Link](JFrame.EXIT_ON_CLOSE);
12. }
13. public static void main(String[] args) {
14. new ButtonExample();
15. }
16. }

Output:

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a
user cannot edit it directly. It inherits JComponent class.

JLabel class declaration


Let's see the declaration for [Link] class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an


empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.

Commonly used Methods:

Methods Description
String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the
alignment) X axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along


the X axis.

Java JLabel Example


1. import [Link].*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. [Link](50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. [Link](50,100, 100,30);
12. [Link](l1); [Link](l2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. }

Output:
Java JLabel Example with ActionListener
1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class LabelExample extends Frame implements ActionListener{
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){
7. tf=new JTextField();
8. [Link](50,50, 150,20);
9. l=new JLabel();
10. [Link](50,100, 250,20);
11. b=new JButton("Find IP");
12. [Link](50,150,95,30);
13. [Link](this);
14. add(b);add(tf);add(l);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
20. try{
21. String host=[Link]();
22. String ip=[Link](host).getHostAddress();
23. [Link]("IP of "+host+" is: "+ip);
24. }catch(Exception ex){[Link](ex);}
25. }
26. public static void main(String[] args) {
27. new LabelExample();
28. }}

Output:
Next Topic Java JTextField

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.

JTextField class declaration


Let's see the declaration for [Link] class.

1. public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive


action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.
void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that


removeActionListener(ActionListener l) it no longer receives action events from this textfield.

Java JTextField Example


1. import [Link].*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. [Link](50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. [Link](50,150, 200,30);
12. [Link](t1); [Link](t2);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. }
17. }

Output:

Java JTextField Example with ActionListener


1. import [Link].*;
2. import [Link].*;
3. public class TextFieldExample implements ActionListener{
4. JTextField tf1,tf2,tf3;
5. JButton b1,b2;
6. TextFieldExample(){
7. JFrame f= new JFrame();
8. tf1=new JTextField();
9. [Link](50,50,150,20);
10. tf2=new JTextField();
11. [Link](50,100,150,20);
12. tf3=new JTextField();
13. [Link](50,150,150,20);
14. [Link](false);
15. b1=new JButton("+");
16. [Link](50,200,50,50);
17. b2=new JButton("-");
18. [Link](120,200,50,50);
19. [Link](this);
20. [Link](this);
21. [Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
22. [Link](300,300);
23. [Link](null);
24. [Link](true);
25. }
26. public void actionPerformed(ActionEvent e) {
27. String s1=[Link]();
28. String s2=[Link]();
29. int a=[Link](s1);
30. int b=[Link](s2);
31. int c=0;
32. if([Link]()==b1){
33. c=a+b;
34. }else if([Link]()==b2){
35. c=a-b;
36. }
37. String result=[Link](c);
38. [Link](result);
39. }
40. public static void main(String[] args) {
41. new TextFieldExample();
42. } }

Output:

Next Topic Java JTextArea

Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing
of multiple line text. It inherits JTextComponent class

JTextArea class declaration


Let's see the declaration for [Link] class.

1. public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int column) Creates a text area with the specified number of rows and
columns that displays no text initially.

JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.

Commonly used Methods:


Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int position) It is used to insert the specified text on the specified position.

void append(String s) It is used to append the given text to the end of the document.

Java JTextArea Example


1. import [Link].*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to javatpoint");
7. [Link](10,30, 200,200);
8. [Link](area);
9. [Link](300,300);
10. [Link](null);
11. [Link](true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. }}

Output:
Java JTextArea Example with ActionListener
1. import [Link].*;
2. import [Link].*;
3. public class TextAreaExample implements ActionListener{
4. JLabel l1,l2;
5. JTextArea area;
6. JButton b;
7. TextAreaExample() {
8. JFrame f= new JFrame();
9. l1=new JLabel();
10. [Link](50,25,100,30);
11. l2=new JLabel();
12. [Link](160,25,100,30);
13. area=new JTextArea();
14. [Link](20,75,250,200);
15. b=new JButton("Count Words");
16. [Link](100,300,120,30);
17. [Link](this);
18. [Link](l1);[Link](l2);[Link](area);[Link](b);
19. [Link](450,450);
20. [Link](null);
21. [Link](true);
22. }
23. public void actionPerformed(ActionEvent e){
24. String text=[Link]();
25. String words[]=[Link]("\\s");
26. [Link]("Words: "+[Link]);
27. [Link]("Characters: "+[Link]());
28. }
29. public static void main(String[] args) {
30. new TextAreaExample();
31. }
32. }
Output:

Next Topic Java JPasswordField

Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry.
It allows the editing of a single line of text. It inherits JTextField class.

JPasswordField class declaration


Let's see the declaration for [Link] class.

1. public class JPasswordField extends JTextField

Commonly used Constructors:

Constructor Description

JPasswordField() Constructs a new JPasswordField, with a default document, null


starting text string, and 0 column width.

JPasswordField(int columns) Constructs a new empty JPasswordField with the specified


number of columns.

JPasswordField(String text) Constructs a new JPasswordField initialized with the specified


text.

JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.

Java JPasswordField Example


1. import [Link].*;
2. public class PasswordFieldExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Password Field Example");
5. JPasswordField value = new JPasswordField();
6. JLabel l1=new JLabel("Password:");
7. [Link](20,100, 80,30);
8. [Link](100,100,100,30);
9. [Link](value); [Link](l1);
10. [Link](300,300);
11. [Link](null);
12. [Link](true);
13. }
14. }

Output:

Java JPasswordField Example with ActionListener


1. import [Link].*;
2. import [Link].*;
3. public class PasswordFieldExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Password Field Example");
6. final JLabel label = new JLabel();
7. [Link](20,150, 200,50);
8. final JPasswordField value = new JPasswordField();
9. [Link](100,75,100,30);
10. JLabel l1=new JLabel("Username:");
11. [Link](20,20, 80,30);
12. JLabel l2=new JLabel("Password:");
13. [Link](20,75, 80,30);
14. JButton b = new JButton("Login");
15. [Link](100,120, 80,30);
16. final JTextField text = new JTextField();
17. [Link](100,20, 100,30);
18. [Link](value); [Link](l1); [Link](label); [Link](l2); [Link](b); [Link](text);
19. [Link](300,300);
20. [Link](null);
21. [Link](true);
22. [Link](new ActionListener() {
23. public void actionPerformed(ActionEvent e) {
24. String data = "Username " + [Link]();
25. data += ", Password: "
26. + new String([Link]());
27. [Link](data);
28. }
29. });
30. }
31. }

Output:

Next Topic Java JCheckBox

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or
off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on
".It inherits JToggleButton class.

JCheckBox class declaration


Let's see the declaration for [Link] class.

1. public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:


Constructor Description

JJCheckBox() Creates an initially unselected check box button with no text,


no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not it
selected) is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext associated with this


getAccessibleContext() JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox Example


1. import [Link].*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. [Link](100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. [Link](100,150, 50,50);
10. [Link](checkBox1);
11. [Link](checkBox2);
12. [Link](400,400);
13. [Link](null);
14. [Link](true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Output:

Java JCheckBox Example with ItemListener


1. import [Link].*;
2. import [Link].*;
3. public class CheckBoxExample
4. {
5. CheckBoxExample(){
6. JFrame f= new JFrame("CheckBox Example");
7. final JLabel label = new JLabel();
8. [Link]([Link]);
9. [Link](400,100);
10. JCheckBox checkbox1 = new JCheckBox("C++");
11. [Link](150,100, 50,50);
12. JCheckBox checkbox2 = new JCheckBox("Java");
13. [Link](150,150, 50,50);
14. [Link](checkbox1); [Link](checkbox2); [Link](label);
15. [Link](new ItemListener() {
16. public void itemStateChanged(ItemEvent e) {
17. [Link]("C++ Checkbox: "
18. + ([Link]()==1?"checked":"unchecked"));
19. }
20. });
21. [Link](new ItemListener() {
22. public void itemStateChanged(ItemEvent e) {
23. [Link]("Java Checkbox: "
24. + ([Link]()==1?"checked":"unchecked"));
25. }
26. });
27. [Link](400,400);
28. [Link](null);
29. [Link](true);
30. }
31. public static void main(String args[])
32. {
33. new CheckBoxExample();
34. }
35. }

Output:

Java JCheckBox Example: Food Order


1. import [Link].*;
2. import [Link].*;
3. public class CheckBoxExample extends JFrame implements ActionListener{
4. JLabel l;
5. JCheckBox cb1,cb2,cb3;
6. JButton b;
7. CheckBoxExample(){
8. l=new JLabel("Food Ordering System");
9. [Link](50,50,300,20);
10. cb1=new JCheckBox("Pizza @ 100");
11. [Link](100,100,150,20);
12. cb2=new JCheckBox("Burger @ 30");
13. [Link](100,150,150,20);
14. cb3=new JCheckBox("Tea @ 10");
15. [Link](100,200,150,20);
16. b=new JButton("Order");
17. [Link](100,250,80,30);
18. [Link](this);
19. add(l);add(cb1);add(cb2);add(cb3);add(b);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. setDefaultCloseOperation(EXIT_ON_CLOSE);
24. }
25. public void actionPerformed(ActionEvent e){
26. float amount=0;
27. String msg="";
28. if([Link]()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if([Link]()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if([Link]()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+="-----------------\n";
41. [Link](this,msg+"Total: "+amount);
42. }
43. public static void main(String[] args) {
44. new CheckBoxExample();
45. }
46. }
Output:

Next Topic Java JRadioButton

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


Let's see the declaration for [Link] class.

1. public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified text.

JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.

Commonly used Methods:

Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.


void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JRadioButton Example


1. import [Link].*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. [Link](75,50,100,30);
9. [Link](75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. [Link](r1);[Link](r2);
12. [Link](r1);[Link](r2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }

Output:
Java JRadioButton Example with ActionListener
1. import [Link].*;
2. import [Link].*;
3. class RadioButtonExample extends JFrame implements ActionListener{
4. JRadioButton rb1,rb2;
5. JButton b;
6. RadioButtonExample(){
7. rb1=new JRadioButton("Male");
8. [Link](100,50,100,30);
9. rb2=new JRadioButton("Female");
10. [Link](100,100,100,30);
11. ButtonGroup bg=new ButtonGroup();
12. [Link](rb1);[Link](rb2);
13. b=new JButton("click");
14. [Link](100,150,80,30);
15. [Link](this);
16. add(rb1);add(rb2);add(b);
17. setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public void actionPerformed(ActionEvent e){
22. if([Link]()){
23. [Link](this,"You are Male.");
24. }
25. if([Link]()){
26. [Link](this,"You are Female.");
27. }
28. }
29. public static void main(String args[]){
30. new RadioButtonExample();
31. }}

Output:

Next Topic Java JComboBox

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration


Let's see the declaration for [Link] class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataList


ener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the


specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the


items) specified Vector.

Commonly used Methods:

Methods Description
void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is


editable.

void addActionListener(ActionListener It is used to add the ActionListener.


a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


1. import [Link].*;
2. public class ComboBoxExample {
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new JComboBox(country);
8. [Link](50, 50,90,20);
9. [Link](cb);
10. [Link](null);
11. [Link](400,500);
12. [Link](true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

Output:
Java JComboBox Example with ActionListener
1. import [Link].*;
2. import [Link].*;
3. public class ComboBoxExample {
4. JFrame f;
5. ComboBoxExample(){
6. f=new JFrame("ComboBox Example");
7. final JLabel label = new JLabel();
8. [Link]([Link]);
9. [Link](400,100);
10. JButton b=new JButton("Show");
11. [Link](200,100,75,20);
12. String languages[]={"C","C++","C#","Java","PHP"};
13. final JComboBox cb=new JComboBox(languages);
14. [Link](50, 100,90,20);
15. [Link](cb); [Link](label); [Link](b);
16. [Link](null);
17. [Link](350,350);
18. [Link](true);
19. [Link](new ActionListener() {
20. public void actionPerformed(ActionEvent e) {
21. String data = "Programming language Selected: "
22. + [Link]([Link]());
23. [Link](data);
24. }
25. });
26. }
27. public static void main(String[] args) {
28. new ComboBoxExample();
29. }
30. }
Output:

Next Topic Java JTabel

Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.

JTable class declaration


Let's see the declaration for [Link] class.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example


1. import [Link].*;
2. public class TableExample {
3. JFrame f;
4. TableExample(){
5. f=new JFrame();
6. String data[][]={ {"101","Amit","670000"},
7. {"102","Jai","780000"},
8. {"101","Sachin","700000"}};
9. String column[]={"ID","NAME","SALARY"};
10. JTable jt=new JTable(data,column);
11. [Link](30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. [Link](sp);
14. [Link](300,400);
15. [Link](true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }

Output:

Java JTable Example with ListSelectionListener


1. import [Link].*;
2. import [Link].*;
3. public class TableExample {
4. public static void main(String[] a) {
5. JFrame f = new JFrame("Table Example");
6. String data[][]={ {"101","Amit","670000"},
7. {"102","Jai","780000"},
8. {"101","Sachin","700000"}};
9. String column[]={"ID","NAME","SALARY"};
10. final JTable jt=new JTable(data,column);
11. [Link](true);
12. ListSelectionModel select= [Link]();
13. [Link](ListSelectionModel.SINGLE_SELECTION);
14. [Link](new ListSelectionListener() {
15. public void valueChanged(ListSelectionEvent e) {
16. String Data = null;
17. int[] row = [Link]();
18. int[] columns = [Link]();
19. for (int i = 0; i < [Link]; i++) {
20. for (int j = 0; j < [Link]; j++) {
21. Data = (String) [Link](row[i], columns[j]);
22. }}
23. [Link]("Table element selected is: " + Data);
24. }
25. });
26. JScrollPane sp=new JScrollPane(jt);
27. [Link](sp);
28. [Link](300, 200);
29. [Link](true);
30. }
31. }

Output:

If you select an element in column NAME, name of the element will be displayed on the
console:

1. Table element selected is: Sachin

Next Topic Java JList

Java JList
The object of JList class represents a list of text items. The list of text items can be set up
so that the user can choose either one item or multiple items. It inherits JComponent
class.

JList class declaration


Let's see the declaration for [Link] class.

1. public class JList extends JComponent implements Scrollable, Accessible


Commonly used Constructors:

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

JList(ListModel<ary> Creates a JList that displays elements from the specified, non-
dataModel) null, model.

Commonly used Methods:

Methods Description

Void addListSelectionListener(ListSelectionListener It is used to add a listener to the list, to be


listener) notified each time a change to the selection
occurs.

int getSelectedIndex() It is used to return the smallest selected cell


index.

ListModel getModel() It is used to return the data model that holds


a list of items displayed by the JList
component.

void setListData(Object[] listData) It is used to create a read-only ListModel


from an array of objects.

Java JList Example


1. import [Link].*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. [Link]("Item1");
8. [Link]("Item2");
9. [Link]("Item3");
10. [Link]("Item4");
11. JList<String> list = new JList<>(l1);
12. [Link](100,100, 75,75);
13. [Link](list);
14. [Link](400,400);
15. [Link](null);
16. [Link](true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}

Output:

Java JList Example with ActionListener

1. import [Link].*;
2. import [Link].*;
3. public class ListExample
4. {
5. ListExample(){
6. JFrame f= new JFrame();
7. final JLabel label = new JLabel();
8. [Link](500,100);
9. JButton b=new JButton("Show");
10. [Link](200,150,80,30);
11. final DefaultListModel<String> l1 = new DefaultListModel<>();
12. [Link]("C");
13. [Link]("C++");
14. [Link]("Java");
15. [Link]("PHP");
16. final JList<String> list1 = new JList<>(l1);
17. [Link](100,100, 75,75);
18. DefaultListModel<String> l2 = new DefaultListModel<>();
19. [Link]("Turbo C++");
20. [Link]("Struts");
21. [Link]("Spring");
22. [Link]("YII");
23. final JList<String> list2 = new JList<>(l2);
24. [Link](100,200, 75,75);
25. [Link](list1); [Link](list2); [Link](b); [Link](label);
26. [Link](450,450);
27. [Link](null);
28. [Link](true);
29. [Link](new ActionListener() {
30. public void actionPerformed(ActionEvent e) {
31. String data = "";
32. if ([Link]() != -1) {
33. data = "Programming language Selected: " + [Link]();
34. [Link](data);
35. }
36. if([Link]() != -1){
37. data += ", FrameWork Selected: ";
38. for(Object frame :[Link]()){
39. data += frame + " ";
40. }
41. }
42. [Link](data);
43. }
44. });
45. }
46. public static void main(String args[])
47. {
48. new ListExample();
49. }}

Output:

Next Topic Java JOptionPane

Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog
box, confirm dialog box and input dialog box. These dialog boxes are used to display
information or get input from the user. The JOptionPane class inherits JComponent class.

JOptionPane class declaration


1. public class JOptionPane extends JComponent implements Accessible

Common Constructors of JOptionPane class

Constructor Description

JOptionPane() It is used to create a JOptionPane with a test message.

JOptionPane(Object message) It is used to create an instance of JOptionPane to display a


message.

JOptionPane(Object message, It is used to create an instance of JOptionPane to display a


int messageType message with specified message type and default options.

Common Methods of JOptionPane class

Methods Description

JDialog createDialog(String title) It is used to create and return a new


parentless JDialog with the specified title.
static void showMessageDialog(Component It is used to create an information-
parentComponent, Object message) message dialog titled "Message".

static void showMessageDialog(Component It is used to create a message dialog with


parentComponent, Object message, String title, int given title and messageType.
messageType)

static int showConfirmDialog(Component It is used to create a dialog with the


parentComponent, Object message) options Yes, No and Cancel; with the title,
Select an Option.

static String showInputDialog(Component It is used to show a question-message


parentComponent, Object message) dialog requesting input from the user
parented to parentComponent.

void setInputValue(Object newValue) It is used to set the input value that was
selected or input by the user.

Java JOptionPane Example: showMessageDialog()


1. import [Link].*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. [Link](f,"Hello, Welcome to Javatpoint.");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Output:

Java JOptionPane Example: showMessageDialog()


1. import [Link].*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. [Link](f,"Successfully Updated.","Alert",[Link]
NING_MESSAGE);
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Output:

Java JOptionPane Example: showInputDialog()


1. import [Link].*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=[Link](f,"Enter Name");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }

Output:
Java JOptionPane Example: showConfirmDialog()
1. import [Link].*;
2. import [Link].*;
3. public class OptionPaneExample extends WindowAdapter{
4. JFrame f;
5. OptionPaneExample(){
6. f=new JFrame();
7. [Link](this);
8. [Link](300, 300);
9. [Link](null);
10. [Link](JFrame.DO_NOTHING_ON_CLOSE);
11. [Link](true);
12. }
13. public void windowClosing(WindowEvent e) {
14. int a=[Link](f,"Are you sure?");
15. if(a==JOptionPane.YES_OPTION){
16. [Link](JFrame.EXIT_ON_CLOSE);
17. }
18. }
19. public static void main(String[] args) {
20. new OptionPaneExample();
21. }
22. }

Output:

Next Topic JScrollBar

Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.
JScrollBar class declaration
Let's see the declaration for [Link] class.

1. public class JScrollBar extends JComponent implements Adjustable, Accessible

Commonly used Constructors:

Constructor Description

JScrollBar() Creates a vertical scrollbar with the initial values.

JScrollBar(int orientation) Creates a scrollbar with the specified orientation and


the initial values.

JScrollBar(int orientation, int value, int Creates a scrollbar with the specified orientation,
extent, int min, int max) value, extent, minimum, and maximum.

Java JScrollBar Example


1. import [Link].*;
2. class ScrollBarExample
3. {
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. [Link](100,100, 50,100);
8. [Link](s);
9. [Link](400,400);
10. [Link](null);
11. [Link](true);
12. }
13. public static void main(String args[])
14. {
15. new ScrollBarExample();
16. }}
Output:

Java JScrollBar Example with AdjustmentListener


1. import [Link].*;
2. import [Link].*;
3. class ScrollBarExample
4. {
5. ScrollBarExample(){
6. JFrame f= new JFrame("Scrollbar Example");
7. final JLabel label = new JLabel();
8. [Link]([Link]);
9. [Link](400,100);
10. final JScrollBar s=new JScrollBar();
11. [Link](100,100, 50,100);
12. [Link](s); [Link](label);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. [Link](new AdjustmentListener() {
17. public void adjustmentValueChanged(AdjustmentEvent e) {
18. [Link]("Vertical Scrollbar value is:"+ [Link]());
19. }
20. });
21. }
22. public static void main(String args[])
23. {
24. new ScrollBarExample();
25. }}

Output:
Next Topic ava JMenuItem and JMenu

Java JMenuBar, JMenu and JMenuItem


The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.

The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.

JMenuBar class declaration

1. public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration

1. public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration

1. public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Java JMenuItem and JMenu Example


1. import [Link].*;
2. class MenuExample
3. {
4. JMenu menu, submenu;
5. JMenuItem i1, i2, i3, i4, i5;
6. MenuExample(){
7. JFrame f= new JFrame("Menu and MenuItem Example");
8. JMenuBar mb=new JMenuBar();
9. menu=new JMenu("Menu");
10. submenu=new JMenu("Sub Menu");
11. i1=new JMenuItem("Item 1");
12. i2=new JMenuItem("Item 2");
13. i3=new JMenuItem("Item 3");
14. i4=new JMenuItem("Item 4");
15. i5=new JMenuItem("Item 5");
16. [Link](i1); [Link](i2); [Link](i3);
17. [Link](i4); [Link](i5);
18. [Link](submenu);
19. [Link](menu);
20. [Link](mb);
21. [Link](400,400);
22. [Link](null);
23. [Link](true);
24. }
25. public static void main(String args[])
26. {
27. new MenuExample();
28. }}

Output:

Example of creating Edit menu for Notepad:


1. import [Link].*;
2. import [Link].*;
3. public class MenuExample implements ActionListener{
4. JFrame f;
5. JMenuBar mb;
6. JMenu file,edit,help;
7. JMenuItem cut,copy,paste,selectAll;
8. JTextArea ta;
9. MenuExample(){
10. f=new JFrame();
11. cut=new JMenuItem("cut");
12. copy=new JMenuItem("copy");
13. paste=new JMenuItem("paste");
14. selectAll=new JMenuItem("selectAll");
15. [Link](this);
16. [Link](this);
17. [Link](this);
18. [Link](this);
19. mb=new JMenuBar();
20. file=new JMenu("File");
21. edit=new JMenu("Edit");
22. help=new JMenu("Help");
23. [Link](cut);[Link](copy);[Link](paste);[Link](selectAll);
24. [Link](file);[Link](edit);[Link](help);
25. ta=new JTextArea();
26. [Link](5,5,360,320);
27. [Link](mb);[Link](ta);
28. [Link](mb);
29. [Link](null);
30. [Link](400,400);
31. [Link](true);
32. }
33. public void actionPerformed(ActionEvent e) {
34. if([Link]()==cut)
35. [Link]();
36. if([Link]()==paste)
37. [Link]();
38. if([Link]()==copy)
39. [Link]();
40. if([Link]()==selectAll)
41. [Link]();
42. }
43. public static void main(String[] args) {
44. new MenuExample();
45. }
46. }

Output:

Next Topic Java JPopupMenu

ava JPopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It
inherits the JComponent class.

JPopupMenu class declaration


Let's see the declaration for [Link] class.

1. public class JPopupMenu extends JComponent implements Accessible, MenuElement

Commonly used Constructors:

Constructor Description

JPopupMenu() Constructs a JPopupMenu without an "invoker".

JPopupMenu(String label) Constructs a JPopupMenu with the specified title.


Java JPopupMenu Example
1. import [Link].*;
2. import [Link].*;
3. class PopupMenuExample
4. {
5. PopupMenuExample(){
6. final JFrame f= new JFrame("PopupMenu Example");
7. final JPopupMenu popupmenu = new JPopupMenu("Edit");
8. JMenuItem cut = new JMenuItem("Cut");
9. JMenuItem copy = new JMenuItem("Copy");
10. JMenuItem paste = new JMenuItem("Paste");
11. [Link](cut); [Link](copy); [Link](paste);
12. [Link](new MouseAdapter() {
13. public void mouseClicked(MouseEvent e) {
14. [Link](f , [Link](), [Link]());
15. }
16. });
17. [Link](popupmenu);
18. [Link](300,300);
19. [Link](null);
20. [Link](true);
21. }
22. public static void main(String args[])
23. {
24. new PopupMenuExample();
25. }}

Output:

Java JPopupMenu Example with MouseListener and


ActionListener
1. import [Link].*;
2. import [Link].*;
3. class PopupMenuExample
4. {
5. PopupMenuExample(){
6. final JFrame f= new JFrame("PopupMenu Example");
7. final JLabel label = new JLabel();
8. [Link]([Link]);
9. [Link](400,100);
10. final JPopupMenu popupmenu = new JPopupMenu("Edit");
11. JMenuItem cut = new JMenuItem("Cut");
12. JMenuItem copy = new JMenuItem("Copy");
13. JMenuItem paste = new JMenuItem("Paste");
14. [Link](cut); [Link](copy); [Link](paste);
15. [Link](new MouseAdapter() {
16. public void mouseClicked(MouseEvent e) {
17. [Link](f , [Link](), [Link]());
18. }
19. });
20. [Link](new ActionListener(){
21. public void actionPerformed(ActionEvent e) {
22. [Link]("cut MenuItem clicked.");
23. }
24. });
25. [Link](new ActionListener(){
26. public void actionPerformed(ActionEvent e) {
27. [Link]("copy MenuItem clicked.");
28. }
29. });
30. [Link](new ActionListener(){
31. public void actionPerformed(ActionEvent e) {
32. [Link]("paste MenuItem clicked.");
33. }
34. });
35. [Link](label); [Link](popupmenu);
36. [Link](400,400);
37. [Link](null);
38. [Link](true);
39. }
40. public static void main(String args[])
41. {
42. new PopupMenuExample();
43. }
44. }

Output:

Next Topic Java JCheckBoxMenuItem

ava JCheckBoxMenuItem
JCheckBoxMenuItem class represents checkbox which can be included on a menu . A
CheckBoxMenuItem can have text or a graphic icon or both, associated with
it. MenuItem can be selected or deselected. MenuItems can be configured and controlled
by actions.

Nested class

Modifier Class Description


and Type

protected [Link] This class implements


class accessibility support for the
JcheckBoxMenuItem class.

Constructor

Constructor Description
JCheckBoxMenuItem() It creates an initially unselected check box menu
item with no set text or icon.

JCheckBoxMenuItem(Action a) It creates a menu item whose properties are taken


from the Action supplied.

JCheckBoxMenuItem(Icon icon) It creates an initially unselected check box menu


item with an icon.

JCheckBoxMenuItem(String text) It creates an initially unselected check box menu


item with text.

JCheckBoxMenuItem(String text, boolean It creates a check box menu item with the specified
b) text and selection state.

JCheckBoxMenuItem(String text, Icon It creates an initially unselected check box menu


icon) item with the specified text and icon.

JCheckBoxMenuItem(String text, Icon It creates a check box menu item with the specified
icon, boolean b) text, icon, and selection state.

Methods

Modifier Method Description

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this


JCheckBoxMenuItem.

Object[] getSelectedObjects() It returns an array (length 1) containing the check


box menu item label or null if the check box is not
selected.

boolean getState() It returns the selected-state of the item.

String getUIClassID() It returns the name of the L&F class that renders
this component.

protected String paramString() It returns a string representation of this


JCheckBoxMenuItem.

void setState(boolean b) It sets the selected-state of the item.


Java JCheckBoxMenuItem Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10. import [Link];
11.
12. public class JavaCheckBoxMenuItem {
13. public static void main(final String args[]) {
14. JFrame frame = new JFrame("Jmenu Example");
15. [Link](JFrame.EXIT_ON_CLOSE);
16. JMenuBar menuBar = new JMenuBar();
17. // File Menu, F - Mnemonic
18. JMenu fileMenu = new JMenu("File");
19. [Link](KeyEvent.VK_F);
20. [Link](fileMenu);
21. // File->New, N - Mnemonic
22. JMenuItem menuItem1 = new JMenuItem("Open", KeyEvent.VK_N);
23. [Link](menuItem1);
24.
25. JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem("Option_1");
26. [Link](KeyEvent.VK_C);
27. [Link](caseMenuItem);
28.
29. ActionListener aListener = new ActionListener() {
30. public void actionPerformed(ActionEvent event) {
31. AbstractButton aButton = (AbstractButton) [Link]();
32. boolean selected = [Link]().isSelected();
33. String newLabel;
34. Icon newIcon;
35. if (selected) {
36. newLabel = "Value-1";
37. } else {
38. newLabel = "Value-2";
39. }
40. [Link](newLabel);
41. }
42. };
43.
44. [Link](aListener);
45. [Link](menuBar);
46. [Link](350, 250);
47. [Link](true);
48. }
49. }

Output:

Next Topic Java JSeparator

Java JSeparator
The object of JSeparator class is used to provide a general purpose component for
implementing divider lines. It is used to draw a line to separate widgets in a Layout. It
inherits JComponent class.

JSeparator class declaration


1. public class JSeparator extends JComponent implements SwingConstants, Accessible
Commonly used Constructors of JSeparator

Constructor Description

JSeparator() Creates a new horizontal separator.

JSeparator(int Creates a new separator with the specified horizontal or vertical


orientation) orientation.

Commonly used Methods of JSeparator

Method Description

void setOrientation(int orientation) It is used to set the orientation of the separator.

int getOrientation() It is used to return the orientation of the separator.

Java JSeparator Example 1


1. import [Link].*;
2. class SeparatorExample
3. {
4. JMenu menu, submenu;
5. JMenuItem i1, i2, i3, i4, i5;
6. SeparatorExample() {
7. JFrame f= new JFrame("Separator Example");
8. JMenuBar mb=new JMenuBar();
9. menu=new JMenu("Menu");
10. i1=new JMenuItem("Item 1");
11. i2=new JMenuItem("Item 2");
12. [Link](i1);
13. [Link]();
14. [Link](i2);
15. [Link](menu);
16. [Link](mb);
17. [Link](400,400);
18. [Link](null);
19. [Link](true);
20. }
21. public static void main(String args[])
22. {
23. new SeparatorExample();
24. }}

Output:

Java JSeparator Example 2


1. import [Link].*;
2. import [Link].*;
3. public class SeparatorExample
4. {
5. public static void main(String args[]) {
6. JFrame f = new JFrame("Separator Example");
7. [Link](new GridLayout(0, 1));
8. JLabel l1 = new JLabel("Above Separator");
9. [Link](l1);
10. JSeparator sep = new JSeparator();
11. [Link](sep);
12. JLabel l2 = new JLabel("Below Separator");
13. [Link](l2);
14. [Link](400, 100);
15. [Link](true);
16. }
17. }

Output:
Next Topic Java JProgressBar

Java 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 [Link] class.

1. public class JProgressBar extends JComponent implements SwingConstants, Accessibl


e

Commonly used Constructors:

Constructor Description

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

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

JProgressBar(int It is used to create a progress bar with the specified orientation, it can
orient) be either Vertical or Horizontal by using [Link] and
[Link] constants.

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


orient, int min, int minimum and maximum value.
max)

Commonly used Methods:

Method Description
void It is used to determine whether string should be displayed.
setStringPainted(boolean 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 or


orientation) horizontal by using [Link] and
[Link] constants.

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

Java JProgressBar Example


1. import [Link].*;
2. public class ProgressBarExample extends JFrame{
3. JProgressBar jb;
4. int i=0,num=0;
5. ProgressBarExample(){
6. jb=new JProgressBar(0,2000);
7. [Link](40,40,160,30);
8. [Link](0);
9. [Link](true);
10. add(jb);
11. setSize(250,150);
12. setLayout(null);
13. }
14. public void iterate(){
15. while(i<=2000){
16. [Link](i);
17. i=i+20;
18. try{[Link](150);}catch(Exception e){}
19. }
20. }
21. public static void main(String[] args) {
22. ProgressBarExample m=new ProgressBarExample();
23. [Link](true);
24. [Link]();
25. }
26. }

Output:

Next Topic Java JTree

Java JTree
The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes
in the tree. It inherits JComponent class.

JTree class declaration


Let's see the declaration for [Link] class.

1. public class JTree extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

JTree(Object[] Creates a JTree with every element of the specified array as the child of a
value) new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the
root) root node.

Java JTree Example


1. import [Link].*;
2. import [Link];
3. public class TreeExample {
4. JFrame f;
5. TreeExample(){
6. f=new JFrame();
7. DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
8. DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
9. DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
10. [Link](color);
11. [Link](font);
12. DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
13. DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
14. DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
15. DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
16. [Link](red); [Link](blue); [Link](black); [Link](green);
17. JTree jt=new JTree(style);
18. [Link](jt);
19. [Link](200,200);
20. [Link](true);
21. }
22. public static void main(String[] args) {
23. new TreeExample();
24. }}

Output:

Next Topic Java JColorChooser

Java JColorChooser
The JColorChooser class is used to create a color chooser dialog box so that user can
select any color. It inherits JComponent class.
JColorChooser class declaration
Let's see the declaration for [Link] class.

1. public class JColorChooser extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description

JColorChooser() It is used to create a color chooser panel with white color initially.

JColorChooser(color It is used to create a color chooser panel with the specified color
initialcolor) initially.

Commonly used Methods:

Method Description

void addChooserPanel(AbstractColorChooserPanel It is used to add a color chooser


panel) panel to the color chooser.

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

Java JColorChooser Example


1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class ColorChooserExample extends JFrame implements ActionListener {
5. JButton b;
6. Container c;
7. ColorChooserExample(){
8. c=getContentPane();
9. [Link](new FlowLayout());
10. b=new JButton("color");
11. [Link](this);
12. [Link](b);
13. }
14. public void actionPerformed(ActionEvent e) {
15. Color initialcolor=[Link];
16. Color color=[Link](this,"Select a color",initialcolor);
17. [Link](color);
18. }
19.
20. public static void main(String[] args) {
21. ColorChooserExample ch=new ColorChooserExample();
22. [Link](400,400);
23. [Link](true);
24. [Link](EXIT_ON_CLOSE);
25. }
26. }

Output:

Java JColorChooser Example with ActionListener


1. import [Link].*;
2. import [Link].*;
3. import [Link].*;

public class ColorChooserEx Java JTabbedPane


The JTabbedPane class is used to switch between a group of components by clicking on
a tab with a given title or icon. It inherits JComponent class.

JTabbedPane class declaration


Let's see the declaration for [Link] class.
1. public class JTabbedPane extends JComponent implements Serializable, Accessible, S
wingConstants

Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab


placement of [Link].

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab


placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab


tabLayoutPolicy) placement and tab layout policy.

Java JTabbedPane Example


1. import [Link].*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
7. JPanel p1=new JPanel();
8. [Link](ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. [Link](50,50,200,200);
13. [Link]("main",p1);
14. [Link]("visit",p2);
15. [Link]("help",p3);
16. [Link](tp);
17. [Link](400,400);
18. [Link](null);
19. [Link](true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}

Output:

Next Topic Java JSlider

4. ample extends JFrame implements ActionListener{


5. JFrame f;
6. JButton b;
7. JTextArea ta;
8. ColorChooserExample(){
9. f=new JFrame("Color Chooser Example.");
10. b=new JButton("Pad Color");
11. [Link](200,250,100,30);
12. ta=new JTextArea();
13. [Link](10,10,300,200);
14. [Link](this);
15. [Link](b);[Link](ta);
16. [Link](null);
17. [Link](400,400);
18. [Link](true);
19. }
20. public void actionPerformed(ActionEvent e){
21. Color c=[Link](this,"Choose",[Link]);
22. [Link](c);
23. }
24. public static void main(String[] args) {
25. new ColorChooserExample();
26. }
27. }

Output:

Next Topic Java JTabbedPane

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

JColorChooser class declaration


Let's see the declaration for [Link] class.

1. public class JColorChooser extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description

JColorChooser() It is used to create a color chooser panel with white color initially.

JColorChooser(color It is used to create a color chooser panel with the specified color
initialcolor) initially.

Commonly used Methods:

Method Description

void addChooserPanel(AbstractColorChooserPanel It is used to add a color chooser


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

Java JColorChooser Example


1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class ColorChooserExample extends JFrame implements ActionListener {
5. JButton b;
6. Container c;
7. ColorChooserExample(){
8. c=getContentPane();
9. [Link](new FlowLayout());
10. b=new JButton("color");
11. [Link](this);
12. [Link](b);
13. }
14. public void actionPerformed(ActionEvent e) {
15. Color initialcolor=[Link];
16. Color color=[Link](this,"Select a color",initialcolor);
17. [Link](color);
18. }
19.
20. public static void main(String[] args) {
21. ColorChooserExample ch=new ColorChooserExample();
22. [Link](400,400);
23. [Link](true);
24. [Link](EXIT_ON_CLOSE);
25. }
26. }

Output:
Java JColorChooser Example with ActionListener
1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class ColorChooserExample extends JFrame implements ActionListener{
5. JFrame f;
6. JButton b;
7. JTextArea ta;
8. ColorChooserExample(){
9. f=new JFrame("Color Chooser Example.");
10. b=new JButton("Pad Color");
11. [Link](200,250,100,30);
12. ta=new JTextArea();
13. [Link](10,10,300,200);
14. [Link](this);
15. [Link](b);[Link](ta);
16. [Link](null);
17. [Link](400,400);
18. [Link](true);
19. }
20. public void actionPerformed(ActionEvent e){
21. Color c=[Link](this,"Choose",[Link]);
22. [Link](c);
23. }
24. public static void main(String[] args) {
25. new ColorChooserExample();
26. }
27. }

Output:
Next Topic Java JTabbedPane

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

Commonly used Constructors of JSlider class

Constructor Description

JSlider() creates a slider with the initial value of 50 and range of 0 to 100.

JSlider(int orientation) creates a slider with the specified orientation set by either
[Link] or [Link] with the range 0 to 100
and initial value 50.

JSlider(int min, int max) creates a horizontal slider using the given min and max.

JSlider(int min, int max, int creates a horizontal slider using the given min, max and value.
value)

JSlider(int orientation, int creates a slider using the given orientation, min, max and value.
min, int max, int value)

Commonly used Methods of JSlider class

Method Description

public void setMinorTickSpacing(int n) is used to set the minor tick spacing to the slider.

public void setMajorTickSpacing(int n) is used to set the major tick spacing to the slider.

public void setPaintTicks(boolean b) is used to determine whether tick marks are painted.

public void setPaintLabels(boolean b) is used to determine whether labels are painted.


public void setPaintTracks(boolean b) is used to determine whether track is painted.

Java JSlider Example

1. import [Link].*;
2. public class SliderExample1 extends JFrame{
3. public SliderExample1() {
4. JSlider slider = new JSlider([Link], 0, 50, 25);
5. JPanel panel=new JPanel();
6. [Link](slider);
7. add(panel);
8. }
9.
10. public static void main(String s[]) {
11. SliderExample1 frame=new SliderExample1();
12. [Link]();
13. [Link](true);
14. }
15. }

Output:

Java JSlider Example: painting ticks

1. import [Link].*;
2. public class SliderExample extends JFrame{
3. public SliderExample() {
4. JSlider slider = new JSlider([Link], 0, 50, 25);
5. [Link](2);
6. [Link](10);
7. [Link](true);
8. [Link](true);
9.
10. JPanel panel=new JPanel();
11. [Link](slider);
12. add(panel);
13. }
14. public static void main(String s[]) {
15. SliderExample frame=new SliderExample();
16. [Link]();
17. [Link](true);
18. }
19. }

Output:

Next Topic Java JSpinner

Java JSpinner
The object of JSpinner class is a single line input field that allows the user to select a
number or an object value from an ordered sequence.

JSpinner class declaration


Let's see the declaration for [Link] class.

1. public class JSpinner extends JComponent implements Accessible

Commonly used Contructors:

Constructor Description

JSpinner() It is used to construct a spinner with an Integer


SpinnerNumberModel with initial value 0 and no minimum or
maximum limits.
JSpinner(SpinnerModel It is used to construct a spinner for a given model.
model)

Commonly used Methods:

Method Description

void addChangeListener(ChangeListener It is used to add a listener to the list that is notified


listener) each time a change to the model occurs.

Object getValue() It is used to return the current value of the model.

Java JSpinner Example


1. import [Link].*;
2. public class SpinnerExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Spinner Example");
5. SpinnerModel value =
6. new SpinnerNumberModel(5, //initial value
7. 0, //minimum value
8. 10, //maximum value
9. 1); //step
10. JSpinner spinner = new JSpinner(value);
11. [Link](100,100,50,30);
12. [Link](spinner);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. }

Output:
Java JSpinner Example with ChangeListener
imp
1. ort [Link].*;
2. import [Link].*;
3. public class SpinnerExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Spinner Example");
6. final JLabel label = new JLabel();
7. [Link]([Link]);
8. [Link](250,100);
9. SpinnerModel value =
10. new SpinnerNumberModel(5, //initial value
11. 0, //minimum value
12. 10, //maximum value
13. 1); //step
14. JSpinner spinner = new JSpinner(value);
15. [Link](100,100,50,30);
16. [Link](spinner); [Link](label);
17. [Link](300,300);
18. [Link](null);
19. [Link](true);
20. [Link](new ChangeListener() {
21. public void stateChanged(ChangeEvent e) {
22. [Link]("Value : " + ((JSpinner)[Link]()).getValue());
23. }
24. });
25. }
26. }

Output:
Next Topic Java JDialog

ava JDialog
The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

JDialog class declaration


Let's see the declaration for [Link] class.

1. public class JDialog extends Dialog implements WindowConstants, Accessible, RootPa


neContainer

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a title and


without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with specified Frame


as its owner and an empty title.

JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.

Java JDialog Example


1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class DialogExample {
5. private static JDialog d;
6. DialogExample() {
7. JFrame f= new JFrame();
8. d = new JDialog(f , "Dialog Example", true);
9. [Link]( new FlowLayout() );
10. JButton b = new JButton ("OK");
11. [Link] ( new ActionListener()
12. {
13. public void actionPerformed( ActionEvent e )
14. {
15. [Link](false);
16. }
17. });
18. [Link]( new JLabel ("Click button to continue."));
19. [Link](b);
20. [Link](300,300);
21. [Link](true);
22. }
23. public static void main(String args[])
24. {
25. new DialogExample();
26. }
27. }

Output:

Next Topic Java JPanel

Java JPanel
The JPanel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the JComponents class.

It doesn't have title bar.


JPanel class declaration
1. public class JPanel extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the


isDoubleBuffered) specified buffering strategy.

JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.

Java JPanel Example


1. import [Link].*;
2. import [Link].*;
3. public class PanelExample {
4. PanelExample()
5. {
6. JFrame f= new JFrame("Panel Example");
7. JPanel panel=new JPanel();
8. [Link](40,80,200,200);
9. [Link]([Link]);
10. JButton b1=new JButton("Button 1");
11. [Link](50,100,80,30);
12. [Link]([Link]);
13. JButton b2=new JButton("Button 2");
14. [Link](100,100,80,30);
15. [Link]([Link]);
16. [Link](b1); [Link](b2);
17. [Link](panel);
18. [Link](400,400);
19. [Link](null);
20. [Link](true);
21. }
22. public static void main(String args[])
23. {
24. new PanelExample();
25. }
26. }

Output:

Next Topic Java JFileChooser

Java JFileChooser
The object of JFileChooser class represents a dialog window from which the user can select
file. It inherits JComponent class.

JFileChooser class declaration


Let's see the declaration for [Link] class.

1. public class JFileChooser extends JComponent implements Accessible

Commonly used Constructors:

Constructor Description

JFileChooser() Constructs a JFileChooser pointing to the user's default


directory.
JFileChooser(File currentDirectory) Constructs a JFileChooser using the given File as the
path.

JFileChooser(String Constructs a JFileChooser using the given path.


currentDirectoryPath)

Java JFileChooser Example


1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class FileChooserExample extends JFrame implements ActionListener{
5. JMenuBar mb;
6. JMenu file;
7. JMenuItem open;
8. JTextArea ta;
9. FileChooserExample(){
10. open=new JMenuItem("Open File");
11. [Link](this);
12. file=new JMenu("File");
13. [Link](open);
14. mb=new JMenuBar();
15. [Link](0,0,800,20);
16. [Link](file);
17. ta=new JTextArea(800,800);
18. [Link](0,20,800,800);
19. add(mb);
20. add(ta);
21. }
22. public void actionPerformed(ActionEvent e) {
23. if([Link]()==open){
24. JFileChooser fc=new JFileChooser();
25. int i=[Link](this);
26. if(i==JFileChooser.APPROVE_OPTION){
27. File f=[Link]();
28. String filepath=[Link]();
29. try{
30. BufferedReader br=new BufferedReader(new FileReader(filepath));
31. String s1="",s2="";
32. while((s1=[Link]())!=null){
33. s2+=s1+"\n";
34. }
35. [Link](s2);
36. [Link]();
37. }catch (Exception ex) {[Link](); }
38. }
39. }
40. }
41. public static void main(String[] args) {
42. FileChooserExample om=new FileChooserExample();
43. [Link](500,500);
44. [Link](null);
45. [Link](true);
46. [Link](EXIT_ON_CLOSE);
47. }
48. }

Output:

Next Topic Java JToggleButton

Java JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.

Nested Classes
Modifier Class Description
and Type

protected [Link] This class implements accessibility


class support for the JToggleButton class.

static class [Link] The ToggleButton model

Constructors

Constructor Description

JToggleButton() It creates an initially unselected toggle button without


setting the text or image.

JToggleButton(Action a) It creates a toggle button where properties are taken


from the Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button with the


specified image but no text.

JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the specified


text.

JToggleButton(String text, boolean It creates a toggle button with the specified text and
selected) selection state.

JToggleButton(String text, Icon icon) It creates a toggle button that has the specified text and
image, and that is initially unselected.

JToggleButton(String text, Icon icon, It creates a toggle button with the specified text, image,
boolean selected) and selection state.

Methods
Modifier and Method Description
Type

AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this


JToggleButton.

String getUIClassID() It returns a string that specifies the name of the


l&f class that renders this component.

protected String paramString() It returns a string representation of this


JToggleButton.

void updateUI() It resets the UI property to a value from the


current look and feel.

JToggleButton Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. [Link](this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if ([Link]())
30. [Link]("OFF");
31. else
32. [Link]("ON");
33. }
34. }

Output

Next Topic Java JToolBar

Java JToolBar
JToolBar container allows us to group other components, usually buttons with icons in a
row or column. JToolBar provides a component which is useful for displaying commonly
used actions or controls.

Nested Classes

Modifier and Class Description


Type

protected class [Link] This class implements accessibility support for


the JToolBar class.

static class [Link] A toolbar-specific separator.


Constructors

Constructor Description

JToolBar() It creates a new tool bar; orientation defaults to


HORIZONTAL.

JToolBar(int orientation) It creates a new tool bar with the specified orientation.

JToolBar(String name) It creates a new tool bar with the specified name.

JToolBar(String name, int It creates a new tool bar with a specified name and
orientation) orientation.

Useful Methods

Modifier and Type Method Description

JButton add(Action a) It adds a new JButton which


dispatches the action.

protected void addImpl(Component comp, Object If a JButton is being added, it


constraints, int index) is initially set to be disabled.

void addSeparator() It appends a separator of


default size to the end of the
tool bar.

protected createActionChangeListener(JButton It returns a properly


PropertyChangeListener b) configured
PropertyChangeListener
which updates the control as
changes to the Action occur,
or null if the default property
change listener for the control
is desired.

protected JButton createActionComponent(Action a) Factory method which creates


the JButton for Actions added
to the JToolBar.
ToolBarUI getUI() It returns the tool bar's current
UI.

void setUI(ToolBarUI ui) It sets the L&F object that


renders this component.

void setOrientation(int o) It sets the orientation of the


tool bar.

Java JToolBar Example


1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class JToolBarExample {
11. public static void main(final String args[]) {
12. JFrame myframe = new JFrame("JToolBar Example");
13. [Link](JFrame.EXIT_ON_CLOSE);
14. JToolBar toolbar = new JToolBar();
15. [Link](true);
16. JButton button = new JButton("File");
17. [Link](button);
18. [Link]();
19. [Link](new JButton("Edit"));
20. [Link](new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-3", "Opt-4" }));
21. Container contentPane = [Link]();
22. [Link](toolbar, [Link]);
23. JTextArea textArea = new JTextArea();
24. JScrollPane mypane = new JScrollPane(textArea);
25. [Link](mypane, [Link]);
26. [Link](450, 250);
27. [Link](true);
28. }
29. }

Output:

Next Topic Java JViewPort

Java JToolBar
JToolBar container allows us to group other components, usually buttons with icons in a
row or column. JToolBar provides a component which is useful for displaying commonly
used actions or controls.

Nested Classes

Modifier and Class Description


Type

protected class [Link] This class implements accessibility support for


the JToolBar class.

static class [Link] A toolbar-specific separator.

Constructors

Constructor Description

JToolBar() It creates a new tool bar; orientation defaults to


HORIZONTAL.

JToolBar(int orientation) It creates a new tool bar with the specified orientation.
JToolBar(String name) It creates a new tool bar with the specified name.

JToolBar(String name, int It creates a new tool bar with a specified name and
orientation) orientation.

Useful Methods

Modifier and Type Method Description

JButton add(Action a) It adds a new JButton which


dispatches the action.

protected void addImpl(Component comp, Object If a JButton is being added, it


constraints, int index) is initially set to be disabled.

void addSeparator() It appends a separator of


default size to the end of the
tool bar.

protected createActionChangeListener(JButton It returns a properly


PropertyChangeListener b) configured
PropertyChangeListener
which updates the control as
changes to the Action occur,
or null if the default property
change listener for the control
is desired.

protected JButton createActionComponent(Action a) Factory method which creates


the JButton for Actions added
to the JToolBar.

ToolBarUI getUI() It returns the tool bar's current


UI.

void setUI(ToolBarUI ui) It sets the L&F object that


renders this component.

void setOrientation(int o) It sets the orientation of the


tool bar.
Java JToolBar Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class JToolBarExample {
11. public static void main(final String args[]) {
12. JFrame myframe = new JFrame("JToolBar Example");
13. [Link](JFrame.EXIT_ON_CLOSE);
14. JToolBar toolbar = new JToolBar();
15. [Link](true);
16. JButton button = new JButton("File");
17. [Link](button);
18. [Link]();
19. [Link](new JButton("Edit"));
20. [Link](new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-3", "Opt-4" }));
21. Container contentPane = [Link]();
22. [Link](toolbar, [Link]);
23. JTextArea textArea = new JTextArea();
24. JScrollPane mypane = new JScrollPane(textArea);
25. [Link](mypane, [Link]);
26. [Link](450, 250);
27. [Link](true);
28. }
29. }

Output:
Next Topic Java JViewPort

Java JFrame
The [Link] class is a type of container which inherits the [Link] class.
JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Nested Class

Modifier and Class Description


Type

protected class [Link] This class implements accessibility support for


the JFrame class.

Fields

Modifier and Type Field Description

protected accessibleContext The accessible context property.


AccessibleContext

static int EXIT_ON_CLOSE The exit application default window close


operation.

protected JRootPane rootPane The JRootPane instance that manages the


contentPane and optional menuBar for this
frame, as well as the glassPane.

protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be
forwarded to the contentPane.

Constructors
Constructor Description

JFrame() It constructs a new frame that is initially invisible.

JFrame(GraphicsConfiguration gc) It creates a Frame in the specified GraphicsConfiguration


of a screen device and a blank title.

JFrame(String title) It creates a new, initially invisible Frame with the specified
title.

JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen device.

Useful Methods

Modifier and Method Description


Type

protected void addImpl(Component comp, Object Adds the specified child


constraints, int index) Component.

protected createRootPane() Called by the constructor


JRootPane methods to create the default
rootPane.

protected void frameInit() Called by the constructors to


init the JFrame properly.

void setContentPane(Containe contentPane) It sets the contentPane


property

static void setDefaultLookAndFeelDecorated(boolean Provides a hint as to whether


defaultLookAndFeelDecorated) or not newly created JFrames
should have their Window
decorations (such as borders,
widgets to close the window,
title...) provided by the current
look and feel.
void setIconImage(Image image) It sets the image to be
displayed as the icon for this
window.

void setJMenuBar(JMenuBar menubar) It sets the menubar for this


frame.

void setLayeredPane(JLayeredPane layeredPane) It sets the layeredPane


property.

JRootPane getRootPane() It returns the rootPane object


for this frame.

TransferHandler getTransferHandler() It gets the transferHandler


property.

JFrame Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class JFrameExample {
7. public static void main(String s[]) {
8. JFrame frame = new JFrame("JFrame Example");
9. JPanel panel = new JPanel();
10. [Link](new FlowLayout());
11. JLabel label = new JLabel("JFrame By Example");
12. JButton button = new JButton();
13. [Link]("Button");
14. [Link](label);
15. [Link](button);
16. [Link](panel);
17. [Link](200, 300);
18. [Link](null);
19. [Link](JFrame.EXIT_ON_CLOSE);
20. [Link](true);
21. }
22. }

Output

Next Topic Java JComponent

Java JComponent
The JComponent class is the base class of all Swing components except top-level
containers. Swing components whose names begin with "J" are descendants of the
JComponent class. For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and
JDialog don't inherit JComponent class because they are the child of top-level containers.

The JComponent class extends the Container class which itself extends Component. The
Container class has support for adding components to the container.

Fields

Modifier and Type Field Description

protected accessibleContext The AccessibleConte


AccessibleContext associated with th
JComponent.

protectedEventListenerList listenerList A list of event listene


for this component.

static String TOOL_TIP_TEXT_KEY The comment to displa


when the cursor is ove
the component, als
known as a "value tip
"flyover help", o
"flyover label"
protected ComponentUI ui The look and fe
delegate for th
component.

static int UNDEFINED_CONDITION It is a constant used b


some of the APIs t
mean that no conditio
is defined.

static int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT It is a constant used fo


registerKeyboardActio
that means that th
command should b
invoked when th
receiving component
an ancestor of th
focused component o
is itself the focuse
component.

static int WHEN_FOCUSED It is a constant used fo


registerKeyboardActio
that means that th
command should b
invoked when th
component has th
focus.

static int WHEN_IN_FOCUSED_WINDOW Constant used fo


registerKeyboardActio
that means that th
command should b
invoked when th
receiving component
in the window that ha
the focus or is itself th
focused component.

Constructor
Constructor Description

JComponent() Default JComponent constructor.

Useful Methods

Modifier and Method Description


Type

void setActionMap(ActionMap am) It sets the ActionMap to am.

void setBackground(Color bg) It sets the background color of this


component.

void setFont(Font font) It sets the font for this component.

void setMaximumSize(Dimension It sets the maximum size of this component


maximumSize) to a constant value.

void setMinimumSize(Dimension It sets the minimum size of this component


minimumSize) to a constant value.

protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this
component.

void setVisible(boolean aFlag) It makes the component visible or invisible.

void setForeground(Color fg) It sets the foreground color of this


component.

String getToolTipText(MouseEvent It returns the string to be used as the tooltip


event) for event.

Container getTopLevelAncestor() It returns the top-level ancestor of this


component (either the containing Window
or Applet), or null if this component has not
been added to any container.

TransferHandler getTransferHandler() It gets the transferHandler property.


Java JComponent Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. class MyJComponent extends JComponent {
6. public void paint(Graphics g) {
7. [Link]([Link]);
8. [Link](30, 30, 100, 100);
9. }
10. }
11. public class JComponentExample {
12. public static void main(String[] arguments) {
13. MyJComponent com = new MyJComponent();
14. // create a basic JFrame
15. [Link](true);
16. JFrame frame = new JFrame("JComponent Example");
17. [Link](300,200);
18. [Link](JFrame.EXIT_ON_CLOSE);
19. // add the JComponent to main frame
20. [Link](com);
21. [Link](true);
22. }
23. }

Output:

Next Topic Java JLayeredPane

Java JDesktopPane
The JDesktopPane class, can be used to create "multi-document" applications. A multi-
document application can have many windows included in it. We do it by making the
contentPane in the main window as an instance of the JDesktopPane class or a subclass.
Internal windows add instances of JInternalFrame to the JdesktopPane instance. The
internal windows are the instances of JInternalFrame or its subclasses.

Fields

Modifier and Field Description


Type

static int LIVE_DRAG_MODE It indicates that the entire contents of the item being
dragged should appear inside the desktop pane.

static int OUTLINE_DRAG_MODE It indicates that an outline only of the item being
dragged should appear inside the desktop pane.

Constructor

Constructor Description

JDesktopPane() Creates a new JDesktopPane.

Java JDesktopPane Example


1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. public class JDPaneDemo extends JFrame
8. {
9. public JDPaneDemo()
10. {
11. CustomDesktopPane desktopPane = new CustomDesktopPane();
12. Container contentPane = getContentPane();
13. [Link](desktopPane, [Link]);
14. [Link](desktopPane);
15.
16. setTitle("JDesktopPane Example");
17. setSize(300,350);
18. setVisible(true);
19. }
20. public static void main(String args[])
21. {
22. new JDPaneDemo();
23. }
24. }
25. class CustomDesktopPane extends JDesktopPane
26. {
27. int numFrames = 3, x = 30, y = 30;
28. public void display(CustomDesktopPane dp)
29. {
30. for(int i = 0; i < numFrames ; ++i )
31. {
32. JInternalFrame jframe = new JInternalFrame("Internal Frame " + i , true, true, true, t
rue);
33.
34. [Link](x, y, 250, 85);
35. Container c1 = [Link]( ) ;
36. [Link](new JLabel("I love my country"));
37. [Link]( jframe );
38. [Link](true);
39. y += 85;
40. }
41. }
42. }

Output:
Next Topic Java JEditorPane

Java JEditorPane
JEditorPane class is used to create a simple text editor window. This class has
setContentType() and setText() methods.

setContentType("text/plain"): This method is used to set the content type to be plain


text.

setText(text): This method is used to set the initial text content.

Nested Classes

Modifier Class Description


and
Type

protected [Link] This class implements accessibility


class the JEditorPane class.

protected [Link] This class provides sup


class AccessibleHypertext, and is used
where the EditorKit installed in this
is an instance of HTMLEditorKit.

protected [Link] What's returned


class [Link]

Fields

Modifier Field Description


and Type

static String HONOR_DISPLAY_PROPERTIES Key for a client property used to indicate


whether the default font and foreground color
from the component are used if a font or
foreground color is not specified in the styled
text.

static String W3C_LENGTH_UNITS Key for a client property used to indicate


whether w3c compliant length units are used for
html rendering.

Constructors

Constructor Description

JEditorPane() It creates a new JEditorPane.

JEditorPane(String url) It creates a JEditorPane based on a string containing a URL


specification.

JEditorPane(String type, String It creates a JEditorPane that has been initialized to the given
text) text.

JEditorPane(URL initialPage) It creates a JEditorPane based on a specified URL for input.

Useful Methods

Modifier Method Description


and Type

void addHyperlinkListener(HyperlinkListener Adds a hyperlink listener for


listener) notification of any changes, for
example when a link is selected and
entered.

protected createDefaultEditorKit() It creates the default editor kit


EditorKit (PlainEditorKit) for when the
component is first created.

void setText(String t) It sets the text of this TextComponent


to the specified content, which is
expected to be in the format of the
content type of this editor.
void setContentType(String type) It sets the type of content that this
editor handles.

void setPage(URL page) It sets the current URL being displayed.

void read(InputStream in, Object desc) This method initializes from a stream.

void scrollToReference(String reference) It scrolls the view to the given


reference location (that is, the value
returned by the [Link] method for
the URL being displayed).

void setText(String t) It sets the text of this TextComponent


to the specified content, which is
expected to be in the format of the
content type of this editor.

String getText() It returns the text contained in this


TextComponent in terms of the
content type of this editor.

void read(InputStream in, Object desc) This method initializes from a stream.

JEditorPane Example
1. import [Link];
2. import [Link];
3.
4. public class JEditorPaneExample {
5. JFrame myFrame = null;
6.
7. public static void main(String[] a) {
8. (new JEditorPaneExample()).test();
9. }
10.
11. private void test() {
12. myFrame = new JFrame("JEditorPane Test");
13. [Link](JFrame.EXIT_ON_CLOSE);
14. [Link](400, 200);
15. JEditorPane myPane = new JEditorPane();
16. [Link]("text/plain");
17. [Link]("Sleeping is necessary for a healthy body."
18. + " But sleeping in unnecessary times may spoil our health, wealth and studies
."
19. + " Doctors advise that the sleeping at improper timings may lead for obesity
during the students days.");
20. [Link](myPane);
21. [Link](true);
22. }
23. }

Output:

JEditorPane Example: using HTML


1. import [Link];
2. import [Link];
3.
4. public class JEditorPaneExample {
5. JFrame myFrame = null;
6.
7. public static void main(String[] a) {
8. (new JEditorPaneExample()).test();
9. }
10.
11. private void test() {
12. myFrame = new JFrame("JEditorPane Test");
13. [Link](JFrame.EXIT_ON_CLOSE);
14. [Link](400, 200);
15. JEditorPane myPane = new JEditorPane();
16. [Link]("text/html");
17. [Link]("<h1>Sleeping</h1><p>Sleeping is necessary for a healthy body.
"
18. + " But sleeping in unnecessary times may spoil our health, wealth and studies
."
19. + " Doctors advise that the sleeping at improper timings may lead for obesity
during the students days.</p>");
20. [Link](myPane);
21. [Link](true);
22. }
23. }

Output:

Next Topic Java JScrollPane

Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.

Constructors

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when present,


sets the scroll pane's client. The two int parameters, when present,
JScrollPane(Component) set the vertical and horizontal scroll bar policies (respectively).

JScrollPane(int, int)

JScrollPane(Component,
int, int)

Useful Methods
Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must
Component getCorner(String) be one of the following constants defined in
ScrollPaneConstants: UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

JScrollPane Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5.
6. public class JScrollPaneExample {
7. private static final long serialVersionUID = 1L;
8.
9. private static void createAndShowGUI() {
10.
11. // Create and set up the window.
12. final JFrame frame = new JFrame("Scroll Pane Example");
13.
14. // Display the window.
15. [Link](500, 500);
16. [Link](true);
17. [Link](JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. [Link]().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. [Link](JScrollPane.HORIZONTAL_SCROLLB
AR_ALWAYS);
26. [Link](JScrollPane.VERTICAL_SCROLLBAR_AL
WAYS);
27.
28. [Link]().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. [Link](new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }

Output:

Next Topic Java JSplitPane


Java JSplitPane
JSplitPane is used to divide two components. The two components are divided based on
the look and feel implementation, and they can be resized by the user. If the minimum
size of the two components is greater than the size of the split pane, the divider will not
allow you to resize it.

The two components in a split pane can be aligned left to right using
JSplitPane.HORIZONTAL_SPLIT, or top to bottom using JSplitPane.VERTICAL_SPLIT. When
the user is resizing the components the minimum size of the components is used to
determine the maximum/minimum position the components can be set to.

Nested Class

Modifier and Class Description


Type

protected class [Link] This class implements accessibility support


for the JsplitPane class.

Useful Fields

Modifier and Field Description


Type

static String BOTTOM It use to add a Component below the


other Component.

static String CONTINUOUS_LAYOUT_PROPERTY Bound property name for


continuousLayout.

static String DIVIDER It uses to add a Component that will


represent the divider.

static int HORIZONTAL_SPLIT Horizontal split indicates the


Components are split along the x axis.

protected int lastDividerLocation Previous location of the split pane.


protected leftComponent The left or top component.
Component

static int VERTICAL_SPLIT Vertical split indicates the Components


are split along the y axis.

protected rightComponent The right or bottom component.


Component

protected int orientation How the views are split.

Constructors

Constructor Description

JSplitPane() It creates a new JsplitPane configured to


arrange the child components side-by-side
horizontally, using two buttons for the
components.

JSplitPane(int newOrientation) It creates a new JsplitPane configured with


the specified orientation.

JSplitPane(int newOrientation, boolean It creates a new JsplitPane with the specified


newContinuousLayout) orientation and redrawing style.

JSplitPane(int newOrientation, boolean It creates a new JsplitPane with the specified


newContinuousLayout, Component orientation and redrawing style, and with
newLeftComponent, Component the specified components.
newRightComponent)

JSplitPane(int newOrientation, Component It creates a new JsplitPane with the specified


newLeftComponent, Component orientation and the specified components.
newRightComponent)

Useful Methods

Modifier and Method Description


Type
protected void addImpl(Component comp, Object It cdds the specified component to
constraints, int index) this split pane.

AccessibleContext getAccessibleContext() It gets the AccessibleContext


associated with this JSplitPane.

int getDividerLocation() It returns the last value passed to


setDividerLocation.

int getDividerSize() It returns the size of the divider.

Component getBottomComponent() It returns the component below, or to


the right of the divider.

Component getRightComponent() It returns the component to the right


(or below) the divider.

SplitPaneUI getUI() It returns the SplitPaneUI that is


providing the current look and feel.

boolean isContinuousLayout() It gets the continuousLayout


property.

boolean isOneTouchExpandable() It gets the oneTouchExpandable


property.

void setOrientation(int orientation) It gets the orientation, or how the


splitter is divided.

JSplitPane Example
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class JSplitPaneExample {
7. private static void createAndShow() {
8. // Create and set up the window.
9. final JFrame frame = new JFrame("JSplitPane Example");
10. // Display the window.
11. [Link](300, 300);
12. [Link](true);
13. [Link](JFrame.EXIT_ON_CLOSE);
14. // set flow layout for the frame
15. [Link]().setLayout(new FlowLayout());
16. String[] option1 = { "A","B","C","D","E" };
17. JComboBox box1 = new JComboBox(option1);
18. String[] option2 = {"1","2","3","4","5"};
19. JComboBox box2 = new JComboBox(option2);
20. Panel panel1 = new Panel();
21. [Link](box1);
22. Panel panel2 = new Panel();
23. [Link](box2);
24. JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel
2);
25. // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
26. // panel1, panel2);
27. [Link]().add(splitPane);
28. }
29. public static void main(String[] args) {
30. // Schedule a job for the event-dispatching thread:
31. // creating and showing this application's GUI.
32. [Link](new Runnable() {
33. public void run() {
34. createAndShow();
35. }
36. });
37. }
38. }

Output:
Next Topic Java JTextPane

Layout managers
BorderLayout (LayoutManagers)
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in
GUI forms. LayoutManager is an interface that is implemented by all the classes of layout
managers. There are the following classes that represent the layout managers:

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link] etc.

Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:

o BorderLayout(): creates a border layout but with no gaps between the


components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Example of BorderLayout class: Using BorderLayout() constructor


FileName: [Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
15. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
17.
18. [Link](b1, [Link]); // b1 will be placed in the North Direction
19. [Link](b2, [Link]); // b2 will be placed in the South Direction
20. [Link](b3, [Link]); // b2 will be placed in the East Direction
21. [Link](b4, [Link]); // b2 will be placed in the West Direction
22. [Link](b5, [Link]); // b2 will be placed in the Center
23.
24. [Link](300, 300);
25. [Link](true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }

Output:

download this example

Example of BorderLayout class: Using BorderLayout(int hgap, int


vgap) constructor
The following example inserts horizontal and vertical gaps between buttons using the
parameterized constructor BorderLayout(int hgap, int gap)

FileName: [Link]

1. // import statement
2. import [Link].*;
3. import [Link].*;
4. public class BorderLayoutExample
5. {
6. JFrame jframe;
7. // constructor
8. BorderLayoutExample()
9. {
10. // creating a Frame
11. jframe = new JFrame();
12. // create buttons
13. JButton btn1 = new JButton("NORTH");
14. JButton btn2 = new JButton("SOUTH");
15. JButton btn3 = new JButton("EAST");
16. JButton btn4 = new JButton("WEST");
17. JButton btn5 = new JButton("CENTER");
18. // creating an object of the BorderLayout class using
19. // the parameterized constructor where the horizontal gap is 20
20. // and vertical gap is 15. The gap will be evident when buttons are placed
21. // in the frame
22. [Link](new BorderLayout(20, 15));
23. [Link](btn1, [Link]);
24. [Link](btn2, [Link]);
25. [Link](btn3, [Link]);
26. [Link](btn4, [Link]);
27. [Link](btn5, [Link]);
28. [Link](300,300);
29. [Link](true);
30. }
31. // main method
32. public static void main(String argvs[])
33. {
34. new BorderLayoutExample();
35. }
36. }

Output:

Java BorderLayout: Without Specifying Region


The add() method of the JFrame class can work even when we do not specify the region.
In such a case, only the latest component added is shown in the frame, and all the
components added previously get discarded. The latest component covers the whole
area. The following example shows the same.
FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4.
5. public class BorderLayoutWithoutRegionExample
6. {
7. JFrame jframe;
8.
9. // constructor
10. BorderLayoutWithoutRegionExample()
11. {
12. jframe = new JFrame();
13.
14. JButton btn1 = new JButton("NORTH");
15. JButton btn2 = new JButton("SOUTH");
16. JButton btn3 = new JButton("EAST");
17. JButton btn4 = new JButton("WEST");
18. JButton btn5 = new JButton("CENTER");
19.
20. // horizontal gap is 7, and the vertical gap is 7
21. // Since region is not specified, the gaps are of no use
22. [Link](new BorderLayout(7, 7));
23.
24. // each button covers the whole area
25. // however, the btn5 is the latest button
26. // that is added to the frame; therefore, btn5
27. // is shown
28. [Link](btn1);
29. [Link](btn2);
30. [Link](btn3);
31. [Link](btn4);
32. [Link](btn5);
33.
34. [Link](300,300);
35. [Link](true);
36. }
37.
38. // main method
39. public static void main(String argvs[])
40. {
41. new BorderLayoutWithoutRegionExample();
42. }
43. }

Output:

Next Topic GridLayout

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class

1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor


The GridLayout() constructor creates only one row. The following example shows the
usage of the parameterless constructor.
FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4.
5. public class GridLayoutExample
6. {
7. JFrame frameObj;
8.
9. // constructor
10. GridLayoutExample()
11. {
12. frameObj = new JFrame();
13.
14. // creating 9 buttons
15. JButton btn1 = new JButton("1");
16. JButton btn2 = new JButton("2");
17. JButton btn3 = new JButton("3");
18. JButton btn4 = new JButton("4");
19. JButton btn5 = new JButton("5");
20. JButton btn6 = new JButton("6");
21. JButton btn7 = new JButton("7");
22. JButton btn8 = new JButton("8");
23. JButton btn9 = new JButton("9");
24.
25. // adding buttons to the frame
26. // since, we are using the parameterless constructor, therfore;
27. // the number of columns is equal to the number of buttons we
28. // are adding to the frame. The row count remains one.
29. [Link](btn1); [Link](btn2); [Link](btn3);
30. [Link](btn4); [Link](btn5); [Link](btn6);
31. [Link](btn7); [Link](btn8); [Link](btn9);
32.
33. // setting the grid layout using the parameterless constructor
34. [Link](new GridLayout());
35.
36.
37. [Link](300, 300);
38. [Link](true);
39. }
40.
41. // main method
42. public static void main(String argvs[])
43. {
44. new GridLayoutExample();
45. }
46. }

Output:

Example of GridLayout class: Using GridLayout(int rows, int


columns) Constructor
FileName: [Link]

1. import [Link].*;
2. import [Link].*;
3. public class MyGridLayout{
4. JFrame f;
5. MyGridLayout(){
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. JButton b6=new JButton("6");
13. JButton b7=new JButton("7");
14. JButton b8=new JButton("8");
15. JButton b9=new JButton("9");
16. // adding buttons to the frame
17. [Link](b1); [Link](b2); [Link](b3);
18. [Link](b4); [Link](b5); [Link](b6);
19. [Link](b7); [Link](b8); [Link](b9);
20.
21. // setting grid layout of 3 rows and 3 columns
22. [Link](new GridLayout(3,3));
23. [Link](300,300);
24. [Link](true);
25. }
26. public static void main(String[] args) {
27. new MyGridLayout();
28. }
29. }

Output:

download this example

Example of GridLayout class: Using GridLayout(int rows, int


columns, int hgap, int vgap) Constructor
The following example inserts horizontal and vertical gaps between buttons using the
parameterized constructor GridLayout(int rows, int columns, int hgap, int vgap).

FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4.
5. public class GridLayoutExample1
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. GridLayoutExample1()
12. {
13. frameObj = new JFrame();
14.
15. // creating 9 buttons
16. JButton btn1 = new JButton("1");
17. JButton btn2 = new JButton("2");
18. JButton btn3 = new JButton("3");
19. JButton btn4 = new JButton("4");
20. JButton btn5 = new JButton("5");
21. JButton btn6 = new JButton("6");
22. JButton btn7 = new JButton("7");
23. JButton btn8 = new JButton("8");
24. JButton btn9 = new JButton("9");
25.
26. // adding buttons to the frame
27. // since, we are using the parameterless constructor, therefore;
28. // the number of columns is equal to the number of buttons we
29. // are adding to the frame. The row count remains one.
30. [Link](btn1); [Link](btn2); [Link](btn3);
31. [Link](btn4); [Link](btn5); [Link](btn6);
32. [Link](btn7); [Link](btn8); [Link](btn9);
33. // setting the grid layout
34. // a 3 * 3 grid is created with the horizontal gap 20
35. // and vertical gap 25
36. [Link](new GridLayout(3, 3, 20, 25));
37. [Link](300, 300);
38. [Link](true);
39. }
40. // main method
41. public static void main(String argvs[])
42. {
43. new GridLayoutExample();
44. }
45. }

Output:

Next Topic FlowLayout

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another
(in a flow). It is the default layout of the applet or panel.

Fields of FlowLayout class

1. public static final int LEFT


2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Example of FlowLayout class: Using FlowLayout() constructor
FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. [Link](b1); [Link](b2); [Link](b3); [Link](b4);
31. [Link](b5); [Link](b6); [Link](b7); [Link](b8);
32. [Link](b9); [Link](b10);
33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. [Link](new FlowLayout());
38.
39. [Link](300, 300);
40. [Link](true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }

Output:

Example of FlowLayout class: Using FlowLayout(int align)


constructor
FileName: [Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. // adding buttons to the frame
16. [Link](b1); [Link](b2); [Link](b3); [Link](b4); [Link](b5);
17.
18. // setting flow layout of right alignment
19. [Link](new FlowLayout([Link]));
20.
21. [Link](300,300);
22. [Link](true);
23. }
24. public static void main(String[] args) {
25. new MyFlowLayout();
26. }
27. }

Output:

download this example

Example of FlowLayout class: Using FlowLayout(int align, int hgap,


int vgap) constructor
FileName: [Link]

1. // import statement
2. import [Link].*;
3. import [Link].*;
4.
5. public class FlowLayoutExample1
6. {
7. JFrame frameObj;
8.
9. // constructor
10. FlowLayoutExample1()
11. {
12. // creating a frame object
13. frameObj = new JFrame();
14.
15. // creating the buttons
16. JButton b1 = new JButton("1");
17. JButton b2 = new JButton("2");
18. JButton b3 = new JButton("3");
19. JButton b4 = new JButton("4");
20. JButton b5 = new JButton("5");
21. JButton b6 = new JButton("6");
22. JButton b7 = new JButton("7");
23. JButton b8 = new JButton("8");
24. JButton b9 = new JButton("9");
25. JButton b10 = new JButton("10");
26.
27.
28. // adding the buttons to frame
29. [Link](b1); [Link](b2); [Link](b3); [Link](b4);
30. [Link](b5); [Link](b6); [Link](b7); [Link](b8);
31. [Link](b9); [Link](b10);
32.
33. // parameterized constructor is used
34. // where alignment is left
35. // horizontal gap is 20 units and vertical gap is 25 units.
36. [Link](new FlowLayout([Link], 20, 25));
37.
38.
39. [Link](300, 300);
40. [Link](true);
41. }
42. // main method
43. public static void main(String argvs[])
44. {
45. new FlowLayoutExample1();
46. }
47. }

Output:

Next Topic BoxLayout

Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or
horizontally. For this purpose, the BoxLayout class provides four constants. They are as
follows:

Note: The BoxLayout class is found in [Link] package.

Fields of BoxLayout Class

1. public static final int X_AXIS: Alignment of the components are horizontal from left to
right.
2. public static final int Y_AXIS: Alignment of the components are vertical from top to
bottom.
3. public static final int LINE_AXIS: Alignment of the components is similar to the way
words are aligned in a line, which is based on the ComponentOrientation property of the
container. If the ComponentOrientation property of the container is horizontal, then the
components are aligned horizontally; otherwise, the components are aligned vertically. For
horizontal orientations, we have two cases: left to right, and right to left. If the value
ComponentOrientation property of the container is from left to right, then the
components are rendered from left to right, and for right to left, the rendering of
components is also from right to left. In the case of vertical orientations, the components
are always rendered from top to bottom.
4. public static final int PAGE_AXIS: Alignment of the components is similar to the way text
lines are put on a page, which is based on the ComponentOrientation property of the
container. If the ComponentOrientation property of the container is horizontal, then
components are aligned vertically; otherwise, the components are aligned horizontally. For
horizontal orientations, we have two cases: left to right, and right to left. If the value
ComponentOrientation property of the container is also from left to right, then the
components are rendered from left to right, and for right to left, the rendering of
components is from right to left. In the case of vertical orientations, the components are
always rendered from top to bottom.

Constructor of BoxLayout class

1. BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.

Example of BoxLayout class with Y-AXIS:


FileName: [Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. // adding the buttons so that it can be displayed
13. add (buttons[i]);
14. }
15. // the buttons will be placed horizontally
16. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
17. setSize(400,400);
18. setVisible(true);
19. }
20. // main method
21. public static void main(String args[]){
22. BoxLayoutExample1 b=new BoxLayoutExample1();
23. }
24. }
download this example

Output:

Example of BoxLayout class with X-AXIS


FileName: [Link]

1. import [Link].*;
2. import [Link].*;
3.
4. public class BoxLayoutExample2 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample2() {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. // adding the buttons so that it can be displayed
13. add (buttons[i]);
14. }
15. // the buttons in the output will be aligned vertically
16. setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
17. setSize(400,400);
18. setVisible(true);
19. }
20. // main method
21. public static void main(String args[]){
22. BoxLayoutExample2 b=new BoxLayoutExample2();
23. }
24. }
download this example

Output:

Example of BoxLayout Class with LINE_AXIS


The following example shows the effect of setting the value of ComponentOrientation
property of the container to RIGHT_TO_LEFT. If we do not set the value of
ComponentOrientation property, then the components would be laid out from left to
right. Comment line 11, and see it yourself.

FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4.
5. public class BoxLayoutExample3 extends Frame
6. {
7. Button buttons[];
8.
9. // constructor of the class
10. public BoxLayoutExample3()
11. {
12. buttons = new Button[5];
13. setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // line 11
14.
15. for (int i = 0; i < 5; i++)
16. {
17. buttons[i] = new Button ("Button " + (i + 1));
18.
19. // adding the buttons so that it can be displayed
20. add (buttons[i]);
21. }
22.
23. // the ComponentOrientation is set to RIGHT_TO_LEFT. Therefore,
24. // the added buttons will be rendered from right to left
25. setLayout (new BoxLayout(this, BoxLayout.LINE_AXIS));
26. setSize(400, 400);
27. setVisible(true);
28. }
29.
30. // main method
31. public static void main(String argvs[])
32. {
33. // creating an object of the class BoxLayoutExample3
34. BoxLayoutExample3 obj = new BoxLayoutExample3();
35. }
36. }

Output:

Example of BoxLayout Class with PAGE_AXIS


The following example shows how to use PAGE_AXIS.

FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4.
5. public class BoxLayoutExample4 extends Frame
6. {
7. Button buttons[];
8. // constructor of the class
9. public BoxLayoutExample4()
10. {
11. JFrame f = new JFrame();
12. JPanel pnl = new JPanel();
13. buttons = new Button[5];
14. GridBagConstraints constrntObj = new GridBagConstraints();
15.
16. [Link] = [Link];
17. for (int i = 0; i < 5; i++)
18. {
19. buttons[i] = new Button ("Button " + (i + 1));
20.
21. // adding the buttons so that it can be displayed
22. add(buttons[i]);
23. }
24.
25. // the components will be displayed just like the line is present on a page
26. setLayout (new BoxLayout(this, BoxLayout.PAGE_AXIS));
27. setSize(400, 400);
28. setVisible(true);
29. }
30.
31. // main method
32. public static void main(String argvs[])
33. {
34. // creating an object of the class BoxLayoutExample4
35. BoxLayoutExample4 obj = new BoxLayoutExample4();
36. }
37. }

Output:

The above output shows that the buttons are aligned horizontally. Now, we will display
the buttons vertically using the PAGE_AXIS.

FileName: [Link]

1. // import statementss
2. import [Link].*;
3. import [Link].*;
4.
5. public class BoxLayoutExample5 extends Frame
6. {
7. Button buttons[];
8.
9. // constructor of the class
10. public BoxLayoutExample5()
11. {
12. JFrame f = new JFrame();
13. buttons = new Button[5];
14.
15. // Creating a Box whose alignment is horizontal
16. Box horizontalBox = [Link]();
17.
18. // ContentPane returns a container
19. Container contentPane = [Link]();
20.
21. for (int i = 0; i < 5; i++)
22. {
23. buttons[i] = new Button ("Button " + (i + 1));
24.
25. // adding the buttons to the box so that it can be displayed
26. [Link](buttons[i]);
27. }
28.
29. // adding the box and the borderlayout to the content pane
30. [Link](horizontalBox, [Link]);
31.
32. // now, the rendered components are displayed vertically.
33. // it is because the box is aligned horizontally
34. [Link] (new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
35.
36. [Link](400, 400);
37. [Link](true);
38. }
39.
40. // main method
41. public static void main(String argvs[])
42. {
43. // creating an object of the class BoxLayoutExample5
44. BoxLayoutExample5 obj = new BoxLayoutExample5();
45. }
46. }

Output:

Next Topic CardLayout

Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known
as CardLayout.
Constructors of CardLayout Class

1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.

Commonly Used Methods of CardLayout Class

o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of
the given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified
card with the given name.

Example of CardLayout Class: Using Default Constructor


The following program uses the next() method to move to the next card of the container.

FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4. import [Link].*;
5.
6. public class CardLayoutExample1 extends JFrame implements ActionListener
7. {
8.
9. CardLayout crd;
10.
11. // button variables to hold the references of buttons
12. JButton btn1, btn2, btn3;
13. Container cPane;
14.
15. // constructor of the class
16. CardLayoutExample1()
17. {
18.
19. cPane = getContentPane();
20.
21. //default constructor used
22. // therefore, components will
23. // cover the whole area
24. crd = new CardLayout();
25.
26. [Link](crd);
27.
28. // creating the buttons
29. btn1 = new JButton("Apple");
30. btn2 = new JButton("Boy");
31. btn3 = new JButton("Cat");
32.
33. // adding listeners to it
34. [Link](this);
35. [Link](this);
36. [Link](this);
37.
38. [Link]("a", btn1); // first card is the button btn1
39. [Link]("b", btn2); // first card is the button btn2
40. [Link]("c", btn3); // first card is the button btn3
41.
42. }
43. public void actionPerformed(ActionEvent e)
44. {
45. // Upon clicking the button, the next card of the container is shown
46. // after the last card, again, the first card of the container is shown upon clicking
47. [Link](cPane);
48. }
49.
50. // main method
51. public static void main(String argvs[])
52. {
53. // creating an object of the class CardLayoutExample1
54. CardLayoutExample1 crdl = new CardLayoutExample1();
55.
56. // size is 300 * 300
57. [Link](300, 300);
58. [Link](true);
59. [Link](EXIT_ON_CLOSE);
60. }
61. }

Output:

When the button named apple is clicked, we get

When the boy button is clicked, we get

Again, we reach the first card of the container if the cat button is clicked, and the cycle
continues.

Example of CardLayout Class: Using Parameterized Constructor


FileName: [Link]

1. import [Link].*;
2. import [Link].*;
3.
4. import [Link].*;
5.
6. public class CardLayoutExample2 extends JFrame implements ActionListener{
7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExample2(){
11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space
15. [Link](card);
16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. [Link](this);
21. [Link](this);
22. [Link](this);
23.
24. [Link]("a",b1);[Link]("b",b2);[Link]("c",b3);
25.
26. }
27. public void actionPerformed(ActionEvent e) {
28. [Link](c);
29. }
30.
31. public static void main(String[] args) {
32. CardLayoutExample2 cl=new CardLayoutExample2();
33. [Link](400,400);
34. [Link](true);
35. [Link](EXIT_ON_CLOSE);
36. }
37. }
download this example

Output:

Usage of the Methods of the CardLayout Class


The following example shows how one can use different methods of the CardLayout class.

FileName: [Link]

1. // Import statements.
2. import [Link].*;
3. import [Link];
4. import [Link];
5. import [Link].*;
6.
7. public class CardLayoutExample3 extends JFrame
8. {
9.
10. // Initializing the value of
11. // currCard to 1 .
12. private int currCard = 1;
13.
14. // Declaring of objects
15. // of the CardLayout class.
16. private CardLayout cObjl;
17.
18. // constructor of the class
19. public CardLayoutExample3()
20. {
21.
22. // Method to set the Title of the JFrame
23. setTitle("Card Layout Methods");
24.
25. // Method to set the visibility of the JFrame
26. setSize(310, 160);
27.
28. // Creating an Object of the "Jpanel" class
29. JPanel cPanel = new JPanel();
30.
31. // Initializing of the object "cObjl"
32. // of the CardLayout class.
33. cObjl = new CardLayout();
34.
35. // setting the layout
36. [Link](cObjl);
37.
38. // Initializing the object
39. // "jPanel1" of the JPanel class.
40. JPanel jPanel1 = new JPanel();
41.
42. // Initializing the object
43. // "jPanel2" of the CardLayout class.
44. JPanel jPanel2 = new JPanel();
45.
46. // Initializing the object
47. // "jPanel3" of the CardLayout class.
48. JPanel jPanel3 = new JPanel();
49.
50. // Initializing the object
51. // "jPanel4" of the CardLayout class.
52. JPanel jPanel4 = new JPanel();
53.
54. // Initializing the object
55. // "jl1" of the JLabel class.
56. JLabel jLabel1 = new JLabel("C1");
57.
58. // Initializing the object
59. // "jLabel2" of the JLabel class.
60. JLabel jLabel2 = new JLabel("C2");
61.
62. // Initializing the object
63. // "jLabel3" of the JLabel class.
64. JLabel jLabel3 = new JLabel("C3");
65.
66. // Initializing the object
67. // "jLabel4" of the JLabel class.
68. JLabel jLabel4 = new JLabel("C4");
69.
70. // Adding JLabel "jLabel1" to the JPanel "jPanel1".
71. [Link](jLabel1);
72.
73. // Adding JLabel "jLabel2" to the JPanel "jPanel2".
74. [Link](jLabel2);
75.
76. // Adding JLabel "jLabel3" to the JPanel "jPanel3".
77. [Link](jLabel3);
78.
79. // Adding JLabel "jLabel4" to the JPanel "jPanel4".
80. [Link](jLabel4);
81.
82. // Add the "jPanel1" on cPanel
83. [Link](jPanel1, "1");
84.
85. // Add the "jPanel2" on cPanel
86. [Link](jPanel2, "2");
87.
88. // Add the "jPanel3" on cPanel
89. [Link](jPanel3, "3");
90.
91. // Add the "jPanel4" on cPanel
92. [Link](jPanel4, "4");
93.
94. // Creating an Object of the "JPanel" class
95. JPanel btnPanel = new JPanel();
96.
97. // Initializing the object
98. // "firstButton" of the JButton class.
99. JButton firstButton = new JButton("First");
100.
101. // Initializing the object
102. // "nextButton" of the JButton class.
103. JButton nextButton = new JButton("->");
104.
105. // Initializing the object
106. // "previousbtn" of JButton class.
107. JButton previousButton = new JButton("<-");
108.
109. // Initializing the object
110. // "lastButton" of the JButton class.
111. JButton lastButton = new JButton("Last");
112.
113. // Adding the JButton "firstbutton" on the JPanel.
114. [Link](firstButton);
115.
116. // Adding the JButton "nextButton" on the JPanel.
117. [Link](nextButton);
118.
119. // Adding the JButton "previousButton" on the JPanel.
120. [Link](previousButton);
121.
122. // Adding the JButton "lastButton" on the JPanel.
123. [Link](lastButton);
124.
125. // adding firstButton in the ActionListener
126. [Link](new ActionListener()
127. {
128. public void actionPerformed(ActionEvent ae)
129. {
130.
131. // using the first cObjl CardLayout
132. [Link](cPanel);
133.
134. // value of currCard is 1
135. currCard = 1;
136. }
137. });
138.
139. // add lastButton in ActionListener
140. [Link](new ActionListener()
141. {
142. public void actionPerformed(ActionEvent ae)
143. {
144.
145. // using the last cObjl CardLayout
146. [Link](cPanel);
147.
148. // value of currCard is 4
149. currCard = 4;
150. }
151. });
152.
153. // add nextButton in ActionListener
154. [Link](new ActionListener()
155. {
156. public void actionPerformed(ActionEvent ae)
157. {
158.
159. if (currCard < 4)
160. {
161.
162. // increase the value of currCard by 1
163. currCard = currCard + 1;
164.
165. // show the value of currCard
166. [Link](cPanel, "" + (currCard));
167. }
168. }
169. });
170.
171. // add previousButton in ActionListener
172. [Link](new ActionListener()
173. {
174. public void actionPerformed(ActionEvent ae)
175. {
176.
177. if (currCard > 1)
178. {
179.
180. // decrease the value
181. // of currCard by 1
182. currCard = currCard - 1;
183.
184. // show the value of currCard
185. [Link](cPanel, "" + (currCard));
186. }
187. }
188. });
189.
190. // using to get the content pane
191. getContentPane().add(cPanel, [Link]);
192.
193. // using to get the content pane
194. getContentPane().add(btnPanel, [Link]);
195. }
196.
197. // main method
198. public static void main(String argvs[])
199. {
200.
201. // Creating an object of the CardLayoutExample3 class.
202. CardLayoutExample3 cll = new CardLayoutExample3();
203.
204. // method to set the default operation of the JFrame.
205. [Link](JFrame.EXIT_ON_CLOSE);
206.
207. // aethod to set the visibility of the JFrame.
208. [Link](true);
209. }
210. }

Output:

Next Topic Java GridBagLayout

Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.

The components may not be of the same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known as
its display area. Each component associates an instance of GridBagConstraints. With the
help of the constraints object, we arrange the component's display area on the grid. The
GridBagLayout manages each component's minimum and preferred sizes in order to
determine the component's size. GridBagLayout components are also arranged in the
rectangular grid but can have many different sizes and can occupy multiple rows or
columns.

Constructor
GridBagLayout(): The parameterless constructor is used to create a grid bag layout
manager.

GridBagLayout Fields

Modifier and Type Field Description

double[] columnWeights It is used to hold the


overrides to the column
weights.

int[] columnWidths It is used to hold the


overrides to the column
minimum width.

protected comptable It is used to maintains the


Hashtable<Component,GridBagConstraints> association between a
component and its
gridbag constraints.

protected GridBagConstraints defaultConstraints It is used to hold a gridbag


constraints instance
containing the default
values.

protected GridBagLayoutInfo layoutInfo It is used to hold the layout


information for the
gridbag.

protected static int MAXGRIDSIZE No longer in use just for


backward compatibility
protected static int MINSIZE It is smallest grid that can
be laid out by the grid bag
layout.

protected static int PREFERREDSIZE It is preferred grid size that


can be laid out by the grid
bag layout.

int[] rowHeights It is used to hold the


overrides to the row
minimum heights.

double[] rowWeights It is used to hold the


overrides to the row
weights.

GridBagLayout Methods

Modifier and Method Description


Type

void addLayoutComponent(Component It adds specified component


comp, Object constraints) to the layout, using the
specified constraints object.

void addLayoutComponent(String name, It has no effect, since this


Component comp) layout manager does not use
a per-component string.

protected void adjustForGravity(GridBagConstraints It adjusts the x, y, width, and


constraints, Rectangle r) height fields to the correct
values depending on the
constraint geometry and pads.

protected void AdjustForGravity(GridBagConstraints This method is for backwards


constraints, Rectangle r) compatibility only

protected void arrangeGrid(Container parent) Lays out the grid.


protected void ArrangeGrid(Container parent) This method is obsolete and
supplied for backwards
compatibility

GridBagConstraints getConstraints(Component comp) It is for getting the constraints


for the specified component.

float getLayoutAlignmentX(Container parent) It returns the alignment along


the x axis.

float getLayoutAlignmentY(Container parent) It returns the alignment along


the y axis.

int[][] getLayoutDimensions() It determines column widths


and row heights for the layout
grid.

protected getLayoutInfo(Container parent, int This method is obsolete and


GridBagLayoutInfo sizeflag) supplied for backwards
compatibility.

protected GetLayoutInfo(Container parent, int This method is obsolete and


GridBagLayoutInfo sizeflag) supplied for backwards
compatibility.

Point getLayoutOrigin() It determines the origin of the


layout area, in the graphics
coordinate space of the target
container.

double[][] getLayoutWeights() It determines the weights of


the layout grid's columns and
rows.

protected getMinSize(Container parent, It figures out the minimum


Dimension GridBagLayoutInfo info) size of the master based on
the information from
getLayoutInfo.
protected GetMinSize(Container parent, This method is obsolete and
Dimension GridBagLayoutInfo info) supplied for backwards
compatibility only

Example 1
FileName: [Link]

1. import [Link];
2. import [Link];
3. import [Link];
4.
5. import [Link].*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample();
9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. [Link](layout);
17. [Link] = [Link];
18. [Link] = 0;
19. [Link] = 0;
20. [Link](new Button("Button One"), gbc);
21. [Link] = 1;
22. [Link] = 0;
23. [Link](new Button("Button two"), gbc);
24. [Link] = [Link];
25. [Link] = 20;
26. [Link] = 0;
27. [Link] = 1;
28. [Link](new Button("Button Three"), gbc);
29. [Link] = 1;
30. [Link] = 1;
31. [Link](new Button("Button Four"), gbc);
32. [Link] = 0;
33. [Link] = 2;
34. [Link] = [Link];
35. [Link] = 2;
36. [Link](new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE);
41.
42. }
43.
44. }

Output:

Example 2
FileName: [Link]

1. public class GridBagLayoutDemo {


2. final static boolean shouldFill = true;
3. final static boolean shouldWeightX = true;
4. final static boolean RIGHT_TO_LEFT = false;
5.
6. public static void addComponentsToPane(Container pane) {
7. if (RIGHT_TO_LEFT) {
8. [Link](ComponentOrientation.RIGHT_TO_LEFT);
9. }
10.
11. JButton button;
12. [Link](new GridBagLayout());
13. GridBagConstraints c = new GridBagConstraints();
14. if (shouldFill) {
15. //natural height, maximum width
16. [Link] = [Link];
17. }
18.
19. button = new JButton("Button 1");
20. if (shouldWeightX) {
21. [Link] = 0.5;
22. }
23. [Link] = [Link];
24. [Link] = 0;
25. [Link] = 0;
26. [Link](button, c);
27.
28. button = new JButton("Button 2");
29. [Link] = [Link];
30. [Link] = 0.5;
31. [Link] = 1;
32. [Link] = 0;
33. [Link](button, c);
34.
35. button = new JButton("Button 3");
36. [Link] = [Link];
37. [Link] = 0.5;
38. [Link] = 2;
39. [Link] = 0;
40. [Link](button, c);
41.
42. button = new JButton("Long-Named Button 4");
43. [Link] = [Link];
44. [Link] = 40; //make this component tall
45. [Link] = 0.0;
46. [Link] = 3;
47. [Link] = 0;
48. [Link] = 1;
49. [Link](button, c);
50.
51. button = new JButton("5");
52. [Link] = [Link];
53. [Link] = 0; //reset to default
54. [Link] = 1.0; //request any extra vertical space
55. [Link] = GridBagConstraints.PAGE_END; //bottom of space
56. [Link] = new Insets(10,0,0,0); //top padding
57. [Link] = 1; //aligned with button 2
58. [Link] = 2; //2 columns wide
59. [Link] = 2; //third row
60. [Link](button, c);
61. }
62.
63.
64. private static void createAndShowGUI() {
65. //Create and set up the window.
66. JFrame frame = new JFrame("GridBagLayoutDemo");
67. [Link](JFrame.EXIT_ON_CLOSE);
68.
69. //Set up the content pane.
70. addComponentsToPane([Link]());
71.
72. //Display the window.
73. [Link]();
74. [Link](true);
75. }
76.
77. public static void main(String[] args) {
78. [Link](new Runnable() {
79. public void run() {
80. createAndShowGUI();
81. }
82. });
83. }
84. }

Output:

Next Topic Java GroupLayout

GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The
grouping is done by instances of the Group class.

Group is an abstract class, and two concrete classes which implement this Group class are
SequentialGroup and ParallelGroup.

SequentialGroup positions its child sequentially one after another whereas ParallelGroup
aligns its child on top of each other.

The GroupLayout class provides methods such as createParallelGroup() and


createSequentialGroup() to create groups.

GroupLayout treats each axis independently. That is, there is a group representing the
horizontal axis, and a group representing the vertical axis. Each component must exist in
both a horizontal and vertical group, otherwise an IllegalStateException is thrown during
layout or when the minimum, preferred, or maximum size is requested.

Nested Classes

Modifier Class Description


and Type
static class [Link] Enumeration of the possible ways ParallelGroup
can align its children.

class [Link] Group provides the basis for the two types of
operations supported by GroupLayout: laying out
components one after another
(SequentialGroup) or aligned (ParallelGroup).

class [Link] It is a Group that aligns and sizes it's children.

class [Link] It is a Group that positions and sizes its elements


sequentially, one after another.

Fields

Modifier and Field Description


Type

static int DEFAULT_SIZE It indicates the size from the component or gap should be
used for a particular range value.

static int PREFERRED_SIZE It indicates the preferred size from the component or gap
should be used for a particular range value.

Constructors

GroupLayout(Container host) It creates a GroupLayout for the specified Container.

Useful Methods

Modifier and Type Field Description

void addLayoutComponent(Component It notify that a


component, Object constraints) Component has
been added to the
parent container.
void addLayoutComponent(String name, It notify that a
Component component) Component has
been added to the
parent container.

[Link] createBaselineGroup(boolean resizable, It creates and


boolean anchorBaselineToTop) returns a
ParallelGroup that
aligns it's elements
along the baseline.

[Link] createParallelGroup() It creates and


returns a
ParallelGroup with
an alignment of
[Link]

[Link] createParallelGroup([Link] It creates and


alignment) returns a
ParallelGroup with
the specified
alignment.

[Link] createParallelGroup([Link] It creates and


alignment, boolean resizable) returns a
ParallelGroup with
the specified
alignment and
resize behavior.

[Link] createSequentialGroup() It creates and


returns a
SequentialGroup.

boolean getAutoCreateContainerGaps() It returns true if


gaps between the
container and
components that
border the container
are automatically
created.

boolean getAutoCreateGaps() It returns true if


gaps between
components are
automatically
created.

boolean getHonorsVisibility() It returns whether


component visiblity
is considered when
sizing and
positioning
components.

float getLayoutAlignmentX(Container parent) It returns the


alignment along the
x axis.

float getLayoutAlignmentY(Container parent) It returns the


alignment along the
y axis.

Dimension maximumLayoutSize(Container parent) It returns the


maximum size for
the specified
container.

Example 1
FileName: [Link]

1. // import statements
2. import [Link].*;
3. import [Link].*;
4. public class GroupExample {
5. public static void main(String[] args) {
6. JFrame frame = new JFrame("GroupLayoutExample");
7. [Link](JFrame.EXIT_ON_CLOSE);
8. Container contentPanel = [Link]();
9. GroupLayout groupLayout = new GroupLayout(contentPanel);
10.
11. [Link](groupLayout);
12.
13. JLabel clickMe = new JLabel("Click Here");
14. JButton button = new JButton("This Button");
15.
16. [Link](
17. [Link]()
18. .addComponent(clickMe)
19. .addGap(10, 20, 100)
20. .addComponent(button));
21. [Link](
22. [Link]([Link])
23. .addComponent(clickMe)
24. .addComponent(button));
25. [Link]();
26. [Link](true);
27. }
28. }

Output:

Example 2
FileName: [Link]

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import static [Link].*;
6. public class GroupExample2 {
7. public static void main(String[] args) {
8. JFrame frame = new JFrame("GroupLayoutExample");
9. [Link](JFrame.EXIT_ON_CLOSE);
10. Container myPanel = [Link]();
11.
12. GroupLayout groupLayout = new GroupLayout(myPanel);
13. [Link](true);
14. [Link](true);
15. [Link](groupLayout);
16.
17. JButton b1 = new JButton("Button One");
18. JButton b2 = new JButton("Button Two");
19. JButton b3 = new JButton("Button Three");
20.
21. [Link]([Link]()
22. .addGroup([Link](LEADING).addComponent(b1).ad
dComponent(b3))
23. .addGroup([Link](TRAILING).addComponent(b2)));
24.
25. [Link]([Link]()
26. .addGroup([Link](BASELINE).addComponent(b1).ad
dComponent(b2))
27. .addGroup([Link](BASELINE).addComponent(b3)));
28.
29. [Link]();
30. [Link](true);
31. }
32. }

Output:
Next Topic Java SpringLayout

Java SpringLayout
A SpringLayout arranges the children of its associated container according to a set of
constraints. Constraints are nothing but horizontal and vertical distance between two-
component edges. Every constraint is represented by a [Link] object.

Each child of a SpringLayout container, as well as the container itself, has exactly one set
of constraints associated with them.

Each edge position is dependent on the position of the other edge. If a constraint is added
to create a new edge, than the previous binding is discarded. SpringLayout doesn't
automatically set the location of the components it manages.

Constructor
SpringLayout(): The default constructor of the class is used to instantiate the
SpringLayout class.

Nested Classes

Modifier Class Description


and Type

static class [Link] It is a Constraints object helps to govern


component's size and position change in a container
that is controlled by SpringLayout

SpringLayout Fields

Modifier and Field Description


Type

static String BASELINE It specifies the baseline of a component.

static String EAST It specifies the right edge of a component's


bounding rectangle.
static String HEIGHT It specifies the height of a component's bounding
rectangle.

static String HORIZONTAL_CENTER It specifies the horizontal center of a component's


bounding rectangle.

static String NORTH It specifies the top edge of a component's bounding


rectangle.

static String SOUTH It specifies the bottom edge of a component's


bounding rectangle.

static String VERTICAL_CENTER It specifies the vertical center of a component's


bounding rectangle.

static String WEST It specifies the left edge of a component's bounding


rectangle.

static String WIDTH It specifies the width of a component's bounding


rectangle.

SpringLayout Methods

Modifier and Type Method Description

void addLayoutComponent(Component If constraints is an instance


component, Object constraints) of SpringLayout.
Constraints, associates the
constraints with the
specified component.

void addLayoutComponent(String name, Has no effect, since this


Component c) layout manager does not
use a per-component
string.

Spring getConstraint(String edgeName, It returns the spring


Component c) controlling the distance
between the specified edge
of the component and the
top or left edge of its
parent.

[Link] getConstraints(Component c) It returns the constraints for


the specified component.

float getLayoutAlignmentX(Container p) It returns 0.5f (centered).

float getLayoutAlignmentY(Container p) It returns 0.5f (centered).

void invalidateLayout(Container p) It Invalidates the layout,


indicating that if the layout
manager has cached
information it should be
discarded.

void layoutContainer(Container parent) It lays out the specified


container.

Dimension maximumLayoutSize(Container parent) It is used to calculates the


maximum size dimensions
for the specified container,
given the components it
contains.

Dimension minimumLayoutSize(Container parent) It is used to calculates the


minimum size dimensions
for the specified container,
given the components it
contains.

Dimension preferredLayoutSize(Container parent) It is used to calculates the


preferred size dimensions
for the specified container,
given the components it
contains.

Example: 1
FileName: [Link]
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. public class MySpringDemo {
7. private static void createAndShowGUI() {
8. JFrame frame = new JFrame("MySpringDemp");
9. [Link](JFrame.EXIT_ON_CLOSE);
10.
11. Container contentPane = [Link]();
12. SpringLayout layout = new SpringLayout();
13. [Link](layout);
14.
15. JLabel label = new JLabel("Label: ");
16. JTextField textField = new JTextField("My Text Field", 15);
17. [Link](label);
18. [Link](textField);
19.
20. [Link]([Link], label,6,[Link], contentPan
e);
21. [Link]([Link], label,6,[Link], content
Pane);
22. [Link]([Link], textField,6,[Link], label);
23. [Link]([Link], textField,6,[Link], cont
entPane);
24. [Link]([Link], contentPane,6,[Link], textFi
eld);
25. [Link]([Link], contentPane,6,[Link], t
extField);
26.
27. [Link]();
28. [Link](true);
29. }
30. public static void main(String[] args) {
31. [Link](new Runnable() {
32. public void run() {
33. createAndShowGUI();
34. }
35. });
36. }
37. }

Output:

Example: 2
The following program does the arrangement of the components in a JFrame. We have
created one class named "MySpringDemo1 class" and have also created 4 JButton
components called "btn1″, "btn2", "btn3", "btn4", "btn5" and then adding them to the
JFrame using the method add(). Using the method setvisible(), we have set the visibility
of the frame. The setLayout() method sets the layout.

FileName: [Link]

1. // Importing the different Packages.


2. import [Link].*;
3. import [Link].*;
4. // the MySpringDemo1 class
5. public class MySpringDemo1
6. {
7. // main method
8. public static void main(String argvs[])
9. {
10. // the main window
11. // Method for setting the default look and feel
12. // decorated status of the JFrame.
13. [Link](true);
14. // Creating an object of the "JFrame" class
15. JFrame f = new JFrame("Spring Layout Example");
16. // Function to set the default
17. // close operation status of JFrame
18. [Link](JFrame.EXIT_ON_CLOSE);
19. // method to determine the
20. // size status of the JFrame
21. [Link](310, 210);
22. // to get the content pane
23. Container cntt = [Link]();
24. // Creating Object of "SpringLayout" class
25. SpringLayout sprLayout = new SpringLayout();
26. // for setting the layout class
27. [Link](sprLayout);
28. // Initializing the object
29. // "btn1" of the JButton class.
30. Component btn1 = new JButton("C++");
31. // Initializing the object
32. // "btn2" of the JButton class.
33. Component btn2 = new JButton("Python");
34. // Initializing the object
35. // "btn3" the JButton class.
36. Component btn3 = new JButton("JAVA");
37. // Initializing the object
38. // "btn4" of the JButton class.
39. Component btn4 = new JButton("NETWORKING");
40. // Adding the JButton "btn1" on the frame f
41. [Link](btn1);
42. // Adding the JButton "btn2" on the frame f
43. [Link](btn2);
44. // Adding the JButton "btn3" on the frame f
45. [Link](btn3);
46. // Adding the JButton "btn4" on the frame f
47. [Link](btn4);
48. // It is used for inserting the
49. // layout constraint in the JFrame by using
50. // the springLayout class on the btn1 JButton
51. [Link]([Link], btn1,
52. 24, [Link], cntt);
53.
54. [Link]([Link], btn1,
55. 9, [Link], cntt);
56. // It is used for inserting the
57. // layout constraint in the JFrame using
58. // the springLayout class on the btn2 JButton
59. [Link]([Link], btn2,
60. 49, [Link], cntt);
61. [Link]([Link], btn2,
62. 10, [Link], btn1);
63. // It is used for inserting the
64. // layout constraint in the JFrame using
65. // springLayout class on the btn3 JButton
66. [Link]([Link], btn3,
67. 74, [Link], cntt);
68.
69. [Link]([Link], btn3,
70. 9, [Link], btn2);
71. // It is used for inserting the
72. // layout constraint in the JFrame using
73. // sprLayout class on the btn4 JButton
74. [Link]([Link], btn4,
75. 14, [Link], btn1);
76. [Link]([Link], btn4,
77. 9, [Link], cntt);
78. // method for setting the
79. // visibility status of the JFrame
80. [Link](true);
81. }
82. }

Output:

Next Topic Java ScrollPaneLayout

ScrollPaneLayout
The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four "corner"
components.

Constructor
ScrollPaneLayout(): The parameterless constructor is used to create a new
ScrollPanelLayout.

Nested Class

Modifier and Class Description


Type

static class [Link] It is UI resource version of


ScrollPaneLayout.

FieldScrollPanelLayout Field

Modifier and Type Field Description

protected JViewport colHead It is column header child.

protected JScrollBar hsb It is scrollpane's horizontal scrollbar child.

protected int hsbPolicy It displays policy for the horizontal scrollbar.

protected Component lowerLeft This displays the lower left corner.


protected Component lowerRight This displays in the lower right corner.

protected JViewport rowHead It is row header child.

protected Component upperLeft This component displays in the upper left corner.

protected Component upperRight This component displays in the upper right corner.

protected JViewport viewport It is scrollpane's viewport child.

protected JScrollBar vsb It is scrollpane's vertical scrollbar child.

protected int vsbPolicy It is the display policy for the vertical scrollbar.

ScrollPanelLayout Methods

Modifier and Method Description


Type

void addLayoutComponent(String s, Component c) It adds the specified


component to the layout.

protected addSingletonComponent(Component oldC, It removes an existing


Component Component newC) component.

JViewport getColumnHeader() It returns the JViewport object


that is the column header.

Component getCorner(String key) It returns the Component at


the specified corner.

JScrollBar getHorizontalScrollBar() It returns the JScrollBar object


that handles horizontal
scrolling.

int getHorizontalScrollBarPolicy() It returns the horizontal


scrollbar-display policy.

JViewport getRowHeader() It returns the JViewport object


that is the row header.
JScrollBar getVerticalScrollBar() It returns the JScrollBar object
that handles vertical scrolling.

int getVerticalScrollBarPolicy() It returns the vertical scrollbar-


display policy.

JViewport getViewport() It returns the JViewport object


that displays the scrollable
contents.

Example: 1
FileName: [Link]

1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. public class ScrollPaneDemo extends JFrame
6. {
7. public ScrollPaneDemo() {
8. super("ScrollPane Demo");
9. ImageIcon img = new ImageIcon("[Link]");
10.
11. JScrollPane png = new JScrollPane(new JLabel(img));
12.
13. getContentPane().add(png);
14. setSize(300,250);
15. setVisible(true);
16. }
17.
18. public static void main(String[] args) {
19. new ScrollPaneDemo();
20. }
21. }
Output:

Example: 2
The below Java program shows the usage of the ScrollPaneLayout by arranging the
several components of JLabel in a JFrame,

whose instance class is named as "ScrollPaneDemo1". We create one JScrollPane


component named "scrlpane".

Also, the JRadioButton and ButtonGroup are made. We set the visibility and size of the
frame by using the setVisible() and setSize() methods, respectively.

The layout is being set by using the setLayout() method.

FileName: [Link]

1. // important import statements


2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9. import [Link];
10.
11.
12. // creating a class ScrollPaneDemo1
13. // for extending the JFrame
14. public class ScrollPaneDemo1 extends JFrame
15. {
16.
17. // Declaring the objects of
18. // the JScrollPane class
19. JScrollPane scrlpane;
20.
21. // Constructor of the ScrollPaneDemo1 class
22. public ScrollPaneDemo1()
23. {
24.
25. // using to invoke the super class
26. // methods and variables
27. super("JScrollPane Rating Display");
28.
29. // Method to determine the size of the JFrame.
30. setSize(310, 210);
31.
32. // Method to set the Default
33. // tereminating operation of the JFrame.
34. setDefaultCloseOperation(EXIT_ON_CLOSE);
35.
36.
37. inner(); // invoking the method inner
38.
39. // Method for setting the
40. // visibility of the JFrame.
41. setVisible(true);
42. }
43.
44. // method inner
45. public void inner()
46. {
47.
48. // Declaring the objects
49. // of the JRadioButton class.
50. JRadioButton f[][] = new JRadioButton[12][5];
51.
52. // to stores the ratings (1 stat, 2 star, etc)
53. String cnts[] = {"RATING ", " *", " * * ",
54. "* * * ", " * * * * ", " * * * * * "};
55.
56. // to storing the string values
57. String ctg[] = {"CCNA", "Design Patterns", "Java",
58. "Python", "Algorithms",
59. "JAVASCRIPT", "Operating System", "CS Subject",
60. "Data Structure", "PHP language", "Concurrency",
61. "C #" };
62.
63. // Declaration of objects
64. // of the JPanel class.
65. JPanel panel = new JPanel();
66.
67. // method to determine the size of the JFrame.
68. [Link](610, 410);
69.
70. // method to set the Layout of the JFrame.
71. [Link](new GridLayout(13, 6, 10, 0));
72.
73. // for loop
74. for (int r = 0; r < 13; r++) {
75.
76. // Declaring the objects
77. // of the ButtonGroup class
78. ButtonGroup btngrp = new ButtonGroup();
79.
80. for (int c = 0; c < 6; c++)
81. {
82.
83. // for the 0th row
84. if (r == 0)
85. {
86.
87. // adding a new Jlabel
88. [Link](new JLabel(cnts[c]));
89. }
90. else {
91. // for the 0th col
92. if (c == 0)
93. {
94.
95. // adding the new Jlabel
96. [Link](new JLabel(ctg[r - 1]));
97. }
98.
99. else
100. {
101. f[r - 1][c - 1] = new JRadioButton();
102.
103. // adding the form in the ButtonGroup
104. [Link](f[r - 1][c - 1]);
105.
106. // adding the form in the JFrame
107. [Link](f[r - 1][c - 1]);
108. }
109. }
110. }
111. }
112.
113. // Declaring the objects
114. // of the scrollpane class.
115. scrlpane = new JScrollPane(panel);
116.
117. // for getting the content pane
118. getContentPane().add(scrlpane, [Link]);
119. }
120.
121. // main method
122. public static void main(String argvs[])
123. {
124. new ScrollPaneDemo1();
125. }
126. }

Output:

Next Topic Java Applet

You might also like