0% found this document useful (0 votes)
101 views106 pages

Java Swing Tutorial for Beginners

The Java Swing tutorial covers the creation of window-based applications using the Java Foundation Classes (JFC) and the javax.swing package, which provides lightweight and platform-independent components. It highlights the differences between AWT and Swing, introduces commonly used Swing components like JButton and JLabel, and provides examples of creating GUI applications. The tutorial also includes methods, constructors, and event handling for various components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views106 pages

Java Swing Tutorial for Beginners

The Java Swing tutorial covers the creation of window-based applications using the Java Foundation Classes (JFC) and the javax.swing package, which provides lightweight and platform-independent components. It highlights the differences between AWT and Swing, introduces commonly used Swing components like JButton and JLabel, and provides examples of creating GUI applications. The tutorial also includes methods, constructors, and event handling for various components.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, 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- Java swing components


dependent. are platform-independent.

2) AWT components are heavyweight. Swing components


are lightweight.

3) AWT doesn't support pluggable look Swing supports pluggable


and feel. look and feel.

4) AWT provides less components than Swing provides more powerful


Swing. 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 sets size of the component.


height)

public void sets the layout manager for the component.


setLayout(LayoutManager 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 It is used to add the action listener to this


addActionListener(ActionListener a) 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, Acc


essible
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,
horizontalAlignment) image, 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


alignment) along the 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:

Union in C
Keep Watching
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
columns) text and columns.

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


number of columns.
Commonly used Methods:

Methods Description

void It is used to add the specified action listener to


addActionListener(ActionListener receive action events from this textfield.
l)

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


removeActionListener(ActionListe listener so that it no longer receives action
ner l) 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

← PrevNext →

ava 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 Constructs a new empty JPasswordField with the


columns) specified number of columns.

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


specified text.

JPasswordField(String text, Construct a new JPasswordField initialized with the


int columns) specified 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](t
ext);
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:

Java Try Catch


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, Creates a check box with text and specifies whether
boolean selected) or not it 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


getAccessibleContext() with this 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 ActionListene
r{
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:
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 It is used to add the action listener to this


addActionListener(ActionListener a) 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:
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,


ListDataListener, ActionListener, Accessible

Commonly used Constructors:

Constructor Description

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

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


items) 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 It is used to add the ActionListener.


addActionListener(ActionListener
a)

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


i)

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:

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

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


dataModel) specified, non-null, model.

Commonly used Methods:

Methods Description

Void It is used to add a listener to the list,


addListSelectionListener(ListSelectionListen to be notified each time a change to
er listener) 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]
ctedValue();
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:

HTML Tutorial

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 It is used to create an instance of JOptionPane to
message) display a message.

JOptionPane(Object It is used to create an instance of JOptionPane to


message, int messageType display a 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


parentComponent, Object message, String dialog with given title and
title, int 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-


parentComponent, Object message) 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",JOption
Pane.WARNING_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:
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, Acces


sible

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 Creates a scrollbar with the specified


value, int extent, int min, int max) orientation, 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:
How to find Nth Highest Salary in SQL

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, Ac


cessible

JMenu class declaration

1. public class JMenu extends JMenuItem implements MenuElement, Accessi


ble

JMenuItem class declaration

1. public class JMenuItem extends AbstractButton implements Accessible, M


enuElement

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:

Java 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, Me
nuElement

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](pa
ste);
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](pa
ste);
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:

How to find Nth Highest Salary in SQL

Java 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 nuItem 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, It creates a check box menu item with the


boolean b) specified text and selection state.

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


Icon icon) menu item with the specified text and icon.

JCheckBoxMenuItem(String text, It creates a check box menu item with the


Icon icon, boolean b) specified text, icon, and selection state.

Methods

Modifier Method Description

AccessibleCont getAccessibleConte It gets the AccessibleContext associated


ext xt() 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 paramString() It returns a string representation of this


String 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:
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


orientation) vertical orientation.

Commonly used Methods of JSeparator

Method Description

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


orientation)

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:

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 SwingConstan
ts, Accessible

Commonly used Constructors:

Constructor Description

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


text.

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


min, int max) specified minimum and maximum value.

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


orient) orientation, it can be either Vertical or Horizontal by using
[Link] and [Link]
constants.

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


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

Commonly used Methods:

Method Description

void It is used to determine whether string should be


setStringPainted(boolea displayed.
n b)

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

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


orientation) or horizontal by using [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 J

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
value) child of a new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) displays the 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("blac
k");
15. DefaultMutableTreeNode green=new DefaultMutableTreeNode("gre
en");
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:
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


initialcolor) specified color initially.

Commonly used Methods:

Method Description

void It is used to add a color chooser


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

Java JColorChooser Example


1. import [Link].*;
2. import [Link].*;
3. import [Link].*;
4. public class ColorChooserExample extends JFrame implements ActionList
ener {
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 ActionList
ener{
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:
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 creates a horizontal slider using the given min and max.
max)

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

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

Commonly used Methods of JSlider class

Method Description

public void is used to set the minor tick spacing to the


setMinorTickSpacing(int n) slider.

public void is used to set the major tick spacing to the


setMajorTickSpacing(int n) slider.

public void setPaintTicks(boolean is used to determine whether tick marks are


b) painted.

public void setPaintLabels(boolean is used to determine whether labels are


b) painted.

public void is used to determine whether track is painted.


setPaintTracks(boolean b)

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:

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 It is used to add a listener to the list that is


addChangeListener(ChangeListener notified each time a change to the model
listener) 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:

Java 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, RootPaneCont


ainer
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 It is used to create a dialog with the specified title,
title, boolean modal) owner 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:

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


isDoubleBuffered) the specified buffering strategy.

