Java4

 

Unit-IV

Event Handling

1.What is event ? Explain event handling in java?

Ans:

An object resides in a particular state until it is made to transit to the other state. This transition occurs due to an event.

e.g., pressing a key on the keyboard, moving the mouse, clicking on a button, etc.

The object which generates the event, is called event generator.

If a button is pressed for an operation, the button is the event  generator.

The object that is responsible for performing the task when the event occurs is called the event handler. There may be more than one event handlers for one single event generated;


2.Explain types of events in Java?

Ans:

ActionEvent Class

ActionEvent is an event which indicates that a component-defined action has occurred. This event is generated by a component (such as a Button) when the component-specific action occurs (such as a click).

 An actionEvent class is defined in Java as

public class ActionEvent extends AWTEvent

 

AdjustmentEvent Class

The adjustment events are generated by adjustable objects like scroll bar. There are some adjustment events defined by AdjustmentEvent class, identified by corresponding integer constants.

AdjustmentEvent class is defined in Java as,

public class AdjustmentEvent extends AWTEvent

 

KeyEvent Class

KeyEvent is an event which indicates that a keystroke occurred in a component. This low-level event is generated by a component object (such as a text field, Applet, frame) when a key is pressed, released, or typed.  There can be three types of key events, which are identified by integer constants. These are

 KEY_PRESSED (it is generated when any key is pressed)

 KEY_TYPED (it is generated if a valid unicode character could be generated)

 KEY_RELEASED (it is generated when any key is released)

This class is defined in Java as,

public class KeyEvent extends InputEvent

 

MouseEvent Class

It is an event which indicates that a mouse action occurred in a component. A mouse action occurs in a particular component if and only if the mouse cursor is over the defined part of the component’s bounds when the action happens. MouseEvent class is defined in Java as,

 

  1. void mouseReleased(MouseEvent e) : Mouse key is released
  2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
  3. void mouseExited(MouseEvent e) : Mouse exited the component
  4. void mouseEntered(MouseEvent e) : Mouse entered the component
  5. void mousepressed(MouseEvent e) : Mouse key is pressed

public class MouseEvent extends InputEvent

     

FocusEvent Class

This event is generated when a component gains or loses focus. There are two types of focus events: permanent and temporary. Permanent focus event occurs when the user explicitly changes focus from one component to other, e.g., by pressing the tab key. Temporary focus event occurs when the focus is lost due to operations like window being deactivated. In this case, when the window will again be activated, the focus will be on the same component.

FocusEvent class is defined as,

public class FocusEvent extends ComponentEvent

 

ItemEvent Class

It is an event which shows whether an item was selected or de-selected. This event is generated by an ItemSelectable object (such as a list), where the event is generated when an item of the list is either selected or de-selected.

ItemEvent class is defined as,

public class ItemEvent extends AWTEvent

 

TextEvent Class

This event indicates the change in the object’s text. This event is generated by an object (such as a TextComponent) whenever its text changes

TextEvent class is defined as,

public class TextEvent extends AWTEvent

 

WindowEvent When a window has changed its status.


3.Explain components and containers in java?

Ans:

A graphical user interface is developed with the help of graphical elements such as buttons, scrollbars, lists, and textfields. These elements are called components. These components are generally the source of events that allow the user to interact with the program .

A container contains components. Components are found within container. Containers are themselves components, thus they can be placed inside other components. A container has a layout manager that determines visual placement of component. Figure shows the hierarchy of different AWT classes in Java.

 

Component Class

 

The Component class, which is actually a subclass of the Object class and superclass of various classes such as Button, Label, CheckBox, RadioButton, Choice, Canvas, TextComponent, List, and ScrollBar.

Creating The Components

In order to have a particular component in a window, you must add that particular component to the window.Container class has a method, add(), for the purpose.        

Component add(Component ComObj)

The object of the Component, which is to be added, is passed as the argument to the above method.

 

If you wish to remove a Component from a window, you can use remove() method for the same.

void remove(Component ComObj)

In the above syntax, the object of the Component which is to be removed is passed as the argument to the above method.

 

Components as Event Generator

All the controls, except label, can generate events. The notifications for the events generated by these controls are received by the registered listeners. This notification helps the listeners in identifying the type of control that generated event.


4.Explain Various AWT Components in java?

