Swing - SPLessons

Swing Models

Chapter 14

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Models

Swing Models

shape Description

Swing Models, Programmers developed a Swing to overcome the drawbacks of AWT, so Swing became the extension of the AWT. Swing consists of more components compared to AWT. Each component will consists of it’s own model and functionality. Swing Box(Toolkit) uses Model View Controller. Swing Models Box will use state models and data models.

If developer does not provide the model to the selected component then by default swing API will attach the default model. For instance just look at the following example where developer has created the default model to the selected button.

public JButton(String text, Icon icon) {
  setModel(new DefaultButtonModel());// default model will be created at the constructor of the component
   init(text, icon);// initializing the parameters
}

Button

shape Example

Developer can perform model on the various components like radio buttons, check buttons. The following example describes how to implement model on JButton and state of the selected button also. Below is the source code of a button example

ButtonEx.java

package swing;//create a pacakge

import java.awt.Container;//import all the required pacakges 
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.DefaultButtonModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ButtonEx extends JFrame {//created a class ButtonEx that should extend JFrame

    private JButton okbtn;//created buttom
    private JLabel enabledLbl;//created a label
    private JLabel pressedLbl;//created a label
    private JLabel armedLbl;//created a label
    private JCheckBox cb;//created check box

    public ButtonEx() {

        initUI();//method
    }

    private void initUI() {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        okbtn = new JButton("OK");//created OK button
        okbtn.addChangeListener(new DisabledChangeListener());//ChangeListener will be performed on the OK button and it focuses on the state of the button also.

        cb = new JCheckBox();
        cb.setAction(new CheckBoxAction());//check box state and action will be performed

        enabledLbl = new JLabel("Enabled: true");//depends on the mode it will work
        pressedLbl = new JLabel("Pressed: false");
        armedLbl = new JLabel("Armed: false");

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createParallelGroup()
                .addGroup(gl.createSequentialGroup()
                        .addComponent(okbtn)
                        .addGap(80)
                        .addComponent(cb))
                .addGroup(gl.createParallelGroup()
                        .addComponent(enabledLbl)
                        .addComponent(pressedLbl)
                        .addComponent(armedLbl))
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addGroup(gl.createParallelGroup()
                        .addComponent(okbtn)
                        .addComponent(cb))
                .addGap(40)
                .addGroup(gl.createSequentialGroup()
                        .addComponent(enabledLbl)
                        .addComponent(pressedLbl)
                        .addComponent(armedLbl))
        );

        pack();

        setTitle("ButtonModel");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
    private class DisabledChangeListener implements ChangeListener {

        @Override
        public void stateChanged(ChangeEvent e) {

            DefaultButtonModel model = (DefaultButtonModel) okbtn.getModel();//if any model is not there automatically it can reserve. 

            if (model.isEnabled()) {
                enabledLbl.setText("Enabled: true");
            } else {
                enabledLbl.setText("Enabled: false");
            }

            if (model.isArmed()) {
                armedLbl.setText("Armed: true");
            } else {
                armedLbl.setText("Armed: false");
            }

            if (model.isPressed()) {
                pressedLbl.setText("Pressed: true");
            } else {
                pressedLbl.setText("Pressed: false");
            }
        }
    }
    
    private class CheckBoxAction extends AbstractAction {
        
        public CheckBoxAction() {
            super("Disabled");
        }

        @Override
        public void actionPerformed(ActionEvent e) {//action will be performed depends on the selected event.
            if (okbtn.isEnabled()) {
                okbtn.setEnabled(false);//depends on the user requirement it works.
            } else {
                okbtn.setEnabled(true);//to enable the OK button
            }
        }
    }

    public static void main(String[] args) {//here main method have been written.

        EventQueue.invokeLater(new Runnable() {//The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe.
        {
         
            @Override
            public void run() {
                SimpleWindow sw = new SimpleWindow();//created the instance
                sw.setVisible(true);//to visible the window
            }
        });
    }
}

            @Override
            public void run() {
                ButtonEx ex = new ButtonEx();
                ex.setVisible(true);//it should always be true otherwise window will not be displayed.
            }
        });
    }
}

Create a class that should extend from Jframe, create one button, three labels, check box.

public class ButtonEx extends JFrame {
 
    private JButton okbtn;
    private JLabel enabledLbl;
    private JLabel pressedLbl;
    private JLabel armedLbl;
    private JCheckBox cb;

Create a constructor that should be same as class name and write one method inside the constructor.

public ButtonEx() {
 
        initUI();//method
    }

Create OK button and add changeListener to the button.ChangeListener will be performed on the OK button and it focuses on the state of the button also.

okbtn = new JButton("OK");
        okbtn.addChangeListener(new DisabledChangeListener());

Create the labels that are enabled, pressed, armed and create the gap between the components.

enabledLbl = new JLabel("Enabled: true");
        pressedLbl = new JLabel("Pressed: false");
        armedLbl = new JLabel("Armed: false");
gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

Create the another class DisabledChangeListener that should implement ChangeListener and create default OK button.

private class DisabledChangeListener implements ChangeListener
DefaultButtonModel model = (DefaultButtonModel) okbtn.getModel();

Create a class CheckBoxAction that should extend Abstraction and create a constructor with class name.

private class CheckBoxAction extends AbstractAction {
         
