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 javax.swing 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 J
1) AWT components are platform-dependent.
2) AWT components are heavyweight.
3) AWT doesn't support pluggable look and feel.
4) AWT provides less components than Swing.
5) AWT doesn't follows MVC(Model View 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 com
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the
public void setVisible(boolean b) sets the visibility of the compone
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: FirstSwingExample.java
1. import javax.swing.*;
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. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(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: Simple.java
1. import javax.swing.*;
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. b.setBounds(130,100,100, 40);
9.
10. f.add(b);//adding button in JFrame
11.
12. f.setSize(400,500);//400 width and 500 height
13. f.setLayout(null);//using no layout managers
14. f.setVisible(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: Simple2.java
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(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
next →← prev
Java JButton
The JButton class is used to create a labeled button that has platform independent implementation. The applica
AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton 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 specifie
String getText() It is used to return the t
void setEnabled(boolean b) It is used to enable or d
void setIcon(Icon b) It is used to set the spe
Icon getIcon() It is used to get the Ico
void setMnemonic(int a) It is used to set the mn
void addActionListener(ActionListener a) It is used to add the act
Java JButton Example
1. import javax.swing.*;
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. b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. }
Output:
Java JButton Example with ActionListener
1. import java.awt.event.*;
2. import javax.swing.*;
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. tf.setBounds(50,50, 150,20);
8. JButton b=new JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to Javatpoint.");
13. }
14. });
15. f.add(b);f.add(tf);
16. f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }
20. }
Output:
Example of displaying image on the button:
1. import javax.swing.*;
2. public class ButtonExample{
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton(new ImageIcon("D:\\icon.png"));
6. b.setBounds(100,100,100, 40);
7. f.add(b);
8. f.setSize(300,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. f.setDefaultCloseOperation(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 javax.swing.JLabel class.
1. public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image a
JLabel(String s) Creates a JLabel instance with the specifie
JLabel(Icon i) Creates a JLabel instance with the specifie
JLabel(String s, Icon i, int horizontalAlignment) Creates a JLabel instance with the specifie
Commonly used Methods:
Methods Description
String getText() t returns the text string that a labe
void setText(String text) It defines the single line of text this
void setHorizontalAlignment(int alignment) It sets the alignment of the label's
Icon getIcon() It returns the graphic image that th
int getHorizontalAlignment() It returns the alignment of the labe
Java JLabel Example
1. import javax.swing.*;
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. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
Java JLabel Example with ActionListener
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class LabelExample extends Frame implements ActionListener{
5. JTextField tf; JLabel l; JButton b;
6. LabelExample(){
7. tf=new JTextField();
8. tf.setBounds(50,50, 150,20);
9. l=new JLabel();
10. l.setBounds(50,100, 250,20);
11. b=new JButton("Find IP");
12. b.setBounds(50,150,95,30);
13. b.addActionListener(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=tf.getText();
22. String ip=java.net.InetAddress.getByName(host).getHostAddress();
23. l.setText("IP of "+host+" is: "+ip);
24. }catch(Exception ex){System.out.println(ex);}
25. }
26. public static void main(String[] args) {
27. new LabelExample();
28. }}
Output:
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 javax.swing.JTextField 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 spe
JTextField(String text, int columns) Creates a new TextField initialized with the spe
JTextField(int columns) Creates a new empty TextField with the specifi
Commonly used Methods:
Methods Description
void addActionListener(ActionListener l) It is used to add the specified action listener to receive
Action getAction() It returns the currently set Action for this ActionEvent s
void setFont(Font f) It is used to set the current font.
void removeActionListener(ActionListener l) It is used to remove the specified action listener so that
Java JTextField Example
1. import javax.swing.*;
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. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
Java JTextField Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
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. tf1.setBounds(50,50,150,20);
10. tf2=new JTextField();
11. tf2.setBounds(50,100,150,20);
12. tf3=new JTextField();
13. tf3.setBounds(50,150,150,20);
14. tf3.setEditable(false);
15. b1=new JButton("+");
16. b1.setBounds(50,200,50,50);
17. b2=new JButton("-");
18. b2.setBounds(120,200,50,50);
19. b1.addActionListener(this);
20. b2.addActionListener(this);
21. f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
22. f.setSize(300,300);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public void actionPerformed(ActionEvent e) {
27. String s1=tf1.getText();
28. String s2=tf2.getText();
29. int a=Integer.parseInt(s1);
30. int b=Integer.parseInt(s2);
31. int c=0;
32. if(e.getSource()==b1){
33. c=a+b;
34. }else if(e.getSource()==b2){
35. c=a-b;
36. }
37. String result=String.valueOf(c);
38. tf3.setText(result);
39. }
40. public static void main(String[] args) {
41. new TextFieldExample();
42. } }
Output:
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 javax.swing.JTextArea 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
JTextArea(String s, int row, int column) Creates a text area with the specified number of rows
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 sp
void append(String s) It is used to append the given text to the end
Java JTextArea Example
1. import javax.swing.*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to javatpoint");
7. area.setBounds(10,30, 200,200);
8. f.add(area);
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. }}
Output:
Java JTextArea Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
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. l1.setBounds(50,25,100,30);
11. l2=new JLabel();
12. l2.setBounds(160,25,100,30);
13. area=new JTextArea();
14. area.setBounds(20,75,250,200);
15. b=new JButton("Count Words");
16. b.setBounds(100,300,120,30);
17. b.addActionListener(this);
18. f.add(l1);f.add(l2);f.add(area);f.add(b);
19. f.setSize(450,450);
20. f.setLayout(null);
21. f.setVisible(true);
22. }
23. public void actionPerformed(ActionEvent e){
24. String text=area.getText();
25. String words[]=text.split("\\s");
26. l1.setText("Words: "+words.length);
27. l2.setText("Characters: "+text.length());
28. }
29. public static void main(String[] args) {
30. new TextAreaExample();
31. }
32. }
Output:
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 javax.swing.JPasswordField class.
1. public class JPasswordField extends JTextField
Commonly used Constructors:
Constructor Description
JPasswordField() Constructs a new JPasswordField, with a default docume
JPasswordField(int columns) Constructs a new empty JPasswordField with the specifie
JPasswordField(String text) Constructs a new JPasswordField initialized with the spec
JPasswordField(String text, int columns) Construct a new JPasswordField initialized with the speci
Java JPasswordField Example
1. import javax.swing.*;
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. l1.setBounds(20,100, 80,30);
8. value.setBounds(100,100,100,30);
9. f.add(value); f.add(l1);
10. f.setSize(300,300);
11. f.setLayout(null);
12. f.setVisible(true);
13. }
14. }
Output:
Java JPasswordField Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
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. label.setBounds(20,150, 200,50);
8. final JPasswordField value = new JPasswordField();
9. value.setBounds(100,75,100,30);
10. JLabel l1=new JLabel("Username:");
11. l1.setBounds(20,20, 80,30);
12. JLabel l2=new JLabel("Password:");
13. l2.setBounds(20,75, 80,30);
14. JButton b = new JButton("Login");
15. b.setBounds(100,120, 80,30);
16. final JTextField text = new JTextField();
17. text.setBounds(100,20, 100,30);
18. f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);
19. f.setSize(300,300);
20. f.setLayout(null);
21. f.setVisible(true);
22. b.addActionListener(new ActionListener() {
23. public void actionPerformed(ActionEvent e) {
24. String data = "Username " + text.getText();
25. data += ", Password: "
26. + new String(value.getPassword());
27. label.setText(data);
28. }
29. });
30. }
31. }
Output:
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 javax.swing.JCheckBox class.
1. public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JJCheckBox() Creates an initially unselected check box butto
JChechBox(String s) Creates an initially unselected check box with
JCheckBox(String text, boolean selected) Creates a check box with text and specifies wh
JCheckBox(Action a) Creates a check box where properties are take
Commonly used Methods:
Methods Description
AccessibleContext getAccessibleContext() It is used to get the AccessibleContext as
protected String paramString() It returns a string representation of this
Java JCheckBox Example
1. import javax.swing.*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. checkBox1.setBounds(100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);
9. checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}
Output:
Java JCheckBox Example with ItemListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class CheckBoxExample
4. {
5. CheckBoxExample(){
6. JFrame f= new JFrame("CheckBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JCheckBox checkbox1 = new JCheckBox("C++");
11. checkbox1.setBounds(150,100, 50,50);
12. JCheckBox checkbox2 = new JCheckBox("Java");
13. checkbox2.setBounds(150,150, 50,50);
14. f.add(checkbox1); f.add(checkbox2); f.add(label);
15. checkbox1.addItemListener(new ItemListener() {
16. public void itemStateChanged(ItemEvent e) {
17. label.setText("C++ Checkbox: "
18. + (e.getStateChange()==1?"checked":"unchecked"));
19. }
20. });
21. checkbox2.addItemListener(new ItemListener() {
22. public void itemStateChanged(ItemEvent e) {
23. label.setText("Java Checkbox: "
24. + (e.getStateChange()==1?"checked":"unchecked"));
25. }
26. });
27. f.setSize(400,400);
28. f.setLayout(null);
29. f.setVisible(true);
30. }
31. public static void main(String args[])
32. {
33. new CheckBoxExample();
34. }
35. }
Output:
Java JCheckBox Example: Food Order
1. import javax.swing.*;
2. import java.awt.event.*;
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. l.setBounds(50,50,300,20);
10. cb1=new JCheckBox("Pizza @ 100");
11. cb1.setBounds(100,100,150,20);
12. cb2=new JCheckBox("Burger @ 30");
13. cb2.setBounds(100,150,150,20);
14. cb3=new JCheckBox("Tea @ 10");
15. cb3.setBounds(100,200,150,20);
16. b=new JButton("Order");
17. b.setBounds(100,250,80,30);
18. b.addActionListener(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(cb1.isSelected()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if(cb2.isSelected()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if(cb3.isSelected()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+="-----------------\n";
41. JOptionPane.showMessageDialog(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 javax.swing.JRadioButton class.
1. public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
JRadioButton() Creates an unselected radio button wit
JRadioButton(String s) Creates an unselected radio button wit
JRadioButton(String s, boolean selected) Creates a radio button with the specifie
Commonly used Methods:
Methods Description
void setText(String s) It is used to set specified te
String getText() It is used to return the text
void setEnabled(boolean b) It is used to enable or disab
void setIcon(Icon b) It is used to set the specifie
Icon getIcon() It is used to get the Icon of
void setMnemonic(int a) It is used to set the mnemo
void addActionListener(ActionListener a) It is used to add the action
Java JRadioButton Example
1. import javax.swing.*;
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. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
12. f.add(r1);f.add(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
Output:
Java JRadioButton Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. class RadioButtonExample extends JFrame implements ActionListener{
4. JRadioButton rb1,rb2;
5. JButton b;
6. RadioButtonExample(){
7. rb1=new JRadioButton("Male");
8. rb1.setBounds(100,50,100,30);
9. rb2=new JRadioButton("Female");
10. rb2.setBounds(100,100,100,30);
11. ButtonGroup bg=new ButtonGroup();
12. bg.add(rb1);bg.add(rb2);
13. b=new JButton("click");
14. b.setBounds(100,150,80,30);
15. b.addActionListener(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(rb1.isSelected()){
23. JOptionPane.showMessageDialog(this,"You are Male.");
24. }
25. if(rb2.isSelected()){
26. JOptionPane.showMessageDialog(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 javax.swing.JComboBox class.
1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, ActionListe
ner, 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 t
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in t
Commonly used Methods:
Methods Description
void addItem(Object anObject) It is used to add an item to the ite
void removeItem(Object anObject) It is used to delete an item to the i
void removeAllItems() It is used to remove all the items f
void setEditable(boolean b) It is used to determine whether th
void addActionListener(ActionListener a) It is used to add the ActionListener
void addItemListener(ItemListener i) It is used to add the ItemListener.
Java JComboBox Example
1. import javax.swing.*;
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. cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(null);
11. f.setSize(400,500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }
Output:
Java JComboBox Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ComboBoxExample {
4. JFrame f;
5. ComboBoxExample(){
6. f=new JFrame("ComboBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JButton b=new JButton("Show");
11. b.setBounds(200,100,75,20);
12. String languages[]={"C","C++","C#","Java","PHP"};
13. final JComboBox cb=new JComboBox(languages);
14. cb.setBounds(50, 100,90,20);
15. f.add(cb); f.add(label); f.add(b);
16. f.setLayout(null);
17. f.setSize(350,350);
18. f.setVisible(true);
19. b.addActionListener(new ActionListener() {
20. public void actionPerformed(ActionEvent e) {
21. String data = "Programming language Selected: "
22. + cb.getItemAt(cb.getSelectedIndex());
23. label.setText(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 javax.swing.JTable class.
Commonly used Constructors:
Constructor Description
JTable() Creates a table
JTable(Object[][] rows, Object[] columns) Creates a table
Java JTable Example
1. import javax.swing.*;
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. jt.setBounds(30,40,200,300);
12. JScrollPane sp=new JScrollPane(jt);
13. f.add(sp);
14. f.setSize(300,400);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new TableExample();
19. }
20. }
Output:
Java JTable Example with ListSelectionListener
1. import javax.swing.*;
2. import javax.swing.event.*;
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. jt.setCellSelectionEnabled(true);
12. ListSelectionModel select= jt.getSelectionModel();
13. select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
14. select.addListSelectionListener(new ListSelectionListener() {
15. public void valueChanged(ListSelectionEvent e) {
16. String Data = null;
17. int[] row = jt.getSelectedRows();
18. int[] columns = jt.getSelectedColumns();
19. for (int i = 0; i < row.length; i++) {
20. for (int j = 0; j < columns.length; j++) {
21. Data = (String) jt.getValueAt(row[i], columns[j]);
22. }}
23. System.out.println("Table element selected is: " + Data);
24. }
25. });
26. JScrollPane sp=new JScrollPane(jt);
27. f.add(sp);
28. f.setSize(300, 200);
29. f.setVisible(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 javax.swing.JList 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 sp
JList(ListModel<ary> dataModel) Creates a JList that displays elements from the spe
Commonly used Methods:
Methods Description
Void addListSelectionListener(ListSelectionListener listener) It is used to add a listener to the list, t
int getSelectedIndex() It is used to return the smallest selecte
ListModel getModel() It is used to return the data model tha
void setListData(Object[] listData) It is used to create a read-only ListMod
Java JList Example
1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}
Output:
Java JList Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ListExample
4. {
5. ListExample(){
6. JFrame f= new JFrame();
7. final JLabel label = new JLabel();
8. label.setSize(500,100);
9. JButton b=new JButton("Show");
10. b.setBounds(200,150,80,30);
11. final DefaultListModel<String> l1 = new DefaultListModel<>();
12. l1.addElement("C");
13. l1.addElement("C++");
14. l1.addElement("Java");
15. l1.addElement("PHP");
16. final JList<String> list1 = new JList<>(l1);
17. list1.setBounds(100,100, 75,75);
18. DefaultListModel<String> l2 = new DefaultListModel<>();
19. l2.addElement("Turbo C++");
20. l2.addElement("Struts");
21. l2.addElement("Spring");
22. l2.addElement("YII");
23. final JList<String> list2 = new JList<>(l2);
24. list2.setBounds(100,200, 75,75);
25. f.add(list1); f.add(list2); f.add(b); f.add(label);
26. f.setSize(450,450);
27. f.setLayout(null);
28. f.setVisible(true);
29. b.addActionListener(new ActionListener() {
30. public void actionPerformed(ActionEvent e) {
31. String data = "";
32. if (list1.getSelectedIndex() != -1) {
33. data = "Programming language Selected: " + list1.getSelectedValue();
34. label.setText(data);
35. }
36. if(list2.getSelectedIndex() != -1){
37. data += ", FrameWork Selected: ";
38. for(Object frame :list2.getSelectedValues()){
39. data += frame + " ";
40. }
41. }
42. label.setText(data);
43. }
44. });
45. }
46. public static void main(String args[])
47. {
48. new ListExample();
49. }}
Output:
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 displa
JOptionPane(Object message, int messageType It is used to create an instance of JOptionPane to displa
Common Methods of JOptionPane class
Methods Description
JDialog createDialog(String title) It is used to crea
static void showMessageDialog(Component parentComponent, Object message) It is used to crea
static void showMessageDialog(Component parentComponent, Object message, String It is used to crea
title, int messageType)
static int showConfirmDialog(Component parentComponent, Object message) It is used to crea
Select an Option
static String showInputDialog(Component parentComponent, Object message) It is used to sho
parented to pare
void setInputValue(Object newValue) It is used to set
Java JOptionPane Example: showMessageDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(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 javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Output:
Java JOptionPane Example: showInputDialog()
1. import javax.swing.*;
2. public class OptionPaneExample {
3. JFrame f;
4. OptionPaneExample(){
5. f=new JFrame();
6. String name=JOptionPane.showInputDialog(f,"Enter Name");
7. }
8. public static void main(String[] args) {
9. new OptionPaneExample();
10. }
11. }
Output:
Java JOptionPane Example: showConfirmDialog()
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class OptionPaneExample extends WindowAdapter{
4. JFrame f;
5. OptionPaneExample(){
6. f=new JFrame();
7. f.addWindowListener(this);
8. f.setSize(300, 300);
9. f.setLayout(null);
10. f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
11. f.setVisible(true);
12. }
13. public void windowClosing(WindowEvent e) {
14. int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
15. if(a==JOptionPane.YES_OPTION){
16. f.setDefaultCloseOperation(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 javax.swing.JScrollBar class.
1. public class JScrollBar extends JComponent implements Adjustable, Accessible
Commonly used Constructors:
Constructor Description
JScrollBar() Creates a vertical scrollbar with t
JScrollBar(int orientation) Creates a scrollbar with the speci
JScrollBar(int orientation, int value, int extent, int min, int max) Creates a scrollbar with the speci
Java JScrollBar Example
1. import javax.swing.*;
2. class ScrollBarExample
3. {
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new ScrollBarExample();
16. }}
Output:
Java JScrollBar Example with AdjustmentListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. class ScrollBarExample
4. {
5. ScrollBarExample(){
6. JFrame f= new JFrame("Scrollbar Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. final JScrollBar s=new JScrollBar();
11. s.setBounds(100,100, 50,100);
12. f.add(s); f.add(label);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. s.addAdjustmentListener(new AdjustmentListener() {
17. public void adjustmentValueChanged(AdjustmentEvent e) {
18. label.setText("Vertical Scrollbar value is:"+ s.getValue());
19. }
20. });
21. }
22. public static void main(String args[])
23. {
24. new ScrollBarExample();
25. }}
Output:
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 javax.swing.*;
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. menu.add(i1); menu.add(i2); menu.add(i3);
17. submenu.add(i4); submenu.add(i5);
18. menu.add(submenu);
19. mb.add(menu);
20. f.setJMenuBar(mb);
21. f.setSize(400,400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25. public static void main(String args[])
26. {
27. new MenuExample();
28. }}
Output:
Example of creating Edit menu for Notepad:
1. import javax.swing.*;
2. import java.awt.event.*;
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. cut.addActionListener(this);
16. copy.addActionListener(this);
17. paste.addActionListener(this);
18. selectAll.addActionListener(this);
19. mb=new JMenuBar();
20. file=new JMenu("File");
21. edit=new JMenu("Edit");
22. help=new JMenu("Help");
23. edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
24. mb.add(file);mb.add(edit);mb.add(help);
25. ta=new JTextArea();
26. ta.setBounds(5,5,360,320);
27. f.add(mb);f.add(ta);
28. f.setJMenuBar(mb);
29. f.setLayout(null);
30. f.setSize(400,400);
31. f.setVisible(true);
32. }
33. public void actionPerformed(ActionEvent e) {
34. if(e.getSource()==cut)
35. ta.cut();
36. if(e.getSource()==paste)
37. ta.paste();
38. if(e.getSource()==copy)
39. ta.copy();
40. if(e.getSource()==selectAll)
41. ta.selectAll();
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 javax.swing.JPopupMenu class.
1. public class JPopupMenu extends JComponent implements Accessible, MenuElement
Commonly used Constructors:
Constructor Description
JPopupMenu() Constructs a JPopupMenu without an "invok
JPopupMenu(String label) Constructs a JPopupMenu with the specified
Java JPopupMenu Example
1. import javax.swing.*;
2. import java.awt.event.*;
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. popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);
12. f.addMouseListener(new MouseAdapter() {
13. public void mouseClicked(MouseEvent e) {
14. popupmenu.show(f , e.getX(), e.getY());
15. }
16. });
17. f.add(popupmenu);
18. f.setSize(300,300);
19. f.setLayout(null);
20. f.setVisible(true);
21. }
22. public static void main(String args[])
23. {
24. new PopupMenuExample();
25. }}
Output:
Java JPopupMenu Example with MouseListener and
ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. class PopupMenuExample
4. {
5. PopupMenuExample(){
6. final JFrame f= new JFrame("PopupMenu Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(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. popupmenu.add(cut); popupmenu.add(copy); popupmenu.add(paste);
15. f.addMouseListener(new MouseAdapter() {
16. public void mouseClicked(MouseEvent e) {
17. popupmenu.show(f , e.getX(), e.getY());
18. }
19. });
20. cut.addActionListener(new ActionListener(){
21. public void actionPerformed(ActionEvent e) {
22. label.setText("cut MenuItem clicked.");
23. }
24. });
25. copy.addActionListener(new ActionListener(){
26. public void actionPerformed(ActionEvent e) {
27. label.setText("copy MenuItem clicked.");
28. }
29. });
30. paste.addActionListener(new ActionListener(){
31. public void actionPerformed(ActionEvent e) {
32. label.setText("paste MenuItem clicked.");
33. }
34. });
35. f.add(label); f.add(popupmenu);
36. f.setSize(400,400);
37. f.setLayout(null);
38. f.setVisible(true);
39. }
40. public static void main(String args[])
41. {
42. new PopupMenuExample();
43. }
44. }
Output:
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 and Type Class Description
protected class JCheckBoxMenuItem.AccessibleJCheckBoxMenuItem This class implemen
Constructor
Constructor Description
JCheckBoxMenuItem() It creates an initially unselected check
JCheckBoxMenuItem(Action a) It creates a menu item whose propert
JCheckBoxMenuItem(Icon icon) It creates an initially unselected check
JCheckBoxMenuItem(String text) It creates an initially unselected check
JCheckBoxMenuItem(String text, boolean b) It creates a check box menu item with
JCheckBoxMenuItem(String text, Icon icon) It creates an initially unselected check
JCheckBoxMenuItem(String text, Icon icon, boolean b) It creates a check box menu item with
Methods
Modifier Method Description
AccessibleContext getAccessibleContext() It gets the AccessibleContext associated with this JChe
Object[] getSelectedObjects() It returns an array (length 1) containing the check box
boolean getState() It returns the selected-state of the item.
String getUIClassID() It returns the name of the L&F class that renders this
protected String paramString() It returns a string representation of this JCheckBoxMe
void setState(boolean b) It sets the selected-state of the item.
Java JCheckBoxMenuItem Example
1. import java.awt.event.ActionEvent;
2. import java.awt.event.ActionListener;
3. import java.awt.event.KeyEvent;
4. import javax.swing.AbstractButton;
5. import javax.swing.Icon;
6. import javax.swing.JCheckBoxMenuItem;
7. import javax.swing.JFrame;
8. import javax.swing.JMenu;
9. import javax.swing.JMenuBar;
10. import javax.swing.JMenuItem;
11.
12. public class JavaCheckBoxMenuItem {
13. public static void main(final String args[]) {
14. JFrame frame = new JFrame("Jmenu Example");
15. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16. JMenuBar menuBar = new JMenuBar();
17. // File Menu, F - Mnemonic
18. JMenu fileMenu = new JMenu("File");
19. fileMenu.setMnemonic(KeyEvent.VK_F);
20. menuBar.add(fileMenu);
21. // File->New, N - Mnemonic
22. JMenuItem menuItem1 = new JMenuItem("Open", KeyEvent.VK_N);
23. fileMenu.add(menuItem1);
24.
25. JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem("Option_1");
26. caseMenuItem.setMnemonic(KeyEvent.VK_C);
27. fileMenu.add(caseMenuItem);
28.
29. ActionListener aListener = new ActionListener() {
30. public void actionPerformed(ActionEvent event) {
31. AbstractButton aButton = (AbstractButton) event.getSource();
32. boolean selected = aButton.getModel().isSelected();
33. String newLabel;
34. Icon newIcon;
35. if (selected) {
36. newLabel = "Value-1";
37. } else {
38. newLabel = "Value-2";
39. }
40. aButton.setText(newLabel);
41. }
42. };
43.
44. caseMenuItem.addActionListener(aListener);
45. frame.setJMenuBar(menuBar);
46. frame.setSize(350, 250);
47. frame.setVisible(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 orientation) Creates a new separator with the specified horizontal or ve
Commonly used Methods of JSeparator
Method Description
void setOrientation(int orientation) It is used to set the orientation of t
int getOrientation() It is used to return the orientation
Java JSeparator Example 1
1. import javax.swing.*;
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. menu.add(i1);
13. menu.addSeparator();
14. menu.add(i2);
15. mb.add(menu);
16. f.setJMenuBar(mb);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String args[])
22. {
23. new SeparatorExample();
24. }}
Output:
Java JSeparator Example 2
1. import javax.swing.*;
2. import java.awt.*;
3. public class SeparatorExample
4. {
5. public static void main(String args[]) {
6. JFrame f = new JFrame("Separator Example");
7. f.setLayout(new GridLayout(0, 1));
8. JLabel l1 = new JLabel("Above Separator");
9. f.add(l1);
10. JSeparator sep = new JSeparator();
11. f.add(sep);
12. JLabel l2 = new JLabel("Below Separator");
13. f.add(l2);
14. f.setSize(400, 100);
15. f.setVisible(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 javax.swing.JProgressBar class.
1. public class JProgressBar extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description
JProgressBar() It is used to create a horizontal progress bar but no string text.
JProgressBar(int min, int max) It is used to create a horizontal progress bar with the specified minimu
JProgressBar(int orient) It is used to create a progress bar with the specified orientation, it can
SwingConstants.VERTICAL and SwingConstants.HORIZONTAL constants
JProgressBar(int orient, int min, It is used to create a progress bar with the specified orientation, minim
int max)
Commonly used Methods:
Method Description
void setStringPainted(boolean b) It is used to determine whether string should be displayed.
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 horizontal b
orientation) SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress bar.
Java JProgressBar Example
1. import javax.swing.*;
2. public class ProgressBarExample extends JFrame{
3. JProgressBar jb;
4. int i=0,num=0;
5. ProgressBarExample(){
6. jb=new JProgressBar(0,2000);
7. jb.setBounds(40,40,160,30);
8. jb.setValue(0);
9. jb.setStringPainted(true);
10. add(jb);
11. setSize(250,150);
12. setLayout(null);
13. }
14. public void iterate(){
15. while(i<=2000){
16. jb.setValue(i);
17. i=i+20;
18. try{Thread.sleep(150);}catch(Exception e){}
19. }
20. }
21. public static void main(String[] args) {
22. ProgressBarExample m=new ProgressBarExample();
23. m.setVisible(true);
24. m.iterate();
25. }
26. }
Output:
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 javax.swing.JTree 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[] value) Creates a JTree with every element of the specified array as the child
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which displays
Java JTree Example
1. import javax.swing.*;
2. import javax.swing.tree.DefaultMutableTreeNode;
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. style.add(color);
11. style.add(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. color.add(red); color.add(blue); color.add(black); color.add(green);
17. JTree jt=new JTree(style);
18. f.add(jt);
19. f.setSize(200,200);
20. f.setVisible(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 javax.swing.JColorChooser 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
JColorChooser(color initialcolor) It is used to create a color chooser panel with the s
Commonly used Methods:
Method Description
void addChooserPanel(AbstractColorChooserPanel panel) It is used to a
static Color showDialog(Component c, String title, Color initialColor) It is used to s
Java JColorChooser Example
1. import java.awt.event.*;
2. import java.awt.*;
3. import javax.swing.*;
4. public class ColorChooserExample extends JFrame implements ActionListener {
5. JButton b;
6. Container c;
7. ColorChooserExample(){
8. c=getContentPane();
9. c.setLayout(new FlowLayout());
10. b=new JButton("color");
11. b.addActionListener(this);
12. c.add(b);
13. }
14. public void actionPerformed(ActionEvent e) {
15. Color initialcolor=Color.RED;
16. Color color=JColorChooser.showDialog(this,"Select a color",initialcolor);
17. c.setBackground(color);
18. }
19.
20. public static void main(String[] args) {
21. ColorChooserExample ch=new ColorChooserExample();
22. ch.setSize(400,400);
23. ch.setVisible(true);
24. ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
25. }
26. }
Output:
Java JColorChooser Example with ActionListener
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
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. b.setBounds(200,250,100,30);
12. ta=new JTextArea();
13. ta.setBounds(10,10,300,200);
14. b.addActionListener(this);
15. f.add(b);f.add(ta);
16. f.setLayout(null);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20. public void actionPerformed(ActionEvent e){
21. Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
22. ta.setBackground(c);
23. }
24. public static void main(String[] args) {
25. new ColorChooserExample();
26. }
27. }
Output:
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 javax.swing.JTabbedPane class.
1. public class JTabbedPane extends JComponent implements Serializable, Accessible, SwingConstants
Commonly used Constructors:
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a d
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a s
JTabbedPane(int tabPlacement, int tabLayoutPolicy) Creates an empty TabbedPane with a s
Java JTabbedPane Example
1. import javax.swing.*;
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. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new JTabbedPane();
12. tp.setBounds(50,50,200,200);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new TabbedPaneExample();
23. }}
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
JSlider(int orientation) creates a slider with the specified orientation set by either JS
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 value) creates a horizontal slider using the given min, max and valu
JSlider(int orientation, int min, int max, int creates a slider using the given orientation, min, max and va
value)
Commonly used Methods of JSlider class
Method Description
public void setMinorTickSpacing(int n) is used to set the minor tick spa
public void setMajorTickSpacing(int n) is used to set the major tick spa
public void setPaintTicks(boolean b) is used to determine whether tic
public void setPaintLabels(boolean b) is used to determine whether lab
public void setPaintTracks(boolean b) is used to determine whether tra
Java JSlider Example
1. import javax.swing.*;
2. public class SliderExample1 extends JFrame{
3. public SliderExample1() {
4. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
5. JPanel panel=new JPanel();
6. panel.add(slider);
7. add(panel);
8. }
9.
10. public static void main(String s[]) {
11. SliderExample1 frame=new SliderExample1();
12. frame.pack();
13. frame.setVisible(true);
14. }
15. }
Output:
Java JSlider Example: painting ticks
1. import javax.swing.*;
2. public class SliderExample extends JFrame{
3. public SliderExample() {
4. JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
5. slider.setMinorTickSpacing(2);
6. slider.setMajorTickSpacing(10);
7. slider.setPaintTicks(true);
8. slider.setPaintLabels(true);
9.
10. JPanel panel=new JPanel();
11. panel.add(slider);
12. add(panel);
13. }
14. public static void main(String s[]) {
15. SliderExample frame=new SliderExample();
16. frame.pack();
17. frame.setVisible(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 javax.swing.JSpinner 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 w
JSpinner(SpinnerModel model) It is used to construct a spinner for a given model.
Commonly used Methods:
Method Description
void addChangeListener(ChangeListener listener) It is used to add a listener to the list that is n
Object getValue() It is used to return the current value of the m
Java JSpinner Example
1. import javax.swing.*;
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. spinner.setBounds(100,100,50,30);
12. f.add(spinner);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
Java JSpinner Example with ChangeListener
imp
1. ort javax.swing.*;
2. import javax.swing.event.*;
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. label.setHorizontalAlignment(JLabel.CENTER);
8. label.setSize(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. spinner.setBounds(100,100,50,30);
16. f.add(spinner); f.add(label);
17. f.setSize(300,300);
18. f.setLayout(null);
19. f.setVisible(true);
20. spinner.addChangeListener(new ChangeListener() {
21. public void stateChanged(ChangeEvent e) {
22. label.setText("Value : " + ((JSpinner)e.getSource()).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 javax.swing.JDialog class.
1. public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer
Commonly used Constructors:
Constructor Description
JDialog() It is used to create a modeless dialog witho
JDialog(Frame owner) It is used to create a modeless dialog with s
JDialog(Frame owner, String title, boolean modal) It is used to create a dialog with the specifie
Java JDialog Example
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
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. d.setLayout( new FlowLayout() );
10. JButton b = new JButton ("OK");
11. b.addActionListener ( new ActionListener()
12. {
13. public void actionPerformed( ActionEvent e )
14. {
15. DialogExample.d.setVisible(false);
16. }
17. });
18. d.add( new JLabel ("Click button to continue."));
19. d.add(b);
20. d.setSize(300,300);
21. d.setVisible(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 an
JPanel(boolean isDoubleBuffered) It is used to create a new JPanel with FlowLayout and th
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layo
Java JPanel Example
1. import java.awt.*;
2. import javax.swing.*;
3. public class PanelExample {
4. PanelExample()
5. {
6. JFrame f= new JFrame("Panel Example");
7. JPanel panel=new JPanel();
8. panel.setBounds(40,80,200,200);
9. panel.setBackground(Color.gray);
10. JButton b1=new JButton("Button 1");
11. b1.setBounds(50,100,80,30);
12. b1.setBackground(Color.yellow);
13. JButton b2=new JButton("Button 2");
14. b2.setBounds(100,100,80,30);
15. b2.setBackground(Color.green);
16. panel.add(b1); panel.add(b2);
17. f.add(panel);
18. f.setSize(400,400);
19. f.setLayout(null);
20. f.setVisible(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 javax.swing.JFileChooser class.
1. public class JFileChooser extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JFileChooser() Constructs a JFileChooser pointing to
JFileChooser(File currentDirectory) Constructs a JFileChooser using the g
JFileChooser(String currentDirectoryPath) Constructs a JFileChooser using the g
Java JFileChooser Example
1. import javax.swing.*;
2. import java.awt.event.*;
3. import java.io.*;
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. open.addActionListener(this);
12. file=new JMenu("File");
13. file.add(open);
14. mb=new JMenuBar();
15. mb.setBounds(0,0,800,20);
16. mb.add(file);
17. ta=new JTextArea(800,800);
18. ta.setBounds(0,20,800,800);
19. add(mb);
20. add(ta);
21. }
22. public void actionPerformed(ActionEvent e) {
23. if(e.getSource()==open){
24. JFileChooser fc=new JFileChooser();
25. int i=fc.showOpenDialog(this);
26. if(i==JFileChooser.APPROVE_OPTION){
27. File f=fc.getSelectedFile();
28. String filepath=f.getPath();
29. try{
30. BufferedReader br=new BufferedReader(new FileReader(filepath));
31. String s1="",s2="";
32. while((s1=br.readLine())!=null){
33. s2+=s1+"\n";
34. }
35. ta.setText(s2);
36. br.close();
37. }catch (Exception ex) {ex.printStackTrace(); }
38. }
39. }
40. }
41. public static void main(String[] args) {
42. FileChooserExample om=new FileChooserExample();
43. om.setSize(500,500);
44. om.setLayout(null);
45. om.setVisible(true);
46. om.setDefaultCloseOperation(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 and Type Class Description
protected class JToggleButton.AccessibleJToggleButton This class implements a
static class JToggleButton.ToggleButtonModel The ToggleButton mode
Constructors
Constructor Description
JToggleButton() It creates an initially unselected toggle bu
JToggleButton(Action a) It creates a toggle button where propertie
JToggleButton(Icon icon) It creates an initially unselected toggle bu
JToggleButton(Icon icon, boolean selected) It creates a toggle button with the specifie
JToggleButton(String text) It creates an unselected toggle button wit
JToggleButton(String text, boolean selected) It creates a toggle button with the specifie
JToggleButton(String text, Icon icon) It creates a toggle button that has the spe
JToggleButton(String text, Icon icon, boolean selected) It creates a toggle button with the specifie
Methods
Modifier and Type Method Description
AccessibleContext getAccessibleContext() It gets the AccessibleContext associated wit
String getUIClassID() It returns a string that specifies the name o
protected String paramString() It returns a string representation of this JTo
void updateUI() It resets the UI property to a value from the
JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import javax.swing.JToggleButton;
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. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("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 Type Class Description
protected class JToolBar.AccessibleJToolBar This class implements access
static class JToolBar.Separator A toolbar-specific separator.
Constructors
Constructor Description
JToolBar() It creates a new tool bar; orientation de
JToolBar(int orientation) It creates a new tool bar with the specif
JToolBar(String name) It creates a new tool bar with the specif
JToolBar(String name, int orientation) It creates a new tool bar with a specifie
Useful Methods
Modifier and Type Method Description
JButton add(Action a) It adds a new JButton whi
protected void addImpl(Component comp, Object If a JButton is being added
constraints, int index)
void addSeparator() It appends a separator of
protected createActionChangeListener(JButton b) It returns a properly confi
PropertyChangeListener changes to the Action occu
desired.
protected JButton createActionComponent(Action a) Factory method which crea
ToolBarUI getUI() It returns the tool bar's cu
void setUI(ToolBarUI ui) It sets the L&F object that
void setOrientation(int o) It sets the orientation of th
Java JToolBar Example
1. import java.awt.BorderLayout;
2. import java.awt.Container;
3. import javax.swing.JButton;
4. import javax.swing.JComboBox;
5. import javax.swing.JFrame;
6. import javax.swing.JScrollPane;
7. import javax.swing.JTextArea;
8. import javax.swing.JToolBar;
9.
10. public class JToolBarExample {
11. public static void main(final String args[]) {
12. JFrame myframe = new JFrame("JToolBar Example");
13. myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. JToolBar toolbar = new JToolBar();
15. toolbar.setRollover(true);
16. JButton button = new JButton("File");
17. toolbar.add(button);
18. toolbar.addSeparator();
19. toolbar.add(new JButton("Edit"));
20. toolbar.add(new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-3", "Opt-4" }));
21. Container contentPane = myframe.getContentPane();
22. contentPane.add(toolbar, BorderLayout.NORTH);
23. JTextArea textArea = new JTextArea();
24. JScrollPane mypane = new JScrollPane(textArea);
25. contentPane.add(mypane, BorderLayout.EAST);
26. myframe.setSize(450, 250);
27. myframe.setVisible(true);
28. }
29. }
Output:
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
JViewport.setViewPosition() method.
Nested Classes
Modifier and Type Class Description
protected class JViewport.AccessibleJViewport This class implements acce
protected class JViewport.ViewListener A listener for the view.
Fields
Modifier and Type Field Description
static int BACKINGSTORE_SCROLL_MODE It draws viewport contents into an offscreen im
protected Image backingStoreImage The view image used for a backing store.
static int BLIT_SCROLL_MODE It uses graphics.copyArea to implement scrollin
protected boolean isViewSizeSet True when the viewport dimensions have been
protected Point lastPaintPosition The last viewPosition that we've painted, so we
protected boolean scrollUnderway The scrollUnderway flag is used for components
static int SIMPLE_SCROLL_MODE This mode uses the very simple method of redr
Constructor
Constructor Description
JViewport() Creates a JViewport.
Methods
Modifier and Type Method Description
void addChangeListener(ChangeListener It adds a ChangeListener to the
l) viewport's extent size has chang
protected LayoutManager createLayoutManager() Subclassers can override this to
protected createViewListener() It creates a listener for the view
Jviewport.ViewListener
int getScrollMode() It returns the current scrolling m
Component getView() It returns the JViewport's one ch
Point getViewPosition() It returns the view coordinates t
there's no view.
Dimension getViewSize() If the view's size hasn't been ex
current size.
void setExtentSize(Dimension newExtent) It sets the size of the visible par
void setScrollMode(int mode) It used to control the method of
void setViewSize(Dimension newSize) It sets the size of the view.
JViewport Example
1. import java.awt.BorderLayout;
2. import java.awt.Color;
3. import java.awt.Dimension;
4. import javax.swing.JButton;
5. import javax.swing.JFrame;
6. import javax.swing.JLabel;
7. import javax.swing.JScrollPane;
8. import javax.swing.border.LineBorder;
9. public class ViewPortClass2 {
10. public static void main(String[] args) {
11. JFrame frame = new JFrame("Tabbed Pane Sample");
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13.
14. JLabel label = new JLabel("Label");
15. label.setPreferredSize(new Dimension(1000, 1000));
16. JScrollPane jScrollPane = new JScrollPane(label);
17.
18. JButton jButton1 = new JButton();
19. jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
20. jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
21. jScrollPane.setViewportBorder(new LineBorder(Color.RED));
22. jScrollPane.getViewport().add(jButton1, null);
23.
24. frame.add(jScrollPane, BorderLayout.CENTER);
25. frame.setSize(400, 150);
26. frame.setVisible(true);
27. }
28. }
Output:
Java JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame 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 Type Class Description
protected class JFrame.AccessibleJFrame This class implements accessi
Fields
Modifier and Type Field Description
protected accessibleContext The accessible context property.
AccessibleContext
static int EXIT_ON_CLOSE The exit application default window close oper
protected JRootPane rootPane The JRootPane instance that manages the con
glassPane.
protected boolean rootPaneCheckingEnabled If true then calls to add and setLayout will be
Constructors
Constructor Description
JFrame() It constructs a new frame that is initially invisible.
JFrame(GraphicsConfiguration gc) It creates a Frame in the specified GraphicsConfigu
JFrame(String title) It creates a new, initially invisible Frame with the s
JFrame(String title, GraphicsConfiguration gc) It creates a JFrame with the specified title and the
Useful Methods
Modifier and Method Description
Type
protected void addImpl(Component comp, Object constraints, int Adds the specified child Co
index)
protected createRootPane() Called by the constructor m
JRootPane
protected void frameInit() Called by the constructors
void setContentPane(Containe contentPane) It sets the contentPane pr
static void setDefaultLookAndFeelDecorated(boolean Provides a hint as to whet
defaultLookAndFeelDecorated) decorations (such as borde
look and feel.
void setIconImage(Image image) It sets the image to be dis
void setJMenuBar(JMenuBar menubar) It sets the menubar for th
void setLayeredPane(JLayeredPane layeredPane) It sets the layeredPane pr
JRootPane getRootPane() It returns the rootPane ob
TransferHandler getTransferHandler() It gets the transferHandle
JFrame Example
1. import java.awt.FlowLayout;
2. import javax.swing.JButton;
3. import javax.swing.JFrame;
4. import javax.swing.JLabel;
5. import javax.swing.Jpanel;
6. public class JFrameExample {
7. public static void main(String s[]) {
8. JFrame frame = new JFrame("JFrame Example");
9. JPanel panel = new JPanel();
10. panel.setLayout(new FlowLayout());
11. JLabel label = new JLabel("JFrame By Example");
12. JButton button = new JButton();
13. button.setText("Button");
14. panel.add(label);
15. panel.add(button);
16. frame.add(panel);
17. frame.setSize(200, 300);
18. frame.setLocationRelativeTo(null);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. frame.setVisible(true);
21. }
22. }
Output
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 AccessibleContext as
AccessibleContext
protectedEventListenerList listenerList A list of event listeners fo
static String TOOL_TIP_TEXT_KEY The comment to display w
tip", "flyover help", or "fl
protected ComponentUI ui The look and feel delegat
static int UNDEFINED_CONDITION It is a constant used by s
static int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT It is a constant used for r
invoked when the receivi
the focused component.
static int WHEN_FOCUSED It is a constant used for r
invoked when the compo
static int WHEN_IN_FOCUSED_WINDOW Constant used for registe
when the receiving comp
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 compon
void setFont(Font font) It sets the font for this component.
void setMaximumSize(Dimension It sets the maximum size of this componen
maximumSize)
void setMinimumSize(Dimension It sets the minimum size of this componen
minimumSize)
protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this co
void setVisible(boolean aFlag) It makes the component visible or invisible
void setForeground(Color fg) It sets the foreground color of this compon
String getToolTipText(MouseEvent event) It returns the string to be used as the toolt
Container getTopLevelAncestor() It returns the top-level ancestor of this com
component has not been added to any con
TransferHandler getTransferHandler() It gets the transferHandler property.
Java JComponent Example
1. import java.awt.Color;
2. import java.awt.Graphics;
3. import javax.swing.JComponent;
4. import javax.swing.JFrame;
5. class MyJComponent extends JComponent {
6. public void paint(Graphics g) {
7. g.setColor(Color.green);
8. g.fillRect(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. JFrame.setDefaultLookAndFeelDecorated(true);
16. JFrame frame = new JFrame("JComponent Example");
17. frame.setSize(300,200);
18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19. // add the JComponent to main frame
20. frame.add(com);
21. frame.setVisible(true);
22. }
23. }
Output:
Java JLayeredPane
The JLayeredPane class is used to add depth to swing container. It is used to provide a third dimension for
positioning component and divide the depth-range into several different layers.
JLayeredPane class declaration
1. public class JLayeredPane extends JComponent implements Accessible
Commonly used Constructors:
Constructor Description
JLayeredPane It is used to create a new JLayeredPane
Commonly used Methods:
Method Description
int getIndexOf(Component c) It is used to return the index of the specified Compone
int getLayer(Component c) It is used to return the layer attribute for the specified
int getPosition(Component c) It is used to return the relative position of the compon
Java JLayeredPane Example
1. import javax.swing.*;
2. import java.awt.*;
3. public class LayeredPaneExample extends JFrame {
4. public LayeredPaneExample() {
5. super("LayeredPane Example");
6. setSize(200, 200);
7. JLayeredPane pane = getLayeredPane();
8. //creating buttons
9. JButton top = new JButton();
10. top.setBackground(Color.white);
11. top.setBounds(20, 20, 50, 50);
12. JButton middle = new JButton();
13. middle.setBackground(Color.red);
14. middle.setBounds(40, 40, 50, 50);
15. JButton bottom = new JButton();
16. bottom.setBackground(Color.cyan);
17. bottom.setBounds(60, 60, 50, 50);
18. //adding buttons on pane
19. pane.add(bottom, new Integer(1));
20. pane.add(middle, new Integer(2));
21. pane.add(top, new Integer(3));
22. }
23. public static void main(String[] args) {
24. LayeredPaneExample panel = new LayeredPaneExample();
25. panel.setVisible(true);
26. }
27. }
Output:
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 Type Field Description
static int LIVE_DRAG_MODE It indicates that the entire contents of the item be
static int OUTLINE_DRAG_MODE It indicates that an outline only of the item being
Constructor
Constructor Description
JDesktopPane() Creates a new JDesktopPane.
Java JDesktopPane Example
1. import java.awt.BorderLayout;
2. import java.awt.Container;
3. import javax.swing.JDesktopPane;
4. import javax.swing.JFrame;
5. import javax.swing.JInternalFrame;
6. import javax.swing.JLabel;
7. public class JDPaneDemo extends JFrame
8. {
9. public JDPaneDemo()
10. {
11. CustomDesktopPane desktopPane = new CustomDesktopPane();
12. Container contentPane = getContentPane();
13. contentPane.add(desktopPane, BorderLayout.CENTER);
14. desktopPane.display(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, true);
33.
34. jframe.setBounds(x, y, 250, 85);
35. Container c1 = jframe.getContentPane( ) ;
36. c1.add(new JLabel("I love my country"));
37. dp.add( jframe );
38. jframe.setVisible(true);
39. y += 85;
40. }
41. }
42. }
Output:
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 and Class Description
Type
protected JEditorPane.AccessibleJEditorPane This class implements accessibilit
class
protected JEditorPane.AccessibleJEditorPaneHTML This class provides support for Ac
class installed in this JEditorPane is an
protected JEditorPane.JEditorPaneAccessibleHypertextSupport What's returned by AccessibleJEd
class
Fields
Modifier and Field Description
Type
static String HONOR_DISPLAY_PROPERTIES Key for a client property used to indicate whether the
a font or foreground color is not specified in the style
static String W3C_LENGTH_UNITS Key for a client property used to indicate whether w3
Constructors
Constructor Description
JEditorPane() It creates a new JEditorPane.
JEditorPane(String url) It creates a JEditorPane based on a string cont
JEditorPane(String type, String text) It creates a JEditorPane that has been initialize
JEditorPane(URL initialPage) It creates a JEditorPane based on a specified U
Useful Methods
Modifier and Method Description
Type
void addHyperlinkListener(HyperlinkListener Adds a hyperlink listener for notificat
listener) entered.
protected createDefaultEditorKit() It creates the default editor kit (Plain
EditorKit
void setText(String t) It sets the text of this TextComponen
the content type of this editor.
void setContentType(String type) It sets the type of content that this e
void setPage(URL page) It sets the current URL being displaye
void read(InputStream in, Object desc) This method initializes from a stream
void scrollToReference(String reference) It scrolls the view to the given refere
for the URL being displayed).
void setText(String t) It sets the text of this TextComponen
the content type of this editor.
String getText() It returns the text contained in this T
void read(InputStream in, Object desc) This method initializes from a stream
JEditorPane Example
1. import javax.swing.JEditorPane;
2. import javax.swing.JFrame;
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. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. myFrame.setSize(400, 200);
15. JEditorPane myPane = new JEditorPane();
16. myPane.setContentType("text/plain");
17. myPane.setText("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 stude
nts days.");
20. myFrame.setContentPane(myPane);
21. myFrame.setVisible(true);
22. }
23. }
Output:
JEditorPane Example: using HTML
1. import javax.swing.JEditorPane;
2. import javax.swing.JFrame;
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. myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. myFrame.setSize(400, 200);
15. JEditorPane myPane = new JEditorPane();
16. myPane.setContentType("text/html");
17. myPane.setText("<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 stude
nts days.</p>");
20. myFrame.setContentPane(myPane);
21. myFrame.setVisible(true);
22. }
23. }
Output:
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
the vertical and horizontal scroll bar policies (respectively).
JScrollPane(Component)
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 paramete
constants defined in ScrollPaneConstants: UPPER_LE
Component getCorner(String) LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER
UPPER_TRAILING_CORNER.
void setViewportView(Component) Set the scroll pane's client.
JScrollPane Example
1. import java.awt.FlowLayout;
2. import javax.swing.JFrame;
3. import javax.swing.JScrollPane;
4. import javax.swing.JtextArea;
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. frame.setSize(500, 500);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18.
19. // set flow layout for the frame
20. frame.getContentPane().setLayout(new FlowLayout());
21.
22. JTextArea textArea = new JTextArea(20, 20);
23. JScrollPane scrollableTextArea = new JScrollPane(textArea);
24.
25. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
26. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
27.
28. frame.getContentPane().add(scrollableTextArea);
29. }
30. public static void main(String[] args) {
31.
32.
33. javax.swing.SwingUtilities.invokeLater(new Runnable() {
34.
35. public void run() {
36. createAndShowGUI();
37. }
38. });
39. }
40. }
Output:
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 Type Class Description
protected class JSplitPane.AccessibleJSplitPane This class implements acce
Useful Fields
Modifier and Type Field Description
static String BOTTOM It use to add a Compon
static String CONTINUOUS_LAYOUT_PROPERTY Bound property name f
static String DIVIDER It uses to add a Compo
static int HORIZONTAL_SPLIT Horizontal split indicate
protected int lastDividerLocation Previous location of the
protected Component leftComponent The left or top compon
static int VERTICAL_SPLIT Vertical split indicates
protected Component rightComponent The right or bottom co
protected int orientation How the views are split
Constructors
Constructor Description
JSplitPane() It creates a new Js
horizontally, using
JSplitPane(int newOrientation) It creates a new Js
JSplitPane(int newOrientation, boolean newContinuousLayout) It creates a new Js
JSplitPane(int newOrientation, boolean newContinuousLayout, Component It creates a new Js
newLeftComponent, Component newRightComponent) with the specified c
JSplitPane(int newOrientation, Component newLeftComponent, Component It creates a new Js
newRightComponent) components.
Useful Methods
Modifier and Type Method Description
protected void addImpl(Component comp, Object constraints, int index) It cdds the
AccessibleContext getAccessibleContext() It gets the A
int getDividerLocation() It returns th
int getDividerSize() It returns th
Component getBottomComponent() It returns th
Component getRightComponent() It returns th
SplitPaneUI getUI() It returns th
boolean isContinuousLayout() It gets the c
boolean isOneTouchExpandable() It gets the o
void setOrientation(int orientation) It gets the o
JSplitPane Example
1. import java.awt.FlowLayout;
2. import java.awt.Panel;
3. import javax.swing.JComboBox;
4. import javax.swing.JFrame;
5. import javax.swing.JSplitPane;
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. frame.setSize(300, 300);
12. frame.setVisible(true);
13. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14. // set flow layout for the frame
15. frame.getContentPane().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. panel1.add(box1);
22. Panel panel2 = new Panel();
23. panel2.add(box2);
24. JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
25. // JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
26. // panel1, panel2);
27. frame.getContentPane().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. javax.swing.SwingUtilities.invokeLater(new Runnable() {
33. public void run() {
34. createAndShow();
35. }
36. });
37. }
38. }
Output:
Java JTextPane
JTextPane is a subclass of JEditorPane class. JTextPane is used for styled document with embedded
images and components. It is text component that can be marked up with attributes that are represented
graphically. JTextPane uses a DefaultStyledDocument as its default model.
Constructors
Constructor Description
JTextPane() It creates a new JTextPane.
JtextPane(StyledDocument doc) It creates a new JTextPane, with a specified d
Useful Methods
Modifier and Type Method Description
Style addStyle(String nm, Style parent) It adds a new style in
AttributeSet getCharacterAttributes() It fetches the charact
StyledDocument getStyledDocument() It fetches the model
void setDocument(Document doc) It associates the edit
void setCharacterAttributes(AttributeSet attr, boolean replace) It applies the given a
void removeStyle(String nm) It removes a named
void setEditorKit(EditorKit kit) It sets the currently i
void setStyledDocument(StyledDocument doc) It associates the edit
JTextPane Example
1. import java.awt.BorderLayout;
2. import java.awt.Color;
3. import java.awt.Container;
4. import javax.swing.JFrame;
5. import javax.swing.JScrollPane;
6. import javax.swing.JTextPane;
7. import javax.swing.text.BadLocationException;
8. import javax.swing.text.Document;
9. import javax.swing.text.SimpleAttributeSet;
10. import javax.swing.text.StyleConstants;
11. public class JTextPaneExample {
12. public static void main(String args[]) throws BadLocationException {
13. JFrame frame = new JFrame("JTextPane Example");
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. Container cp = frame.getContentPane();
16. JTextPane pane = new JTextPane();
17. SimpleAttributeSet attributeSet = new SimpleAttributeSet();
18. StyleConstants.setBold(attributeSet, true);
19.
20. // Set the attributes before adding text
21. pane.setCharacterAttributes(attributeSet, true);
22. pane.setText("Welcome");
23.
24. attributeSet = new SimpleAttributeSet();
25. StyleConstants.setItalic(attributeSet, true);
26. StyleConstants.setForeground(attributeSet, Color.red);
27. StyleConstants.setBackground(attributeSet, Color.blue);
28.
29. Document doc = pane.getStyledDocument();
30. doc.insertString(doc.getLength(), "To Java ", attributeSet);
31.
32. attributeSet = new SimpleAttributeSet();
33. doc.insertString(doc.getLength(), "World", attributeSet);
34.
35. JScrollPane scrollPane = new JScrollPane(pane);
36. cp.add(scrollPane, BorderLayout.CENTER);
37.
38. frame.setSize(400, 300);
39. frame.setVisible(true);
40. }
41. }
Output
Java JRootPane
JRootPane is a lightweight container used behind the scenes by JFrame, JDialog, JWindow, JApplet, and
JInternalFrame.
Nested Classes
Modifier and Type Class Description
protected class JRootPane.AccessibleJRootPane This class implements accessibility support
protected class JRootPane.RootLayout A custom layout manager that is responsibl
Fields
Modifier and Type Field Description
static int COLOR_CHOOSER_DIALOG Constant used for the windowDecorationStyle prop
protected JButton contentPane The content pane.
protected Container defaultButton The button that gets activated when the pane has
occurs.
protected JMenuBar menuBar The menu bar.
protected glassPane The glass pane that overlays the menu bar and con
Component
static int ERROR_DIALOG Constant used for the windowDecorationStyle prop
Constructor
Constructor Description
JRootPane() Creates a JRootPane, setting up its glassPane, layeredPane, and contentPane.
Useful Methods
Modifier and Type Method Description
protected void addImpl(Component comp, Object constraints, int Overridden to enforce th
index)
void addNotify() Notifies this component
protected Container createContentPane() It is called by the constr
protected createGlassPane() It called by the construc
Component
AccessibleContext getAccessibleContext() It gets the AccessibleCo
JButton getDefaultButton() It returns the value of th
void setContentPane(Container content) It sets the content pane
pane.
void setDefaultButton(JButton defaultButton) It sets the defaultButton
JRootPane.
void setJMenuBar(JMenuBar menu) It adds or changes the m
JRootPane Example
1. import javax.swing.JButton;
2. import javax.swing.JFrame;
3. import javax.swing.JMenu;
4. import javax.swing.JMenuBar;
5. import javax.swing.JRootPane;
6.
7. public class JRootPaneExample {
8. public static void main(String[] args) {
9. JFrame f = new JFrame();
10. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11. JRootPane root = f.getRootPane();
12.
13. // Create a menu bar
14. JMenuBar bar = new JMenuBar();
15. JMenu menu = new JMenu("File");
16. bar.add(menu);
17. menu.add("Open");
18. menu.add("Close");
19. root.setJMenuBar(bar);
20.
21. // Add a button to the content pane
22. root.getContentPane().add(new JButton("Press Me"));
23.
24. // Display the UI
25. f.pack();
26. f.setVisible(true);
27. }
28. }
Output
How to use ToolTip in Java Swing
You can create a tool tip for any JComponent with setToolTipText() method. This method is used to set
up a tool tip for the component.
For example, to add tool tip to PasswordField, you need to add only one line of code:
1. field.setToolTipText("Enter your Password");
Simple ToolTip Example
1. import javax.swing.*;
2. public class ToolTipExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Password Field Example");
5. //Creating PasswordField and label
6. JPasswordField value = new JPasswordField();
7. value.setBounds(100,100,100,30);
8. value.setToolTipText("Enter your Password");
9. JLabel l1=new JLabel("Password:");
10. l1.setBounds(20,100, 80,30);
11. //Adding components to frame
12. f.add(value); f.add(l1);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
How to change TitleBar icon in Java AWT and Swing
The setIconImage() method of Frame class is used to change the icon of Frame or Window. It changes the
icon which is displayed at the left side of Frame or Window.
The Toolkit class is used to get instance of Image class in AWT and Swing.
Toolkit class is the abstract super class of every implementation in the Abstract Window Toolkit(AWT).
Subclasses of Toolkit are used to bind various components. It inherits Object class.
Example to change TitleBar icon in Java AWT
1. import java.awt.*;
2. class IconExample {
3. IconExample(){
4. Frame f=new Frame();
5. Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
6. f.setIconImage(icon);
7. f.setLayout(null);
8. f.setSize(400,400);
9. f.setVisible(true);
10. }
11. public static void main(String args[]){
12. new IconExample();
13. }
14. }
Output:
Example to change TitleBar icon in Java Swing
1. import javax.swing.*;
2. import java.awt.*;
3. class IconExample {
4. IconExample(){
5. JFrame f=new JFrame();
6. Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");
7. f.setIconImage(icon);
8. f.setLayout(null);
9. f.setSize(200,200);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. new ToolkitExample();
14. }
15. }
Output:
How to make an executable jar file in Java
The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An executable
jar file calls the main method of the class if you double click it.
To create the executable jar file, you need to create .mf file, also known as manifest file.
Download this example
Creating manifest file
To create manifest file, you need to write Main-Class, then colon, then space, then classname then enter.
For example:
myfile.mf
1. Main-Class: First
As you can see, the mf file starts with Main-Class colon space class name. Here, class name is First.
In mf file, new line is must after the class name.
Creating executable jar file using jar tool
The jar tool provides many switches, some of them are as follows:
1. -c creates new archive file
2. -v generates verbose output. It displays the included or extracted resource on the standard output.
3. -m includes manifest information from the given mf file.
4. -f specifies the archive file name
5. -x extracts files from the archive file
Now, let's write the code to generated the executable jar using mf file.
You need to write jar then swiches then mf_file then jar_file then .classfile as given below:
1. jar -cvmf myfile.mf myjar.jar First.class
It is shown in the image given below:
Now it will create the executable jar file. If you double click on it, it will call the main method of the First
class.
We are assuming that you have created any window based application using AWT or SWING. If you don't,
you can use the code given below:
First.java
1. import javax.swing.*;
2. public class First{
3. First(){
4. JFrame f=new JFrame();
5.
6. JButton b=new JButton("click");
7. b.setBounds(130,100,100, 40);
8.
9. f.add(b);
10.
11. f.setSize(300,400);
12. f.setLayout(null);
13. f.setVisible(true);
14.
15. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16. }
17. public static void main(String[] args) {
18. new First();
19. }
20. }
Example of digital clock in swing:
1. import javax.swing.*;
2. import java.awt.*;
3. import java.text.*;
4. import java.util.*;
5. public class DigitalWatch implements Runnable{
6. JFrame f;
7. Thread t=null;
8. int hours=0, minutes=0, seconds=0;
9. String timeString = "";
10. JButton b;
11.
12. DigitalWatch(){
13. f=new JFrame();
14.
15. t = new Thread(this);
16. t.start();
17.
18. b=new JButton();
19. b.setBounds(100,100,100,50);
20.
21. f.add(b);
22. f.setSize(300,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26.
27. public void run() {
28. try {
29. while (true) {
30.
31. Calendar cal = Calendar.getInstance();
32. hours = cal.get( Calendar.HOUR_OF_DAY );
33. if ( hours > 12 ) hours -= 12;
34. minutes = cal.get( Calendar.MINUTE );
35. seconds = cal.get( Calendar.SECOND );
36.
37. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
38. Date date = cal.getTime();
39. timeString = formatter.format( date );
40.
41. printTime();
42.
43. t.sleep( 1000 ); // interval given in milliseconds
44. }
45. }
46. catch (Exception e) { }
47. }
48.
49. public void printTime(){
50. b.setText(timeString);
51. }
52.
53. public static void main(String[] args) {
54. new DigitalWatch();
55.
56.
57. }
58. }
next>><<prev
Displaying graphics in swing:
java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified wi
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the defa
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the p
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is u
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified c
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified
Example of displaying graphics in swing:
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class DisplayGraphics extends Canvas{
5.
6. public void paint(Graphics g) {
7. g.drawString("Hello",40,40);
8. setBackground(Color.WHITE);
9. g.fillRect(130, 30,100, 80);
10. g.drawOval(30,130,50, 60);
11. setForeground(Color.RED);
12. g.fillOval(130,130,50, 60);
13. g.drawArc(30, 200, 40,50,90,60);
14. g.fillArc(30, 130, 40,50,180,40);
15.
16. }
17. public static void main(String[] args) {
18. DisplayGraphics m=new DisplayGraphics();
19. JFrame f=new JFrame();
20. f.add(m);
21. f.setSize(400,400);
22. //f.setLayout(null);
23. f.setVisible(true);
24. }
25.
26. }
next>><<prev
Displaying image in swing:
For displaying image, we can use the method drawImage() of Graphics class.
Syntax of drawImage() method:
1. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is u
Example of displaying image in swing:
1. import java.awt.*;
2. import javax.swing.JFrame;
3.
4. public class MyCanvas extends Canvas{
5.
6. public void paint(Graphics g) {
7.
8. Toolkit t=Toolkit.getDefaultToolkit();
9. Image i=t.getImage("p3.gif");
10. g.drawImage(i, 120,100,this);
11.
12. }
13. public static void main(String[] args) {
14. MyCanvas m=new MyCanvas();
15. JFrame f=new JFrame();
16. f.add(m);
17. f.setSize(400,400);
18. f.setVisible(true);
19. }
20.
21. }