Ans:

 

BUTTON

The Button can be created as below,

Button buttonName = new Button(Str);

 

buttonname is the name of the button object , str is  caption on the button.

 

Now the button need to be added to the applet, frame or any other container.

The syntax for it is as follows:

add(buttonname);

 

The constructors defined by button are

Button() throws HeadlessException   This creates a Button with no label displayed on it.

Button(String str)throws HeadLessException;  This creates a Button, displaying the string ‘str’ on it.

 

Methods

void setLabel(String str)  This is used for changing the button’s label text

String getLabel()             This is used and getting the label’s text

Methods of Button Class

void addActionListener(ActionListeneral)

Adds the specified action listener to receive action events from this button.

 

void removeActionListener(ActionListener al)

Removes the specified action listener so that it no longer receives action events from this button.

 

AccessibleContext getAccessibleContext()   Gets the AccessibleContext associated with this button.

 

String paramString()   Returns a string representing the state of this button.

 

void processEvent(AWTEvent awte)  Processes events on this button

 

void addNotify()   Creates the peer of the button.

 

 

Example Button Demonstration

/*<applet code = ButtonClass.class width = 400 height = 150></applet>*/

 import java.applet.*;

import java.awt.*;

 import java.awt.event.*;

 public class ButtonClass extends Applet implements ActionListener {

 Button red;

 Label hit;

public void init(){

 red = new Button("Red");

  hit = new Label("Hit Red Button to change the screen color");

 add(red);

 add(hit);

 red.addActionListener(this);

}

 public void actionPerformed(ActionEvent ae){

 String str = ae.getActionCommand();

 if (str.equals("Red")) {

 setBackground(Color.red);

 }

  repaint();

 }

 }

Output

LABEL

Labels consist of a text string for display only and they never call an action method. The constructors responsible for creating labels are given in Table



Example uses the second type of constructor mentioned in Table

Label labelname = new Label("This label is for demonstration.");

 

Here, ‘labelname’ is  label’s object, the string ‘This label is for demonstration’ displayed on it.

 

A label can be justified LEFT, RIGHT, or CENTERED.

Label labelname = new Label("This label is for demonstration.", Label.RIGHT);

 

labelname.setText("This is new text.");    Used to can change the text of a label

 

String labelText = labelname.getText();    Used to get the label’s text

 

We can change the alignment or get the alignment of a label with the methods shown as follows:

labelname.setAlignment(Label.CENTER);

or

int labelAlignment = labelname.getAlignment();

 

Example An Applet Illustrating a Simple Label

 /*<applet code = "LabelClass.java" width = 350 height = 100></applet>*/

 import java.applet.*;

 import java.awt.*;

 public class LabelClass extends Applet

{

public void init()

{

 Label firstLabel = new Label("Welcome To India ");

 add(firstLabel);

 }

}

Output:

CHECKBOX

Checkboxes are used as on-off or yes-no switches ,if you click on an unchecked checkbox, it will get checked and if  you click on the checked box, it will get unchecked.

The checkboxes are the objects of Checkbox class, which support the following constructors:

Checkbox()

Checkbox(String str)

 

Checkbox(String str, boolean on)

Checkbox(String str, CheckBoxGroup cbg, boolean on)

 

The following line will create a checkbox with Names as a label, null as a placeholder for a group argument, and false to indicate that it is not selected:

 

Checkbox names = new Checkbox("Names", null, false);

Once you create the Checkbox, just add it to the applet (or other container) by entering the following command:

add(names);

where names is the Checkbox name.

Methods belonging to the Checkbox class

String getLabel()  Returns string in the form of Checkbox text.

boolean getState()  Returns boolean in the form of true or false, depending on whether the Checkbox is selected or unselected.

CheckboxGroup getCheckboxGroup()  Returns the associated checkbox’s group.

void setCheckboxGroup (CheckboxGroup ckbg) Sets this checkbox’s group to the specifi ed checkbox group.

void setLabel(String label)  We can change the Checkbox label and set it to the argument,‘label’.

void setState(boolean state)  Changes the checkbox’s state to true (for selected) or false (for unselected).

 

Example Demonstration of Checkboxes

