GUI Controls with Java Swing

0
127

Text Fields

The object of a JTextField class is a text component that allows the editing of a single line text. It inherits the JTextComponent class. JTextField is a part of javax.swing package. The class JTextField is a component that allows editing of a single line of text. JTextField inherits the JTextComponent class and uses the interface SwingConstants.

The constructor of the class are : 

  1. JTextField() : constructor that creates a new TextField
  2. JTextField(int columns) : constructor that creates a new empty TextField with specified number of columns.
  3. JTextField(String text) : constructor that creates a new empty text field initialized with the given string.
  4. JTextField(String text, int columns) : constructor that creates a new empty textField with the given string and a specified number of columns .
  5. JTextField(Document doc, String text, int columns) : constructor that creates a textfield that uses the given text storage model and the given number of columns.

The methods for Java JTextField are:

  1. setColumns(int n) :set the number of columns of the text field.
  2. setFont(Font f) : set the font of text displayed in text field.
  3. addActionListener(ActionListener l) : set an ActionListener to the text field.
  4. int getColumns() :get the number of columns in the textfield.

Sample program for JTextField

Source code:

import java.awt.*;

import javax.swing.*;

 class Textexample extends JFrame {

     public static void main(String[]args) {

     JFrame f= new JFrame(“TextField Example”);  

         JTextField t1,t2;  

         t1=new JTextField(“Hello world”);  

         t1.setBounds(50,100, 200,30);  

         t2=new JTextField(“Java Awt”);  

         t2.setBounds(50,150, 200,30);  

         f.add(t1); f.add(t2);  

         f.setSize(400,400);  

         f.setLayout(null);  

         f.setVisible(true);  

     }

}

Output:

GUI Controls

Password Field

PasswordField is a part of javax.swing package . The class JPasswordField is a component that allows editing of a single line of text where the view indicates that something was typed by does not show the actual characters. JPasswordField inherits the JTextField class in javax.swing package.

Constructors of the class are : 

  1. JPasswordField(): constructor that creates a new PasswordField
     
  2. JPasswordField(int columns) : constructor that creates a new empty PasswordField with specified number of columns.
  3. JPasswordField(String Password) : constructor that creates a new empty Password field initialized with the given string.
  4. JPasswordField(String Password, int columns) : constructor that creates a new empty PasswordField with the given string and a specified number of columns .
     
  5. JPasswordField(Document doc, String Password, int columns) : constructor that creates a Passwordfield that uses the given text storage model and the given number of columns.
     

The method used in password field are:

  1. char getEchoChar() : returns the character used for echoing in JPasswordField.
     
  2. setEchoChar(char c) : set the echo character for JPasswordField.
     
  3. String getPassword() : returns the text contained in JPasswordField.
     
  4. String getText() : returns the text contained in JPasswordField.

Sample Java Program to enter name and password

Source code:

import javax.swing.*;    

import java.awt.event.*;  

 class examplePass extends JFrame  {

public static void main(String[]args) {

JFrame f=new JFrame(“Password Field Example”);    

    final JLabel label = new JLabel();            

    label.setBounds(20,150, 200,50); 

    final JPasswordField value = new JPasswordField();   

    value.setBounds(100,75,100,30);

    JLabel l1=new JLabel(“Username:”);    

        l1.setBounds(20,20, 80,30);    

        JLabel l2=new JLabel(“Password:”);    

        l2.setBounds(20,75, 80,30);    

        JButton b = new JButton(“Login”);  

        b.setBounds(100,120, 80,30);    

        final JTextField text = new JTextField();  

        text.setBounds(100,20, 100,30);    

                f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);  

                f.setSize(300,300);    

                f.setLayout(null);    

                f.setVisible(true);  

                b.addActionListener(new ActionListener() {  

                public void actionPerformed(ActionEvent e) {       

                  String data = “Username ” + text.getText();  

                  data += “, Password: ”   

                  + new String(value.getPassword());   

                  label.setText(data);          

                }  

            });   

}

}

Output

GUI Controls

TextArea

JTextArea is a part of java Swing package . It represents a multi line area that displays text. It is used to edit the text .

JTextArea inherits JComponent class. The text in JTextArea can be set to different available fonts and can be appended to new text . A text area can be customized to the need of user .

Constructors of JTextArea are:

  1. JTextArea() : constructs a new blank text area .
  2. JTextArea(String s) : constructs a new text area with a given initial text.
  3. JTextArea(int row, int column) : constructs a new text area with a given number of rows and columns.
  4. JTextArea(String s, int row, int column) : constructs a new text area with a given number of rows and columns and a given initial text.

