Swings Java
Swings Java
Swings Java
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.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the com
We can write the code of swing inside the main(), constructor or any other
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.}
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.
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.}}
Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.
Constructor Description
Methods Description
Output:
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.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text,
horizontalAlignment) image, and horizontal alignment.
Methods Description
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.
Constructor Description
Methods Description
Output:
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
Constructor Description
JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.
JTextArea(String s, int row, Creates a text area with the specified number of
int column) rows and columns that displays specified text.
Methods Description
void append(String s) It is used to append the given text to the end of the
document.
Output:
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.
Constructor Description
Output:
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.
Constructor Description
JCheckBox(String text, boolean Creates a check box with text and specifies whether
selected) or not it is initially selected.
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:
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.
Constructor Description
Methods Description
void setText(String s) It is used to set specified text on button.
Output:
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.
Constructor Description
Methods Description
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.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
Output:
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:
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.
Constructor Description
Methods Description
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.getSelectedValu
e();
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.
Constructor Description
Output:
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:
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.
Constructor Description
JScrollBar(int orientation, int value, int extent, int Creates a scrollbar with the sp
min, int max) minimum, and maximum.
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:
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.
Output:
Output:
Java JPopupMenu
PopupMenu can be dynamically popped up at specific position within a
component. It inherits the JComponent class.
Constructor Description
Output:
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
Constructor
Constructor Description
Methods
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.
Constructor Description
Method Description
Output:
Output:
Java JProgressBar
The JProgressBar class is used to display the progress of the task. It inherits
JComponent class.
Method Description
void setValue(int value) It is used to set the current value on the progress bar.
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.
Constructor Description
JTree(Object[] value) Creates a JTree with every element of the specified array as th
JTree(TreeNode root) Creates a JTree with the specified TreeNode as its root, which
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.
Method Description
Output:
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.
Constructor Description
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.
Constructor Description
JSlider(int min, int max) creates a horizontal slider using the given min and m
JSlider(int min, int max, int creates a horizontal slider using the given min, max a
value)
JSlider(int orientation, int min, creates a slider using the given orientation, min, max
int max, int value)
Method Description
Output:
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.
Constructor Description
Method Description
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.
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.
Constructor Description
Output:
Java JFileChooser
The object of JFileChooser class represents a dialog window from which the user
can select file. It inherits JComponent class.
Constructor Description
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
Constructors
Constructor Description
Methods
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 ItemLi
stener {
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
Constructors
Constructor Description
Useful Methods
Output: