2

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.stack.imgur.com/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?

u3l
  • 3,342
  • 4
  • 34
  • 51
  • 1
    1) Go through the JTable tutorial which is likely the first hit on Google. 2) Repeat 1). – Hovercraft Full Of Eels Dec 19 '13 at 05:19
  • Edit: yep, it is the first hit. It will show you how to use a TableModel which is the key to your problem. It's all there. – Hovercraft Full Of Eels Dec 19 '13 at 05:20
  • 1
    Ahh okay, I found the `fireTableRowsInserted` method. I had went through the link before but hadn't gone through it thoroughly. I'm sorry... thanks! – u3l Dec 19 '13 at 05:25
  • Glad you've got it fixed. In the future, we'll be able to direct you better if you can show us some code and give more details on the problems your posted code is having. – Hovercraft Full Of Eels Dec 19 '13 at 05:37
  • I'll keep that in mind - I usually do post code in my questions; however, I thought this was more of a thing where I just needed to find out what class/method to use. I'll make sure to next time though. – u3l Dec 19 '13 at 05:38

1 Answers1

3

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Yeah, sorry - I realized this after I went through the JTable tutorial again. This whole time I was under the impression I had to create a new model every time... I can't believe I didn't realize this before. – u3l Dec 19 '13 at 05:32
  • @Trust My lives hard enough as is, I'd hate to see it with a non-mutable table model 8O – MadProgrammer Dec 19 '13 at 05:34