        public CheckBoxAction() {
            super("Disabled");
        }

When click on OK button it will be enabled and when click on disabled button all function will be disabled.

if (okbtn.isEnabled()) {
                okbtn.setEnabled(false);//depends on the user requirement it works.
            } else {
                okbtn.setEnabled(true);

Output:

After executing  above code is  successfully, output will be as follows.Here user can enable and disable the the OK button ,if it is enable then Boolean functions will be visible, otherwise another option is there that is disabled.

ListModel

shape Example

In Swing some components will consists of two models like JList , those model have been explained in the following examples such as ListModel and ListSelectionModel.Below is the source code of a ListModel example.

ListModelEx.java

package swing;//create a package

import java.awt.Container;//import all the required pacakges
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import static javax.swing.GroupLayout.Alignment.CENTER;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class ListModelEx extends JFrame {//create a class that should extend the JFrame

    private DefaultListModel model;
    private JList list;//created a list componet
    private JButton remallbtn;//created a button
    private JButton addbtn;//created a button
    private JButton renbtn;//created a button
    private JButton delbtn;//created a button

    public ListModelEx() {

        initUI();//method
    }

    private void createList() {

        model = new DefaultListModel();//created a default model
        model.addElement("SPlessons");//added element as SPlessons
        model.addElement("iToolsInfo");//added element as iToolsInfo
        model.addElement("Software");//added element as Software
        model.addElement("Hardware");//added element as Hardware
        model.addElement("Employee");//added element as Employee

        list = new JList(model);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        list.addMouseListener(new MouseAdapter() {//MouseListener needs to be implemented when cursor is moved or pressed

            @Override
            public void mouseClicked(MouseEvent e) {

                if (e.getClickCount() == 2) {
                    int index = list.locationToIndex(e.getPoint());
                    Object item = model.getElementAt(index);
                    String text = JOptionPane.showInputDialog("Rename item", item);
                    String newitem = null;
                    if (text != null) {//it means atleast there is one character other than white spaces
                        newitem = text.trim();
                    } else {
                        return;
                    }

                    if (!newitem.isEmpty()) {
                        model.remove(index);
                        model.add(index, newitem);
                        ListSelectionModel selmodel = list.getSelectionModel();
                        selmodel.setLeadSelectionIndex(index);
                    }
                }
            }
        });
    }

    private void createButtons() {

        remallbtn = new JButton("Remove All");
        addbtn = new JButton("Add");
        renbtn = new JButton("Rename");
        delbtn = new JButton("Delete");

        addbtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                String text = JOptionPane.showInputDialog("Add a new item");
                String item = null;

                if (text != null) {
                    item = text.trim();
                } else {
                    return;
                }

                if (!item.isEmpty()) {
                    model.addElement(item);//to add the element
                }
            }
        });

        delbtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent event) {

                ListSelectionModel selmodel = list.getSelectionModel();
                int index = selmodel.getMinSelectionIndex();
                if (index >= 0) {
                    model.remove(index);//to remove the element
                }
            }

        });

        renbtn.addActionListener(new ActionListener() {//ActionListener needs to be implemented when event has happened.

            @Override
            public void actionPerformed(ActionEvent e) {

                ListSelectionModel selmodel = list.getSelectionModel();
                int index = selmodel.getMinSelectionIndex();
                if (index == -1) {
                    return;
                }

                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = null;

                if (text != null) {
                    newitem = text.trim();
                } else {
                    return;
                }

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);//new item will be added
                }
            }
        });

        remallbtn.addActionListener(new ActionListener() {//to listen the selected event ActionListener interface is needed.
            @Override
            public void actionPerformed(ActionEvent e) {//depends on the selected event.
                model.clear();
            }
        });

    }

    private void initUI() {

        createList();
        createButtons();
        JScrollPane scrollpane = new JScrollPane(list);

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createSequentialGroup()
                .addComponent(scrollpane)
                .addGroup(gl.createParallelGroup()
                        .addComponent(addbtn)
                        .addComponent(renbtn)
                        .addComponent(delbtn)
                        .addComponent(remallbtn))
        );

        gl.setVerticalGroup(gl.createParallelGroup(CENTER)
                .addComponent(scrollpane)
                .addGroup(gl.createSequentialGroup()
                        .addComponent(addbtn)
                        .addComponent(renbtn)
                        .addComponent(delbtn)
                        .addComponent(remallbtn))
        );

        gl.linkSize(addbtn, renbtn, delbtn, remallbtn);

        pack();

        setTitle("JList models");//created the title
        setLocationRelativeTo(null);//it means the window should be in center of the screen
        setDefaultCloseOperation(EXIT_ON_CLOSE);//needs to close the window
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                ListModelEx ex = new ListModelEx();
                ex.setVisible(true);
            }
        });
    }
}

Create a class that should extend from JFrame and create buttons by using JButton component.

public class ListModelEx extends JFrame {//create a class that should extend the JFrame
 
    private DefaultListModel model;
    private JList list;
    private JButton remallbtn;
    private JButton addbtn;
    private JButton renbtn;
    private JButton delbtn;

Create the default list model and add the elements into the model such as message dialogues.

model = new DefaultListModel();
        model.addElement("SPlessons");
        model.addElement("iToolsInfo");
        model.addElement("Software");
        model.addElement("Hardware");
        model.addElement("Employee");

Set the selection mode ,where only single selection of an element is possible and add the listener to the list.This step is common to all operations such as Add, Rename, Delete, Remove All.

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 
        list.addMouseListener(new MouseAdapter()

Set the JOptionPane component,when click on Add button it displays input dialogue that is Add a new item.

String text = JOptionPane.showInputDialog("Add a new item");

Output:

After executing the above code successfully, output will be as follows with four buttons and one text field.

In the output Add, Rename, Delete, Remove All elements will have their importance, where user can add and delete elements depends on the availability of the option. Following image shows that how to add the elements.

Summary

shape Points

  • Swing Models – User can create own model also like custom models.
  • Swing Models – JList is the component of the swing and consists of two models.
  • Swing Models – In Swing no need to maintain protocols to write the code, it depends on the requirement of the client.
  • Swing Models – Document model is the good instance to discret the data.