/*<applet code=CheckboxClass.class width=400 height=100></applet>*/

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class CheckboxClass extends Applet implements ActionListener {

Button submit;

Checkbox name1;

Checkbox name2;

public void init(){

name1 = new Checkbox ("Apple",null,true);

name2 = new Checkbox ("Samsung",null,false);

Font f = new Font ("Arial",Font.ITALIC,14);

submit = new Button("SUBMIT");

add(name1);   

add(name2);   

add(submit);

submit.addActionListener(this);         }

public void actionPerformed(ActionEvent ae)          

{

String str = ae.getActionCommand();

if (str.equals("SUBMIT"))     

repaint();

}

public void paint (Graphics g)           

{

//g.setFont(f);

g.setColor(Color.blue);

if (name1.getState())              

g.drawString("Apple",50,60);

if (name2.getState())              

g.drawString("Samsung",50,80);

}

}

Output:


RADIO BUTTONS

 

Radio buttons, which are also called checkbox groups, are a special kind of checkboxes, where within a particular group, only one box can be selected at a time. The CheckboxGroup class is used to group together a set of checkboxes .Checkbox groups are objects of type CheckboxGroup class. There is only one constructor (the default constructor) which creates an empty group. The following line will create a checkbox group, named fruits:

CheckboxGroup fruits = new CheckboxGroup();

Once you create the checkbox group, add the individual checkboxes to that group.

add(new Checkbox("mango", fruits, false));

add(new Checkbox("papaya", fruits, false));

add(new Checkbox("guava", fruits, false));

add(new Checkbox("apple", fruits, true));

The first argument is the radio button label, the second argument is the group of which it is a part of, and the third is the state, true or false, depending on whether the button is selected or not.

 

Some of these methods are

 

void setLabel(String str)

String getLabel()

boolean getState()

void setState(boolean b)

CheckboxGroup getCheckboxGroup()

 

Example Demonstration of Radio Button

/*<applet code = "RadioDemo.class" width = 300 height = 200></applet>*/

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class RadioDemo extends Applet implements ItemListener{

Checkbox red, green;

CheckboxGroup cbg;

public void init(){

add(new Label("The 2 radio buttons will change the screen color."));

cbg = new CheckboxGroup();

red = new Checkbox("Red",cbg,false);

green = new Checkbox("Green",cbg,false);

add(new Label("You can select only one radio button. That is  used to change the screen color."));

add(red);

add(green);

red.addItemListener(this);

green.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie){

String str = (String) ie.getItem();

if (str.equals("Red")){

setBackground(Color.red);

}

else  {

setBackground(Color.green);

}

repaint();

}}

Output:




5.Explain types of Container class with example?

Ans:

Containers allow us to organize components into manageable groups which are extremely important in order to create a good user interface.

A component in the AWT can only be used if it is held within a container. The AWT provides four container classes: Panel, Window, Dialog, and Frame.

Panel

Panel is a window that does not contain a title bar or a menu bar.  It is a generic container for holding components. It does not add any new method; it simply implements the container.

The definition of the Panel class is as follows:

 

public class Panel extends Container implements Accessible

 

The Panel class is a direct subclass of the Container class. Components (such as label and button) can be added to the panel object by using the add() method.

Constructors of Panel Class

Panel()     Creates a new panel using the default layout manager.

Panel(LayoutManager layout)    Creates a new panel with the specified layout.

 

The following steps are followed while creating a panel:

Panel panel = new Panel();                // Create the panel

panel.add(someComponent);             // Add components to panel by using add() method

panel.add(someOtherComponent);

 

Window

This class creates a top-level window. Top-level window means that it is not contained within any other object. A Window object is a window with no borders and no menubar . The default layout for a window is BorderLayout.It has the following signature:

 

public class Window extends Container implements Accessible

 

Frame

It is a top-level window with a border and title. An instance of the Frame class may have a menu bar, title bar, and borders.  If you are not creating an applet, then you will be most likely creating a Frame window.

The constructors responsible for creating a Frame are

Frame()     // simply creates a Frame window without any title

Frame(String title)   // creates a Frame with the title specified as string in the argument.

Methods

void setSize(int width, int height)  It is used to set the dimensions of the window. The new dimension in the form of width and height is passed as argument.

void setSize(Dimension size) Sets the size of the frame with dimension specified.

Dimension getSize()  It is used to make the window visible after its creation. The component is visible only if the argument passed is true