The most commonly used methods for JTextArea are:

  1. append(String s) : appends the given string to the text of the text area.
  2. getLineCount() : get number of lines in the text of text area.
  3. setFont(Font f) : sets the font of text area to the given font.
  4. setColumns(int c) : sets the number of columns of the text area to given integer.
  5. setRows(int r) : sets the number of rows of the text area to given integer.
  6. getColumns() : get the number of columns of text area.
  7. getRows() : get the number of rows of text area.

Sample program to demonstrate JTextArea

Source code:

// Java Program to create a simple JTextArea

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

class Areaexample extends JFrame implements ActionListener {

// JFrame

static JFrame f;

// JButton

static JButton b;

// label to display text

static JLabel l;

// text area

static JTextArea jt;

// default constructor

Areaexample()

{

}

// main class

public static void main(String[] args)

{

// create a new frame to store text field and button

f = new JFrame(“textfield”);

// create a label to display text

l = new JLabel(“nothing entered”);

// create a new button

b = new JButton(“submit”);

// create a object of the text class

Areaexample te = new Areaexample();

// addActionListener to button

b.addActionListener(te);

// create a text area, specifying the rows and columns

jt = new JTextArea(10, 10);

JPanel p = new JPanel();

// add the text area and button to panel

p.add(jt);

p.add(b);

p.add(l);

f.add(p);

// set the size of frame

f.setSize(300, 300);

f.show();

}

// if the button is pressed

public void actionPerformed(ActionEvent e)

{

String s = e.getActionCommand();

if (s.equals(“submit”)) {

// set the text of the label to the text of the field

l.setText(jt.getText());

}

}

}

Output:

GUI Controls

ScrollPane

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.

The constructors used in Java Scrollpane are:

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

Sample Program of Java ScrollPane

Source Code:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

 class option2 {

public static void main(String[]args) {

JFrame Jf = new JFrame();

     Jf.setBounds(100,200,700,500);

     Jf.setVisible(true);

     Jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     Jf.setLayout(new FlowLayout());

     JTextArea ta=new JTextArea(10,15);

     JScrollPane sp = new JScrollPane(ta);

     sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

     sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

     Jf.add(sp);

}

}

Output:

GUI Controls

Labels

The object of the Label 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 a programmer but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create a label, we need to create the object of Label class.

Declaration of Label class

public class Label extends Component implements Accessible  

Sample Program to demonstrate Label 

Source Code:

import java.awt.*;

import javax.swing.JFrame;    

public class labelexample {    

public static void main(String args[]){   

    // creating the object of Frame class and Label class  

JFrame jf= new JFrame(“Label Example”);

 jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Label l1, l2;    

    // initializing the labels   

    l1 = new Label (“First Label.”);   

    l2 = new Label (“Second Label.”);   

    // set the location of label  

    l1.setBounds(50, 100, 100, 30);    

    l2.setBounds(50, 150, 100, 30);  

    // adding labels to the frame    

    jf.add(l1);  

    jf.add(l2);   

    // setting size, layout and visibility of frame   

    jf.setSize(400,400);    

    jf.setLayout(null);    

    jf.setVisible(true);    

}    

}    

Output:

GUI Controls

CheckBoxes and RadioButtons

CheckBoxes

The Checkbox 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”.

Class Declaration of Java CheckBox

public class Checkbox extends Component implements ItemSelectable, Accessible  

Sample Program to Demonstrate CheckBox in Java

Source Code:

import java.awt.Color;

import java.awt.Container;

import javax.swing.JCheckBox;

import javax.swing.JFrame;

public class CheckboxExample {

public static void main(String[]args) {

     JFrame jf = new JFrame(“Example”);

     jf.setBounds(100,100,500,700);

     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     Container c= jf.getContentPane();

     c.setLayout(null);

     c.setBackground(Color.PINK);

     JCheckBox c1= new JCheckBox(“BSc.CSIT”);

         JCheckBox c2= new JCheckBox(“BCA”);

         JCheckBox c3= new JCheckBox(“BBS”);

         c1.setBounds(75,150,100,30);

         c2.setBounds(75,200,100,30);

         c3.setBounds(75,250,100,30);

         c.add(c1);

         c.add(c2);

         c.add(c3);

         c1.setSelected(true);//select one option in default

         c3.setEnabled(false);

         jf.setVisible(true);

}

}

Output:

GUI Controls

RadioButtons

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.

Class Declaration for JRadioButton 

public class JRadioButton extends JToggleButton implements Accessible 

Sample Program for RadioButton in Java

Source Code:

import java.awt.Color;

import java.awt.Container;

import javax.swing.ButtonGroup;

import javax.swing.JFrame;

import javax.swing.JRadioButton;

