Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. With the JTable class you can display tables of data, optionally allowing the user to edit the data. JTable does not contain or cache data; it is simply a view of your data. Here is a picture of a typical table displayed within a scroll pane:. The rest of this section shows you how to accomplish some common table-related tasks.
Here are the topics this section covers:. Or, to compile and run the example yourself, consult the example index. Click the cell that contains "Snowboarding".
The entire first row is selected, indicating that you have selected Kathy Smith's data. A special highlight indicates that the "Snowboarding" cell is editable. Generally, you begin editing a text cell by double-clicking it.
Position the cursor over "First Name". Now press the mouse button and drag to the right. As you can see, users can rearrange columns in tables. Position the cursor just to the right of a column header. Now press the mouse button and drag to the right or left.
The column changes size, and the other columns adjust to fill the remaining space. The table in SimpleTableDemo. The advantage of these constructors is that they are easy to use. However, these constructors also have disadvantages:. If you want to get around these restrictions, you need to implement your own table model, as described in Creating a Table Model. Here is typical code for creating a scroll pane that serves as a container for a table:.
The scroll pane automatically places the table header at the top of the viewport. The column names remain visible at the top of the viewing area when the table data is scrolled. If you are using a table without a scroll pane, then you must get the table header component and place it yourself.
For example:. By default, all columns in a table start out with equal width, and the columns automatically fill the entire width of the table. When the table becomes wider or narrower which might happen when the user resizes the window containing the tableall the column widths change appropriately.
How to Use Tables
When the user resizes a column by dragging its right border, then either other columns must change size, or the table's size must change.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.
By default, a JTable will adjust its width such that a horizontal scrollbar is unnecessary. Note that if you wish to use a JTable in a standalone view outside of a JScrollPane and want the header displayed, you can get it using getTableHeader and display it separately. To enable sorting and filtering of rows, use a RowSorter.
You can set up a row sorter in either of two ways: Directly set the RowSorter. For example: table. For example: setAutoCreateRowSorter true. When designing applications that use the JTable it is worth paying close attention to the data structures that will represent the table's data. As well as copying the data from an application into the DefaultTableModelit is also possible to wrap the data in the methods of the TableModel interface so that the data can be passed to the JTable directly, as in the example above.
This often results in more efficient applications because the model is free to choose the internal representation that best suits the data. A good rule of thumb for deciding whether to use the AbstractTableModel or the DefaultTableModel is to use the AbstractTableModel as the base class for creating subclasses and the DefaultTableModel when subclassing is not required.
Java Swing JTable Simple Example
The "TableExample" directory in the demo area of the source distribution gives a number of complete examples of JTable usage, covering how the JTable can be used to provide an editable view of data taken from a database and how to modify the columns in the display to use specialized renderers and editors.
The JTable uses integers exclusively to refer to both the rows and the columns of the model that it displays. The JTable simply takes a tabular range of cells and uses getValueAt int, int to retrieve the values from the model during painting.
It is important to remember that the column and row indexes returned by various JTable methods are in terms of the JTable the view and are not necessarily the same indexes used by the model. By default, columns may be rearranged in the JTable so that the view's columns appear in a different order to the columns in the model.
This does not affect the implementation of the model at all: when the columns are reordered, the JTable maintains the new order of the columns internally and converts its column indices before querying the model.
So, when writing a TableModelit is not necessary to listen for column reordering events as the model will be queried in its own coordinate system regardless of what is happening in the view. In the examples area there is a demonstration of a sorting algorithm making use of exactly this technique to interpose yet another coordinate system where the order of the rows is changed, rather than the order of the columns. Similarly when using the sorting and filtering functionality provided by RowSorter the underlying TableModel does not need to know how to do sorting, rather RowSorter will handle it.
Coordinate conversions will be necessary when using the row based methods of JTable with the underlying TableModel. All of JTable s row based methods are in terms of the RowSorterwhich is not necessarily the same as that of the underlying TableModel. For example if row 0, in terms of the underlying model, is currently selected, after the sort row 0, in terms of the underlying model will be selected.
Visually the selection may change, but in terms of the underlying model it will remain the same. The one exception to that is if the model index is no longer visible or was removed.
For example, if row 0 in terms of model was filtered out the selection will be empty after the sort. J2SE 5 adds methods to JTable to provide convenient access to some common printing needs.
Simple new print methods allow for quick and easy addition of printing support to your application. In addition, a new getPrintable javax. PrintMode, java. MessageFormat, java. MessageFormat method is available for more advanced printing needs. Warning: Swing is not thread safe. For more information see Swing's Threading Policy. Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing.
As of 1. Please see XMLEncoder.This article explains how to write an editable JTable and proceeds to show an example. Understanding the TableModel:. Let us consider an example. We want to display the employee details in a table and also allow the user to edit the values directly in the table.
The employee details would include fields like id, name, hourly rate and part-time status. Before we start looking at the code, we need to understand about the model of JTable. Let us try and understand why this is needed and how this helps us.
In simple terms, the Model-View-Controller paradigm dictates that the data be held in a Model. And the view should display the data by querying the model. In other words, the view should not hold the data. When there is a need to display the data, the view should invoke the methods of the model to get this information. MVC Model. This means that, the model should expose various methods which return useful information for the view.
For JTablethe model is named as TableModel which is an interface. Let us look at the class diagram of the TableModel to understand this better:. Class Diagram of TableModel. As we can see, there are several getXXX methods which return various data.
Let us try and understand how the view in this case, the JTable can make use of this. Let us consider a scenario. The JTable should display the details of the employees.
So, it should in turn query the TableModel to get this data and display it. Let us focus on the querying part by attempting to write a pseudocode for this. To display the data, the table needs several details like header values, number of rows, number of columns and the actual data.
The pattern would be something like this:. So, when we attempt to convert this into actual working code, the repetitive part of getting the cell values one by one yields itself to a loop. Also, since we are dealing with a 2 dimensional data, this means we would need 2 loops — a loop within a loop i. The outer loop will be for the rows and the inner loop will be for the columns.
Thus, we will be able to traverse the entire table. So, the model should be able to provide the table back with all this information. In other words, the model should provide methods which will return these values for us.
If you look at the TableModel class diagram, you can find that it exactly does this. For example, the getRowCount method returns the number of rows in the model. Similarly, the getColumnCount method returns the number of columns in the model. And most importantly, the getValueAt method takes the row number and the column number as parameters and returns the value of that particular cell.
So, the JTable internally would probably execute a code like this at runtime to display the values:. Note that, the row numbers and column numbers begin indexing at 0 and hence we start from 0. The actual code written by the Swing API developers would be much more complex. But, this should give an idea of what actually happens behind the scenes.
And that in turn, helps us to understand how and what to write in a TableModel implementation.In Java, JTable is used to edit or display 2-D data which consists of rows and columns. It is almost similar to a spreadsheet that contains data in a tabular form. JTable can be created by instantiating the class javax. Let us look into syntax, constructor, and methods of JTable in Java in detail. JFrame; import javax. JScrollPane; import javax.
On Executing the code, a table, as shown above, will be displayed. On clicking it, a popup to print the page will be shown. JTable in Java is almost similar to a spreadsheet that consists of rows and columns. It is mainly used to modify or show 2-D data that are available in those rows and columns. This is a guide to JTable in Java.
Here we discuss the syntax, constructor, and methods of JTable in Java along with program. You may also look at the following articles to learn more —. Your email address will not be published.
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. I was searching for Sorting in JTable and I referred many articles, but couldn't get the easiest way to sort the table. I also know that TableRowSorter could be somehow helpful but don't know how. Being new to JTableI am creating a new question here. What I want here is to sort my table Descending based on 4th column "Mentions".
If counts Mentions are same, it should sort Ascending by 1st column "People". Learn more. How to sort JTable in shortest way?
Creating a JTable : JTable « Swing « Java Tutorial
Ask Question. Asked 5 years, 1 month ago. Active 5 years, 1 month ago. Viewed 40k times. Pratik Pratik 2 2 gold badges 3 3 silver badges 11 11 bronze badges. Active Oldest Votes.
SortKey 4, SortOrder. SortKey 0, SortOrder.
Yes import java. EventQueue; import java. ArrayList; import java. List; import javax. JFrame; import javax. JScrollPane; import javax. JTable; import javax. RowSorter; import javax. SortOrder; import javax.This article shows a simple example of JTable. This is similar to a spreadsheet. Let us consider some examples. Say that you want to display a list of employees belonging to an organization. This should display the various attributes of employees. For example, employee id, name, hourly rate, part-time status etc.
The display will be more like a database table display of rows and columns. In this case, the id,name, hourly rate are the columns. The number of rows might differ based on the number of employees in the organization. First Attempt:. Let us attempt to display such a data with JTable with minimum amount of code. The idea is to only display the details in the table. The user should not be allowed to edit any data. Also, text-based columns should be left-aligned and numerical values should be right-aligned.
The following code should help us do that:. This code attempts to build a table with minimum amount of effort. First of all, the column headers are identified and declared in a String array columns.
Next, a 2d Object array named data is declared. Each inner array corresponds to a row of data.Java - How To Add And Update A Row To JTable From JTextField + Delete Row In Java [With Source Code]
Within each array, the columns are separated by commas. Note that the column values are declared based on their type. For example, the id holds int values, name holds string values, hourly rate holds double values and part-time status holds boolean values.
This is important as it allows us to represent the actual values and not just as string values for all. Coming back to the code, a JTable instance is then created by using the constructor that takes the data and column arrays. When the code is run, we get the following output:. Initial Display. Issues with this Program:. There are a few problems with this program. Firstly, the columns are not aligned properly.
All the columns are left-aligned which is not we want. We want the numbers to be right-aligned. Secondly, when you run the program, you can see that the table allows the user to edit the fields.
Our idea was to build a table that is for display-only.The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet. This arranges data in a tabular form. Output :. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.
See your article appearing on the GeeksforGeeks main page and help other Geeks. Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below. Writing code in comment?
Please use ide. EditText widget in Android using Java with Examples Monolithic vs Microservices architecture Program to check if a String in Java contains only whitespaces In Java, Can we call the main method of a class from another class?
JTable Object data, Object Column : A table is created with the specified name where Column defines the column names. Functions in JTable :. JFrame f. JTable j. Check out this Author's contributed articles. Load Comments. JFrame; import javax. JScrollPane; import javax.