void setTitle(String title)  The title in the frame  window can be used to set to a new title, passed as argument.

Java Swing Components and Containers

A component is an independent visual control and Java Swing Framework contains a large set of these components which provide rich functionalities and allow high level of customization. They all are derived from JComponent class. All these components are lightweight components. This class provides some common functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc.

A container holds a group of components. It provides a space where a component can be managed and displayed. Containers are of two types:

  1. Top level Containers
    • It inherits Component and Container of AWT.
    • It cannot be contained within other containers.
    • Heavyweight.
    • Example: JFrame, JDialog, JApplet
  2. Lightweight Containers
    • It inherits JComponent class.
    • It is a general purpose container.
    • It can be used to organize related components together.
    • Example: JPanel

Swing JButton

JButton class provides functionality of a button. It is used to create button component. JButton class has three constuctors,

Example of JButton

In this example, we are creating two buttons using Jbutton class and adding them into Jframe container.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{

  testswing()
  {
    JButton bt1 = new JButton("Yes");             //Creating a Yes Button.
    JButton bt2 = new JButton("No");              //Creating a No Button.
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)     //setting close operation.
    setLayout(new FlowLayout());          //setting layout using FlowLayout object
    setSize(400, 400);                    //setting size of Jframe
    add(bt1);             //adding Yes button to frame.
    add(bt2);             //adding No button to frame.

    setVisible(true);
  }
  public static void main(String[] args)
  {
    new testswing();
  }
}

swing button example

JTextField

JTextField is used for taking input of single line of text. It is most widely used text component. It has three constructors,

JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

cols represent the number of columns in text field.

Example using JTextField

In this example, we are creating text field using JtextField class and adding into the jframe container.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
  public MyTextField()
  {
    JTextField jtf = new JTextField(20);  //creating JTextField.
    add(jtf);                             //adding JTextField to frame.
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    setVisible(true);
  }
  public static void main(String[] args)
  {
    new MyTextField();
  }
}

jtextfield example

JCheckBox

The JcheckBox class is used to create chekbox in swing framework. In this example, we are creating three checkboxes to get user response.

JCheckBox(String str)
using JCheckBox
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
  public Test()
  {
    JCheckBox jcb = new JCheckBox("yes");   //creating JCheckBox.
    add(jcb);                               //adding JCheckBox to frame.
    jcb = new JCheckBox("no");              //creating JCheckBox.
    add(jcb);                               //adding JCheckBox to frame.
    jcb = new JCheckBox("maybe");           //creating JCheckBox.
    add(jcb);                               //adding JCheckBox to frame.
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 400);
    setVisible(true);
  }
  public static void main(String[] args)
  {
    new Test();
  }
}

jcheckbox example

JRadioButton

Radio button is a group of related button in which only one can be selected. JRadioButton class is used to create a radio button in Frames. Following is the constructor for JRadioButton,

JRadioButton(String str)

Example using JRadioButton

To create radio button in swing, we used jradiobutton class. It is used to get single user response at a time.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
 public Test()
 {
  JRadioButton jcb = new JRadioButton("A");	//creating JRadioButton.
  add(jcb);					//adding JRadioButton to frame.
  jcb = new JRadioButton("B");			//creating JRadioButton.
  add(jcb);					//adding JRadioButton to frame.
  jcb = new JRadioButton("C");			//creating JRadioButton.
  add(jcb);					//adding JRadioButton to frame.
  jcb = new JRadioButton("none");
  add(jcb);
  setLayout(new FlowLayout());
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(400, 400);
  setVisible(true);
 }
 public static void main(String[] args)
 {
  new Test();
 }
}

jradiobutton example

JComboBox

Combo box is a combination of text fields and drop-down list.JComboBox component is used to create a combo box in Swing. Following is the constructor for JComboBox,

JComboBox(String arr[])

Example using JComboBox

Lets create an example to add combobox to the jframe . Combo box is used to create a drop-down menu. See the below example.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
 String name[] = {"Abhi","Adam","Alex","Ashkay"};  //list of name.
 public Test()
 {
  JComboBox jc = new JComboBox(name);	//initialzing combo box with list of name.
  add(jc);				//adding JComboBox to frame.
  setLayout(new FlowLayout());
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(400, 400);
  setVisible(true);
 }
 public static void main(String[] args)
 {
  new Test();
 }
}

