Kyleryan19 Kyleryan19 - 16 days ago 6
Java Question

Creating Persistant Reference To JTable Data

I am trying to create a JTable in IntelliJ with two columns: one is a checkbox, and the other is a string. A user can add an arbitrary string to the table by pressing a JButton, and each time the button is pressed a new row is added to the table where the first column is a checkbox and the second is the arbitrary string. This can be done any number of times adding any number of rows to the table. By clicking on the checkboxes and pressing a remove button, that row is removed from the table. This entire process works fine, but is not what I am having trouble with.

Every time the user presses the button adding a string to the table, I want to add that string to a consistent object/container. So at initialization the object is empty,

Object[][] tableData;


but when the button is pressed the object now contains the "checkbox" represented by a boolean, and the string.

Object[][] tableData = {
{false, "String"}
}


And this can go for awhile.

Object[][] tableData = {
{false, "String"},
{false, "String"},
{false, "String"},
{false, "String"},
{false, "String"},
{false, "String"}
}


And if any of the boolean values get changed to true (via the checkbox), and the remove button is pressed, then that specific "row" or part of the object gets deleted. How would I go about creating this object or container and maintain it? Is there a better way of doing this without an object?

A simple overview of what I have right now is below.

String colNames = {" ", "String"};
DefaultTableModel tableModel = new DefaultTableModel(colNames, 0);

importTable = new JTable(tableModel) {
@Override
public Class getColumnClass(int column) {
switch(column) {
case 0:
return Boolean.class;
default:
return String.class;
}
}
};

importButton.addActionListener(new ActionListener() {
public void actionPerofrmed(ActionEvent e) {
Object[][] newData = {
{false, "String"}
};
tableModel.addRow(newData[0]);
}
});

removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < tableModel.getRowCount(); i++) {
Boolean checked = (Boolean) tableModel.getValueAt(i, 0);
if (checked) {
tableModel.removeRow(i);
i--;
}
}
}
});

Answer

Isn't this exactly what your table model is for? If you need a different data "nucleus" for your table model, one that say uses an ArrayList<CustomType> where CustomType is a class that holds a Boolean and a String and represents each row of data in your JTable, then extend AbstractTableModel, give it your ArrayList above, override the necessary methods, be sure to call the appropriate fireXxxx(...) methods where needed, and you're in business.

Or else stick with the DefaultTableModel, and write code to simply translate it to and from the objects that you need.

Note that part of your post confuses me -- your use of inflexible and object oriented-breaking 2D Object arrays -- why?

Comments