JPanel(LayoutManager It is used to create a new JPanel with the specified


layout) 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:

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 Constructs a JFileChooser using the given File as


currentDirectory) 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 ActionListe
ner{
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:
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


class utton accessibility 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


selected) image and selection state, but no text.

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


specified text.

JToggleButton(String text, It creates a toggle button with the specified text


boolean selected) and selection state.

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

JToggleButton(String text, Icon It creates a toggle button with the specified


icon, boolean selected) text, image, and selection state.

Methods

Modifier and Method Description


Type

AccessibleConte getAccessibleConte It gets the AccessibleContext associated


xt xt() 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 ItemListe
ner {
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

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 [Link] This class implements accessibility


class Bar 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, If a JButton is being


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

void addSeparator() It appends a separator of


default size to the end of
the tool bar.

protected createActionChangeListener(JBu It returns a properly


PropertyChangeListe tton b) configured
ner 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 Factory method which


a) 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", "Op
t-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:

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

Nested Classes

Modifier and Class Description


Type

protected [Link] This class implements accessibility


class utton 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
selected) and 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 It creates a toggle button that has the specified text
icon) and image, and that is initially unselected.

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

Methods

Modifier and Method Description


Type

AccessibleContex getAccessibleConte It gets the AccessibleContext associated with this


t xt() 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

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


Bar 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, If a JButton is being added, it is


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

void addSeparator() It appends a separator of


default size to the end of the
tool bar.

protected createActionChangeListener(JBut It returns a properly configured


PropertyChangeListe ton b) PropertyChangeListener which
ner 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 Factory method which creates


a) 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.
[Link] 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 JViewport
The JViewport class is used to implement scrolling. JViewport is designed to
support both logical scrolling and pixel-based scrolling. The viewport's child,
called the view, is scrolled by calling the [Link]() method.

Nested Classes

Modifier and Class Description


Type

protected [Link] This class implements accessibility


class port support for the Jviewport class.

protected [Link] A listener for the view.


class

Fields

Modifier Field Description


and Type

static int BACKINGSTORE_SCROLL_M It draws viewport contents into an


ODE offscreen image.

protected backingStoreImage The view image used for a backing


Image store.

static int BLIT_SCROLL_MODE It uses [Link] to implement


scrolling.

protected isViewSizeSet True when the viewport dimensions


boolean have been determined.

protected lastPaintPosition The last viewPosition that we've


Point painted, so we know how much of the
backing store image is valid.

protected scrollUnderway The scrollUnderway flag is used for


boolean components like JList.

static int SIMPLE_SCROLL_MODE This mode uses the very simple method
of redrawing the entire contents of the
scrollpane each time it is scrolled.

Constructor

Constructor Description

JViewport() Creates a JViewport.

Methods

Modifier and Type Method Description

void addChangeListener(ChangeList It adds a ChangeListener to


ener l) the list that is notified each
time the view's size,
position, or the viewport's
extent size has changed.

protected createLayoutManager() Subclassers can override


LayoutManager this to install a different
layout manager (or null) in
the constructor.

protected createViewListener() It creates a listener for the


[Link] view.
er

int getScrollMode() It returns the current


scrolling mode.

Component getView() It returns the JViewport's


one child or null.

Point getViewPosition() It returns the view


coordinates that appear in
the upper left hand corner
of the viewport, or 0,0 if
there's no view.

Dimension getViewSize() If the view's size hasn't


been explicitly set, return
the preferred size,
otherwise return the view's
current size.

void setExtentSize(Dimension It sets the size of the


newExtent) visible part of the view
using view coordinates.

void setScrollMode(int mode) It used to control the


method of scrolling the
viewport contents.

void setViewSize(Dimension It sets the size of the view.


newSize)

JViewport 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. public class ViewPortClass2 {
10. public static void main(String[] args) {
11. JFrame frame = new JFrame("Tabbed Pane Sample");
12. [Link](JFrame.EXIT_ON_CLOSE);
13.
14. JLabel label = new JLabel("Label");
15. [Link](new Dimension(1000, 1000));
16. JScrollPane jScrollPane = new JScrollPane(label);
17.
18. JButton jButton1 = new JButton();
19. [Link](JScrollPane.HORIZONTAL_
SCROLLBAR_ALWAYS);
20. [Link](JScrollPane.VERTICAL_SCRO
LLBAR_ALWAYS);
21. [Link](new LineBorder([Link]));
22. [Link]().add(jButton1, null);
23.
24. [Link](jScrollPane, [Link]);
25. [Link](400, 150);
26. [Link](true);
27. }
28. }

Output:

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


ame 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 rootPane The JRootPane instance that manages


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

protected boolean rootPaneCheckingEna If true then calls to add and setLayout


bled will be forwarded to the contentPane.

Constructors

Constructor Description

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

JFrame(GraphicsConfiguration It creates a Frame in the specified


gc) 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


GraphicsConfiguration gc) the specified GraphicsConfiguration of a screen
device.

Useful Methods

Modifier and Method Description


Type

protected addImpl(Component comp, Object Adds the specified child


void constraints, int index) Component.

protected createRootPane() Called by the constructor


JRootPane methods to create the
default rootPane.

protected frameInit() Called by the constructors


void to init the JFrame
properly.
void setContentPane(Containe It sets the contentPane
contentPane) property

static void setDefaultLookAndFeelDecorated(bool Provides a hint as to


ean defaultLookAndFeelDecorated) whether 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 It sets the layeredPane


layeredPane) property.

JRootPane getRootPane() It returns the rootPane


object for this frame.

TransferHandl getTransferHandler() It gets the


er 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

You might also like