As the title says, empty cells are being added to my table when I add something to the underlying list.
Main Class:
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MainFrame frame = new MainFrame();
}
});
}
}
MainFrame class:
import java.awt.BorderLayout;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTable;
public class MainFrame extends JFrame {
private JTable table;
private ArrayList<String> strings;
public MainFrame() {
setTitle("Stack Overflow");
setSize(800, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setVisible(true);
strings = new ArrayList<String>();
table = new JTable(new TableModel(strings));
add(table,BorderLayout.CENTER);
for (int i = 0; i < 10; i++) {
strings.add("data");
}
}
}
AbstractTableModel Class:
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class TableModel extends AbstractTableModel {
private String[] colNames = {"Col1","Col2"};
private List<String> strings;
public TableModel(List<String> strings) {
this.strings = strings;
}
@Override
public String getColumnName(int column) {
return colNames[column];
}
@Override
public int getRowCount() {
return strings.size();
}
@Override
public int getColumnCount() {
return 2;
}
@Override
public String getValueAt(int rowIndex, int columnIndex) {
if (rowIndex*2 + columnIndex >= strings.size()) return "";
return strings.get(rowIndex*2 + columnIndex);
}
}
Is there a better way of getting the items from my 1D array so that the table is populated from left to right, top to bottom (without the extra empty cells)?
Why does this problem happen anyway?
>` instead, so the outer list are the rows and the inner list are the columns for a given row
– MadProgrammer Mar 18 '20 at 21:29