Filling empty tables in Java Swing

I would like to have a JFrame window with an initial empty table, say 10 columns. A mouse action event should then populate the table with a list of 10 or fewer elements, leaving the table rows used blank. How to do it?

+3
source share
3 answers

To do this, you must create a DefaultTableModel with the necessary data, and for empty lines, fill the table of objects with null values .

This is simpler with some code:

As I do not know where the data comes from, I assume that it is obtained from a matrix with less than 10 rows:

String data[][] = {{"a","b"}, {"c","d"}};

null . - .

Object data2[][] = {{"a","b"}, 
{"c","d"}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}, 
{null,null}};

, 10x2, . DefaultTableModel

yourTable.setModel(
        new DefaultTableModel(data2, new String [] {"Column1Title", "Cloumn2Title"}) {
        Class[] types = new Class[] {String.class,String.class}; 
        boolean[] canEdit = new boolean[] {true, true};
        @Override
        public Class getColumnClass(int columnIndex){ return types [columnIndex];}
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex){ return canEdit [columnIndex];}
});

. , Object.

+2

TableModel AbstractTableModel. , "" (, java.util.List). ActionEvent, , TableModelEvent, JTable.

+4

Besides creating your own TableModel, as explained by Adamski, you can directly use javax.swing.table.DefaultTableModel .
It has a constructor that takes a number of columns and rows in an argument and methods for managing data ( addRow, insertRow, setDataAt, ...).

I would prefer to create my own TableModel, unless it is for a very simple program / functionality.

0
source

Source: https://habr.com/ru/post/1729885/


All Articles