Java Graphical User Interface(GUI): JTable Using Eclipse IDE

in #utopian-io7 years ago (edited)

What Will I Learn?

  • The user will learn the concept behind JTable
  • The user will learn how to create a table and use String Arrays to add data to the table.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

The codes in this tutorial are around the same level as other tutorials so difficulty level will be same as others - Intermediate.

Tutorial Contents

This tutorial continues from previous tutorials discussing about Swing components. The tutorial introduces another Swing Component JTable which will be the subject of this tutorial.

This program creates a JTable “table” object and two String arrays; a one dimensional array containing the header of the table and a two dimensional array containing the body of the table. The table is a list of countries, their continents and the population of these countries.

JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable is another powerful Swing component for displaying complex data structures. Like JTree, JTable relies on a separate model object to hold and represent the data it displays and has its own package of helper classes. This package contains theTableModel interface and its default implementations, AbstractTableModel and DefaultTableModel.

If your table data is tidily organized, it is easy to use JTable without worrying about the TableModel. If your data is an array of rows, where each row is an array of objects, you can just pass this Object[][] directly to the JTable constructor. If you want, you can also specify an optional array of column names. This is all you need to do: the JTable does the rest. This technique also works if your data is stored in a Vector of rows, where each row is itself a Vector.

The JTable is used to display and edit regular two-dimensional tables of cells. The JTable has many facilities that make it possible to customize its rendering and editing but provides defaults for these features so that simple tables can be set up easily.

1.png

2.png

CODE BLOCK

table Class
import java.awt.*;
import javax.swing.*;
public class table extends JFrame {
    private JTable table;
    String[] names = {"Country", "Region", "Population"};
    String[][] body = {{"China", "Asia", "1,409,517,397"}, {"India", "Asia", "1,339,180,127"}, 
            {"United States", "North America", "324,459,463"}, {"Indonesia", "Asia", "263,991,379"}, 
            {"Brazil", "South America", "209,288,278"}};
    public table() {
        super("JTable Demo");
        table = new JTable(body, names);
        table.setBackground(Color.ORANGE);
        table.setPreferredScrollableViewportSize(new Dimension(500, 300));
        table.setFillsViewportHeight(true);
        add(new JScrollPane(table));
    }
}
tableMain Class
import javax.swing.JFrame;
public class tableMain {
    public static void main(String args []) {
        table table = new table();
        table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        table.setSize(500, 300);
        table.setVisible(true);
    }
}

table Class

private JTable table;

The JTable object is declared with the above syntax code.

String[] names = {"Country", "Region", "Population"};

The above code creates a one dimension array called “names”. This array will later be passed as an argument to the JTable object and will serve as the header of the table.

String[][] body = {{"China", "Asia", "1,409,517,397"}, {"India", "Asia", "1,339,180,127"}, {"United States", "North America", "324,459,463"}, {"Indonesia", "Asia", "263,991,379"}, {"Brazil", "South America", "209,288,278"}};

This is a two-dimensional array called “body”. This array will also be passed as an argument to the JTable object and will serve as the body of the table.

table = new JTable(body, names);
table.setBackground(Color.ORANGE);
table.setPreferredScrollableViewportSize(new Dimension(500, 300));
table.setFillsViewportHeight(true);
add(new JScrollPane(table));

A JTable object is created and the arrays “body” and “names” is passed to it as arguments. These arrays will be the contents of the table.

The Background Color of the table is set to Orange.

The Dimensions of the table is set and the table is made visible using the inbuilt methods:

table.setPreferredScrollableViewportSize(new Dimension(500, 300));
table.setFillsViewportHeight(true);

Finally, the table is added to the frame with a scroll pane. If the contents of the table is much, a scroll bar appears at the right of the table, enabling the user to scroll down.

tableMain CLASS

import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class tableMain {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

public static void main(String args []) {

The Java main method. Every program must contain this method in order to execute. It is the point from which the program begins execution.
A program without this method will not execute.

table table = new table();

An Object of the table class is created. This enables the user to call in built GUI methods that will help to properly display the JTable components to the screen.

table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

table.setSize(500, 300);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (500, 300).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

table.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

3.png

4.png

The program is run and the table is displayed. The user can also edit the contents of the table is the user wishes.

5.png

6.png

Source Codes from GitHub Account.

You can get the codes here if you want to try it on your own.

REFERENCES

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

Violated Rule:

  • Design or video editing related tutorials, gameplay, simple on-screen instructions, ubiquitous functions (Save, Open, Print, etc.) or basic programming concepts (variables, operators, loops, etc.) will not be accepted.

My Opinion:

  • A tutorial must be informative and explanatory, but also "tutor". This tutorial lacks "tutor"ing, and it is nothing more than an explanation of a documentation.

You can contact us on Discord.

[utopian-moderator]

Good day @yokunjon, Sighting the above reasons you gave with regards to the Utopian rules,

  • This is not a video tutorial, it does not involve basic programming concepts such as the ones stated above. This is a tutorial about a Java programming construct and is not considered as basic. I have done previous tutorials about Java programming constructs related to this and was not reprimanded for rules violation.

In my opinion, the said rule has not been violated.

  • This tutorial is part of a curriculum. This tutorial, was done in the assumption that the user follows through previous tutorials and is now used to the programming terms contained therein.
    Concepts in this tutorial have been explained extensively in previous tutorials and if a user follows my curriculum, the user will find this more than an explanation of a documentation.
    Some of the terms were used and explained in previous tutorials which is part of a curriculum, so if they have been explained numerous times before, the user can backtrack to the last tutorial.
    This tutorial explains the new terms that have not been used before.

I contacted him over Discord.