jcombobox example

A program to change background color of a frame (Using Action Event)

import java.awt.*;  //importing awt package
import javax.swing.*;  //importing swing package
import java.awt.event.*;  //importing event package

//For an event to occur upon clicking the button, ActionListener interface should be implemented
class StColor extends JFrame implements ActionListener{

JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;

StColor(){

   frame = new JFrame("COLORS");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   panel = new JPanel();  //Creating a panel which is a container and will hold all the buttons
   panel.setSize(100, 50);

   b1 = new JButton("BLUE");  //Creating a button named BLUE
   b1.addActionListener(this);  //Registering the button with the listener

   b2 = new JButton("RED");  //Creating a button named RED
   b2.addActionListener(this);  //Registering the button with the listener

   b3 = new JButton("CYAN");//Creating a button named CYAN
   b3.addActionListener(this);//Registering the button with the listener

   b4 = new JButton("PINK");  //Creating a button named PINK
   b4.addActionListener(this);  //Registering the button with the listener

   b5 = new JButton("MAGENTA");  //Creating a button named MAGENTA
   b5.addActionListener(this);  //Registering the button with the listener

   //Adding buttons to the Panel
   panel.add(b1);
   panel.add(b2);
   panel.add(b3);
   panel.add(b4);
   panel.add(b5);

   frame.getContentPane().add(panel);  //adding panel to the frame
   frame.setSize(500,300);
   frame.setVisible(true);
   frame.setLayout(new FlowLayout());

}
//The below method is called whenever a button is clicked
    @Override
    public void actionPerformed(ActionEvent e) {

        //This method returns an object of the button on which the Event-
        Pressing of button initially occurred
        Object see = e.getSource();

        if(see ==(b1)){  //Checking if the object returned is of button1
        frame.getContentPane().setBackground(java.awt.Color.blue);  //changing the panel color to blue
        }
        if(see == b2){  //Checking if the object returned is of button2
            frame.getContentPane().setBackground(java.awt.Color.red);  //changing the panel color to red
        }
        if(see == b3){  //Checking if the object returned is of button3
        frame.getContentPane().setBackground(java.awt.Color.cyan);//changing the panel color to cyan
        }
        if(see == b4){  //Checking if the object returned is of button4
            frame.getContentPane().setBackground(java.awt.Color.pink);  //changing the panel color to pink
        }
        if(see == b5){  //Checking if the object returned is of button5
        frame.getContentPane().setBackground(java.awt.Color.magenta);  //changing the panel color to magenta
        }
    }
}

class Test {
    public static void main(String[] args) {
        StColor o = new StColor();
    }
}

Output:

Background Color of a frame

JLabel

In Java, Swingtoolkit contains a JLabel Class. It is under package javax.swing.JLabel class. It is used for placing text in a box. Only Single line text is allowed and the text can not be changed directly.

Declaration

public class JLabel extends JComponent implements SwingConstants, Accessible

The JLabel Contains 4 constructors. They are as following:

1. JLabel()

2. JLabel(String s)

3. JLabel(Icon i)

4. JLabel(String s, Icon i, int horizontalAlignment)

Example:

  
import javax.swing.*;  
class SLabelDemo1  
{  
public static void main(String args[])  
{  
    JFrame label_f= new JFrame("studytonight ==> Label Demo");  
    JLabel label_l1,label_l2;  
    label_l1=new JLabel("Welcome to studytonight.com");  
    label_l1.setBounds(50,50, 200,30);  
    label_l2=new JLabel("How are You?");  
    label_l2.setBounds(50,100, 200,30);  
    label_f.add(label_l1); 
    label_f.add(label_l2);  
    label_f.setSize(300,300);  
    label_f.setLayout(null);  
    label_f.setVisible(true);  
    }  
} 
  

swing-jlabel-demo swing-jlabel-demo

JTextArea

In Java, Swing toolkit contains a JTextArea Class. It is under package javax.swing.JTextArea class. It is used for displaying multiple-line text.

Declaration

public class JTextArea extends JTextComponent

The JTextArea Contains 4 constructors. They are as following:

1. JTextArea()

2. JTextArea(String s)

3. JTextArea(int row, int column)

