Search code examples
javaswingjtableabstracttablemodel

How can I make my JTable/TableModel dynamic?


So I'm in a situation where I want to use a JTable that can grow and shrink as per user input. (sort of like how an ArrayList can do that while a regular array can't). But I can't find any AbstractTableModel classes that can do this.

Here is an image of my program: https://i.sstatic.net/CI9bQ.png

For my current JTable, I have to enter the number of points (in the field at the top) and based on that, it'll create an entirely new JTable with that many rows... I'm under the impression that this is really inefficient. Is there anyway that I can just press "Enter" or something similar on the keyboard when i'm at the last row, and it'll add a new row?


Solution

  • The short answer is, yes, emphatically.

    You could use a DefaultTableModel which has this kind of functionality, but personally, I prefer to roll my own AbstractTableModel as I can keep the data in POJO's

    Basically, you need to supply add and delete methods in your model to allow it to, obviously, add and remove remove rows from your own internal structure of rows (I typically use some kind of List)

    You also need to fire the appropriate events for these as well, take a look at

    To start with...

    Also, take a look at How to use Tables for more details