Example of creating a label with image


Example of creating a label with image

To create a label with a given image, you create an instance of ImageIcon with the image path. And then you create the label based on this ImageIcon instance.

Here is the output of the demo application:

JLabel with Image

package jlabeldemo2;

import javax.swing.ImageIcon;

import javax.swing.JLabel;
import javax.swing.JFrame;

public classMain {
    public static void main(String[] args) {

        ImageIconicon = new ImageIcon("images/java.gif");
        JLabellabel = new JLabel(icon);

        JFrameframe = new JFrame("JLabel with Image Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setSize(300,200);
        frame.getContentPane().add(label);

        frame.setVisible(true);
    }
}
Advertisements

Inserting Rows in a JTable


After making a table, you  need to insert the data in a table. This tutorial helps you in how to insert rows in a JTable to specified locations or places according to its field. For inserting a row in JTable component, you will require to insert it into its table model object.

Description of program:

This program creates a table by using the JTable constructor that contains 3 rows and 2 columns. If  you want to insert a data at any location by using the insertRow() method that contains its position and data, you have to define the position and data of  the inserting data. All the data will be  add in this table model. This table model supports for inserting the data in the row by using the DefaultTableModel.

Description of code:

DefaultTableModel(Object data[][], Object col[]):
This method creates a DefaultTableModel and initializes the table that will pass in it. It takes the following arguments:

data: This is the object that adds in a table.
col: This is a column object that adds in the table.

insertRow(int row_index, Object data[]):
Above method is used to insert sa row at specified location. It takes the following parameters:

row_index: This is the index of row that to be added.
data: This is the data that have to add in the table.

Here is the code of program:

import javax.swing.*;
import javax.swing.table.*;

public class InsertRows{
  public static void main(String[] args) {
    new InsertRows();
  }

  public InsertRows(){
    JFrame frame = new JFrame("Inserting rows in the table!");
    JPanel panel = new JPanel();
    String data[][] {{"Vinod","100"},{"Raju","200"},{"Ranju","300"}};
    String col[] {"Name","code"};
    DefaultTableModel model = new DefaultTableModel(data,col);
    JTable table = new JTable(model);
    //Insert first position
    model.insertRow(0,new Object[]{"Ranjan","50"});
    //Insert 4 position
    model.insertRow(3,new Object[]{"Amar","600"});
    //Insert last position
    model.insertRow(table.getRowCount(),new Object[]{"Sushil","600"});
    panel.add(table);
    frame.add(panel);
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}

Download this example.

Output of program:

Before inserting data in the JTable

After inserting data in the JTable

Creating a JTable Component


Now you can easily create a JTable component. Here, the procedure for creating a JTable component is given with the brief description of JTable and it’s components.

JTable: The JTabel component is more flexible Java Swing component that allows the user to store, show and edit the data in tabular format. It is a user-interface component that represents the data of  two-dimensional tabular format. The Java swing implements tables by using the JTable class and a subclass of JComponent.

For learning complete JTable component you have to learn following parts:

  • JTable
  • Rendering
  • Table model
  • Observable event model
  • Tool tips

Rendering: In computer program, the rendering is a process that generates an image from a model. Model is a specification of three dimensional objects.

Table model: All tables contains of  its data from an object that implements the TableModel interface of java swing package. The TableModel interface uses the methods of JTable class that integrates a tabular data model.

Observable event model: The event model is a building block of graphical user interfaces (GUI). This is a user friendly and most common that is provided by the graphical frameworks. The observable is a system state property that determines by some sequence of physical operations.

Tool tips: The tool tips are most common graphical user interface that is used for displaying the message in small box given by the user appropriate message, when the mouse pointer or cursor goes on it, a message (description) appears without clicking it.

Description of program:

In this Java programming tutorial we are going to implement the simple JTable on the java swing frame with the help of some java methods. To create a JTable component, you need a java swing frame. The JTable based on the frame’s panel contains multiple data in a tabular format such as rows and columns.

Description of code:

JTable( Object data[][], Object col[]):
This is the constructor of JTable class that implements a JTable for displaying the values in tabular format like rows and columns. All rows must have the same length as column names. It takes two arguments: data and col.

data – It defines the all data that will have to create a JTable.
col – It specifies the name of each column of the JTable.

Here is the code of program:

import javax.swing.*;
import java.awt.*;

public class JTableComponent{
  public static void main(String[] args)
{

    new JTableComponent();
  }

  public JTableComponent(){
    JFrame frame = new JFrame("Creating
JTable Component Example!"
);
    JPanel panel = new JPanel();
    String data[][] {{"vinod","BCA","A"},{"Raju","MCA","b"},
{
"Ranjan","MBA","c"},{"Rinku","BCA","d"}};

    String col[] {"Name","Course","Grade"};
    JTable table = new JTable(data,col);
    panel.add(table,BorderLayout.CENTER);

frame.add(panel);
    frame.setSize(300,200);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}

Download this example.

Output of program:

Java Swing


After learning AWT, lets now see what’s Swing? Well, Swing is important to develop Java programs with a graphical user interface (GUI). There are many components which are used for the building of GUI in Swing. The Swing Toolkit consists of many components for the building of GUI. These components are also helpful in providing interactivity to Java applications.Following are components which are included in Swing toolkit:

  • list controls
  • buttons
  • labels
  • tree controls
  • table controls

All AWT flexible components can be handled by the Java Swing. Swing toolkit contains far more components than the simple component toolkit. It is unique to any other toolkit in the way that it supports integrated internationalization, a highly customizable text package, rich undo support etc. Not only this you can also create your own look and feel using Swing other than the ones that are supported by it. The customized look and feel can be created using Synth which is specially designed. Not to forget that Swing also contains the basic user interface such as customizable painting, event handling, drag and drop etc.

The Java Foundation Classes (JFC) which supports many more features important to a GUI program comprises of Swing as well. The features which are supported by Java Foundation Classes (JFC) are the ability to create a program that can work in different languages, the ability to add rich graphics functionality etc.

The features which are provided by Swing and the Java Foundation Classes are as follows:

Swing GUI Components 

There are several components contained in Swing toolkit such as check boxes, buttons, tables, text etc. Some very simple components also provide sophisticated functionality. For instance, text fields provide formatted text input or password field behavior. Furthermore, the file browsers and dialogs can be used according to one’s need and can even be customized.

Capturing screen shot


In this section, you will learn about the input map. Input map is used to perform actions according to the key strokes that mean when you press any combination of keys the program performs a specific task for the specified component. Specific task for the component is assigned for the specific key combination.

This program shows how to set the key strokes for the specific component to perform a specific task. This program represents a text area on the frame in which you can write text and perform some operation on the text by applying some specified short-cut keys. These keys perform some operations like: cut, copy, paste, up, down, left and right. Following methods and APIs have been used in this program to perform some specific tasks according to the specified key combination:

InputMap:
This is the class of javax.swing.* package. This class is used to create an input map. It performs the work with the ActionMap. And input map is created for performing some specific task according to the specified key combination.

getInputMap():
This is the method of the JComponent class which returns the input map when the component is focused.

getKeyStroke():
This is the method of KeyStroke class which is imported from the javax.swing.*; package. This method returns the instance of the KeyStroke class which determines the specified key combination to perform the specified operations. This method takes different-different arguments. Here, the method has taken two arguments, first is the numeric key code and another is the modifier.

put(KeyStroke key, Object action_name):
This is the method of the InputMap class. This method add key combination to an action map. It takes two arguments in which, first is the object of the KeyStroke class and another is the action name which has to be performed.

DefaultEditorKit.cutAction:
This is the class of javax.swing.* package which is used for applying cut operations on the text. This class cuts the text from the text area and stores text to the system clipboard after applying the operation.

DefaultEditorKit.copyAction:
This is the class which is used to applying copy operation for the specified text of the text area. This class simply send the selected text to the system clipboard.

DefaultEditorKit.pasteAction:
This is the class which is used to the paste the system clipboard text to the specified component.

Here is the code of program:

import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.awt.*;

public class InputMapComponents{
  JFrame frame;
  JPanel panel;
  JLabel label;
  JTextArea area;
  JScrollPane pane;
  InputMap map;
  public static void main(String[] args) {
    InputMapComponents m = new InputMapComponents();
  }
  public InputMapComponents(){
    frame = new JFrame(" Adding an InputMap to a Component");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel = new JPanel();  
    area = new JTextArea(7,10);
    pane = new JScrollPane(area);
    map = area.getInputMap();
    KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK);
        map.put(key, DefaultEditorKit.cutAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.copyAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.pasteAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.backwardAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_R, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.forwardAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_U, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.upAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.downAction);
    String lbl = "<html><b>" "Ctrl+p = paste" 
"<br>" "Ctrl+y = copy" 
"<br>" 
"Ctrl+c = cut" "<br>"
"Ctrl+l = cursor shift left one character" 
"<br>" "Ctrl+r = cursor shift
right one character" 
"<br>"
"Ctrl+u = cursor shift up one line" "<br>" 
"Ctrl+d = cursor shift down
one line" 
"</b></html>";
    JLabel label = new JLabel(lbl);
    panel.add(pane);
    panel.add(label);
    frame.add(panel);
    frame.setSize(400,200);
    frame.setVisible(true);
  }
}

Screen shot for the result of the above program:

Set the input map for the text area in Swing application

Download this example.

Adding an Input Map to a Component


In this section, you will learn about the input map. Input map is used to perform actions according to the key strokes that mean when you press any combination of keys the program performs a specific task for the specified component. Specific task for the component is assigned for the specific key combination.

This program shows how to set the key strokes for the specific component to perform a specific task. This program represents a text area on the frame in which you can write text and perform some operation on the text by applying some specified short-cut keys. These keys perform some operations like: cut, copy, paste, up, down, left and right. Following methods and APIs have been used in this program to perform some specific tasks according to the specified key combination:

InputMap:
This is the class of javax.swing.* package. This class is used to create an input map. It performs the work with the ActionMap. And input map is created for performing some specific task according to the specified key combination.

getInputMap():
This is the method of the JComponent class which returns the input map when the component is focused.

getKeyStroke():
This is the method of KeyStroke class which is imported from the javax.swing.*; package. This method returns the instance of the KeyStroke class which determines the specified key combination to perform the specified operations. This method takes different-different arguments. Here, the method has taken two arguments, first is the numeric key code and another is the modifier.

put(KeyStroke key, Object action_name):
This is the method of the InputMap class. This method add key combination to an action map. It takes two arguments in which, first is the object of the KeyStroke class and another is the action name which has to be performed.

DefaultEditorKit.cutAction:
This is the class of javax.swing.* package which is used for applying cut operations on the text. This class cuts the text from the text area and stores text to the system clipboard after applying the operation.

DefaultEditorKit.copyAction:
This is the class which is used to applying copy operation for the specified text of the text area. This class simply send the selected text to the system clipboard.

DefaultEditorKit.pasteAction:
This is the class which is used to the paste the system clipboard text to the specified component.

Here is the code of program:

import javax.swing.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.awt.*;

public class InputMapComponents{
  JFrame frame;
  JPanel panel;
  JLabel label;
  JTextArea area;
  JScrollPane pane;
  InputMap map;
  public static void main(String[] args) {
    InputMapComponents m = new InputMapComponents();
  }
  public InputMapComponents(){
    frame = new JFrame(" Adding an InputMap to a Component");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel = new JPanel();  
    area = new JTextArea(7,10);
    pane = new JScrollPane(area);
    map = area.getInputMap();
    KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK);
        map.put(key, DefaultEditorKit.cutAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_Y, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.copyAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.pasteAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_L, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.backwardAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_R, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.forwardAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_U, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.upAction);
    key = KeyStroke.getKeyStroke(KeyEvent.VK_D, Event.CTRL_MASK);
    map.put(key, DefaultEditorKit.downAction);
    String lbl = "<html><b>" "Ctrl+p = paste" 
"<br>" "Ctrl+y = copy" 
"<br>" 
"Ctrl+c = cut" "<br>"
"Ctrl+l = cursor shift left one character" 
"<br>" "Ctrl+r = cursor shift
right one character" 
"<br>"
"Ctrl+u = cursor shift up one line" "<br>" 
"Ctrl+d = cursor shift down
one line" 
"</b></html>";
    JLabel label = new JLabel(lbl);
    panel.add(pane);
    panel.add(label);
    frame.add(panel);
    frame.setSize(400,200);
    frame.setVisible(true);
  }
}

Screen shot for the result of the above program:

Set the input map for the text area in Swing application

Download this example.

Laying Out Components Using Absolute Coordinates


In this section, you will learn how to set component’s layout according to the coordinate of the screen or the frame. Absolute coordinates are the fixed points of frame or window which is used for your application. The coordinates are specified based on the x-axis and the y-axis of the frame.

This program shows a frame which contains some swing components like: JLabel, JTextField and JButton. These components are arranged on the frame according to the absolute coordinate of the frame or window. Following methods and APIs have been used to set the fixed point or coordinate for the component on the frame:

setBounds(int x-coordinate, int y-coordinate, int width, int height):
This is the method of the Container class. This method sets the components according to the mentioned coordinate values in the method as parameter. This method takes four argument as follows:

  • First is the X-coordinate of the frame.
  • Second is the Y-coordinate of the frame.
  • Third is the width of the component.
  • And last determines the height of the component.

These values are passed through the setBounds() method after setting the layout manager using the setLayout() method for the Container.

Here is the code of Program:

import javax.swing.*;
import java.awt.*;

public class AbsCoordinate{
  public static void main(String[] args) {
    JFrame frame = new JFrame("Laying Out Components Using Absolute Coordinates");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.setLayout(null);
    JLabel label1 = new JLabel("RoseIndia.Net");
    JTextField field = new JTextField(20);
    JButton button1 = new JButton("OK");
    JButton button2 = new JButton("Cancel");
    label1.setBounds(1005010050);
    field.setBounds(7510020025);
    button1.setBounds(402007525);
    button2.setBounds(2002007525);
    panel.add(label1);
    panel.add(field);
    panel.add(button1);
    panel.add(button2);
    frame.add(panel);
    frame.setSize(400,400);
    frame.setVisible(true);
  }
}

Screen shots for the result of the above program:

Components arranged by setting it's absolute coordinate

Download this example