public class RadioButtonExample {

public static void main(String[]args) {

     JFrame jf = new JFrame(“Example”);

     jf.setBounds(100,100,500,700);

     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     Container c= jf.getContentPane();

     c.setLayout(null);

     c.setBackground(Color.PINK);

     JRadioButton r1 = new JRadioButton(“male”);

     r1.setBounds(75,50,100,30);

     c.add(r1);

     JRadioButton r2 = new JRadioButton(“female”);

     r2.setBounds(75,100,100,30);

     c.add(r2);

     //r1.setEnabled(false);

     ButtonGroup bg= new ButtonGroup();//only one will be selected

     bg.add(r1);

     bg.add(r2);

     jf.setVisible(true);

}

}

Output:

GUI Controls

Borders,ComboBoxes and Sliders in Java

Borders

For a window having multiple groups of radio buttons it is essential to visually indicate which buttons are grouped. Swing provides a set of useful borders for this  purpose. We can apply border to any component that extends JComponent. The most common usage is to place a border around panel and fill that panel with other user interface elements such as radio buttons.

In order to add border we should call static method of the BorderFactory to create border. Following styles can be chosen to create border.

  • Lowered bevel
  • Raised bevel
  • Etched
  • Line
  • Matte
  • Empty

Sample Program to demonstrate border

Source code:

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.FlowLayout;

import java.awt.LayoutManager;

import javax.swing.BorderFactory;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.border.Border;

public class BorderExample {

   public static void main(String[] args) {

      createWindow();

   }

   private static void createWindow() {    

      JFrame frame = new JFrame(“Border”);

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      createUI(frame);

      frame.setSize(560, 200);      

      frame.setLocationRelativeTo(null);  

      frame.setVisible(true);

   }

   private static void createUI(JFrame frame){

      //Create a border

      Border blackline = BorderFactory.createLineBorder(Color.black);

      JPanel panel = new JPanel();

      LayoutManager layout = new FlowLayout();  

      panel.setLayout(layout);       

      JPanel panel1 = new JPanel();

      String spaces = ”                   “;

      panel1.add(new JLabel(spaces + “Border to JPanel” + spaces));  

      panel1.setBorder(blackline);

      panel.add(panel1);

      frame.getContentPane().add(panel, BorderLayout.CENTER);    

   }

}

Output:

GUI Controls

ComboBoxes

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .

Constructor of the JComboBox are: 

  1. JComboBox() : creates a new empty JComboBox .
  2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items from specified ComboBoxModel
  3. JComboBox(E [ ] i) : creates a new JComboBox with items from specified array.
  4. JComboBox(Vector items) : creates a new JComboBox with items from the specified vector

Sample Program to demonstrate ComboBoxes in Java

Source code:

import java.awt.Color;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

public class ComboBoxExample {

public static void main(String[]args) {

     JFrame jf = new JFrame(“Example”);

     jf.setBounds(100,100,500,700);

     jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     Container c= jf.getContentPane();

     c.setLayout(null);

     c.setBackground(Color.PINK);

     String values[] = {“CSIT”,”BCA”,”BASW”};

        JComboBox cb= new JComboBox(values);

        cb.setBounds(75,300,100,30);

        c.add(cb);

        JButton b1= new JButton(“submit”);

        b1.setBounds(200,300,100,30);

        c.add(b1);

        JLabel l1 = new JLabel();

        l1.setBounds(300,400,100,30);

        l1.setForeground(Color.BLUE);

        c.add(l1);

        b1.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

        String item=(String) cb.getSelectedItem();

        l1.setText(item);

        }

        });

        jf.setVisible(true);

}

}

Output:

GUI Controls

Sliders

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 constructor in JSlider are:

ConstructorDescription
JSlider()creates a slider with the initial value of 50 and range of 0 to 100.
JSlider(int orientation)creates a slider with the specified orientation set by either JSlider.HORIZONTAL or JSlider.VERTICAL with the range 0 to 100 and initial value 50.
JSlider(int min, int max)creates a horizontal slider using the given min and max.
JSlider(int min, int max, int value)creates a horizontal slider using the given min, max and value.
JSlider(int orientation, int min, int max, int value)creates a slider using the given orientation, min, max and value.

Sample Program to demonstrate sliders in Java

Source code:

import javax.swing.*;  

public class SliderExample extends JFrame{  

public SliderExample() {  

JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);  

JPanel panel=new JPanel();  

panel.add(slider);  

add(panel);  

}  

public static void main(String s[]) {  

SliderExample frame=new SliderExample();  

frame.pack();  

frame.setVisible(true);  

}  

}  

Output:

GUI Controls

Read more about menu components in Java.

Facebook Comments