4. JTextArea(String s, int row, int column)

Example:

Lets take an example to create text area in swing. We are using JtextArea class to create text area and adding to Jframe container.

  
import javax.swing.*;  
public class STextAreaDemo1  
{  
    STextAreaDemo1()
  {  
        JFrame textArea_f= new JFrame();  
        JTextArea textArea_area=new JTextArea("Welcome to studytonight.com ");  
        textArea_area.setBounds(10,30, 200,200);  
        textArea_f.add(textArea_area);  
        textArea_f.setSize(400,400);  
        textArea_f.setLayout(null);  
        textArea_f.setVisible(true);  
        }  
public static void main(String args[])  
    {  
   new STextAreaDemo1();  
}
}
  

swing-textarea-demo swing-textarea-demo


JPasswordField

In Java, Swing toolkit contains a JPasswordField Class. It is under package javax.swing.JPasswordField class. It is specifically used for password and it can be edited.

Declaration

public class JPasswordField extends JTextField

The JPasswordFieldContains 4 constructors. They are as following:

1. JPasswordField()

2. JPasswordField(int columns)

3. JPasswordField(String text)

4. JPasswordField(String text, int columns)

Example:

To generate a password component, swing provides Jpasswordfield that takes user input in encrypted format.

  
import javax.swing.*;    
public class SPasswordFieldDemo1 
{  
    public static void main(String[] args) 
  {    
  JFrame passWord_f=new JFrame("studytonight ==> Password Field Demo");    
  JPasswordField passWord_value = new JPasswordField();   
  JLabel passWord_l1=new JLabel("Password ");    
        passWord_l1.setBounds(20,100, 100,30);    
        passWord_value.setBounds(100,100,100,30);    
        passWord_f.add(passWord_value);  
  passWord_f.add(passWord_l1);  
        passWord_f.setSize(300,300);    
        passWord_f.setLayout(null);    
        passWord_f.setVisible(true);     
  }  
} 
  

swing-password swing-password

JTable

In Java, Swing toolkit contains a JTable Class. It is under package javax.swing.JTable class. It used to draw a table to display data.

The JTableContains 2 constructors. They are as following:

1. JTable()

2. JTable(Object[][] rows, Object[] columns)

Example:

We are creating an example to create a table using Jtable class and then add it to the Jframe container.

  
import javax.swing.*;    
public class STableDemo1 
{    
    JFrame table_f;    
    STableDemo1(){    
    table_f=new JFrame();    
    String table_data[][]={ {"1001","Cherry"}, {"1002","Candy"}, {"1003","Coco"}};    
    String table_column[]={"SID","SNAME"};         
    JTable table_jt=new JTable(table_data,table_column);    
    table_jt.setBounds(30,40,200,300);          
    JScrollPane table_sp=new JScrollPane(table_jt);    
    table_f.add(table_sp);          
    table_f.setSize(300,400);    
    table_f.setVisible(true);    
}     
public static void main(String[] args) 
{    
    new STableDemo1();    
}    
}  
  

swing-table swing-table

JList

In Java, Swing toolkit contains a JList Class. It is under package javax.swing.JList class. It is used to represent a list of items together. One or more than one item can be selected from the list.

Declaration

public class JList extends JComponent implements Scrollable, Accessible

The JListContains 3 constructors. They are as following:

1. JList()

2. JList(ary[] listData)

3. JList(ListModel<ary> dataModel)

Example:

In this example, we are creating a list of items using Jlist class. this list is used to show the items in a list format and get user input from the list of items. See the below example.

  
import javax.swing.*;  
public class SListDemo  
{  
     SListDemo()
  {  
        JFrame list_f= new JFrame();  
        DefaultListModel<String> list_l1 = new DefaultListModel<>();  
        list_l1.addElement("Red");  
        list_l1.addElement("Pink");  
        list_l1.addElement("Blue");  
        list_l1.addElement("Black");  
        JList<String> list1 = new JList<>(list_l1);  
        list1.setBounds(100,100, 75,75);  
        list_f.add(list1);  
        list_f.setSize(400,400);  
        list_f.setLayout(null);  
        list_f.setVisible(true);  
     }  
public static void main(String args[])  
    {  
  new SListDemo();  
    }
}
  

swing-list swing-list




No comments:

Post a Comment