0

I have in my application two ComboBoxes for rows and columns for each JTable. Shown below:enter image description here

I want to add and remove rows and columns in each table dynamically. I know I would do something like table.add() but what about remove? For example if user selects 3 from Row combobox, it should add another row to it but what if user selects 2 back? It should remove that row inserted. So how do I do that?

I know it can be a stupid question but I am a newbie to Swing so people can't really expect much from me :(

Ingila Ejaz
  • 399
  • 7
  • 25
  • Does this help you : `http://stackoverflow.com/questions/1117888/how-to-remove-a-row-from-jtable` – Sourav 'Abhi' Mitra Aug 19 '14 at 17:34
  • I know the `Remove()` method. But the thing is, how do I know if 2 is selected or 3? Like if JTable has 2 rows already, and user selects 3 from combo, it should `Add()` a row, and if user selects 2 again, it should `remove()` a row. How do I do that? – Ingila Ejaz Aug 19 '14 at 17:39

1 Answers1

3

It seems that you want to control the dimension of the table using combo boxes. JTable renderers its underlying data model. Read more about tables in How to Use Tables. Adding and removing rows is actually manipulation of the data model. For example DefaultTableModel has many methods useful for your task: addRow(), removeRow(), getRowCount() etc.

It all depends on the data and task required. Check out this simple example that uses a custom table model that wraps Apache's RealMatrix. You can choose whatever data structure you need. DefaultTableModel is also good an may be sufficient. The example has two combo boxes that adjust table size.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;

public class TestTableDims extends JPanel{
    private MyTableModel model;
    private JTable table;
    private JComboBox rowsCombo;
    private JComboBox columnsCombo;

    public TestTableDims() {
        setLayout(new BorderLayout(5, 5));

        model = new MyTableModel(2, 2);

        JPanel buttonsPanel = new JPanel();
        Integer[] test = {1, 2, 3, 4, 5};
        rowsCombo = new JComboBox(test);
        rowsCombo.setSelectedItem(2);
        rowsCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                model.setRows(((Integer)rowsCombo.getSelectedItem()));
            }
        });

        buttonsPanel.add(new JLabel("rows"));
        buttonsPanel.add(rowsCombo);

        columnsCombo = new JComboBox(test);
        columnsCombo.setSelectedItem(2);
        columnsCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                model.setColumns(((Integer)columnsCombo.getSelectedItem()));
            }
        });

        buttonsPanel.add(new JLabel("columns"));
        buttonsPanel.add(columnsCombo);
        add(buttonsPanel, BorderLayout.NORTH);

        JTable table = new JTable();
        table.setModel(model);
        add(new JScrollPane(table));
    }

    class MyTableModel extends AbstractTableModel {
        private RealMatrix matrix;

        public MyTableModel(int rows, int columns) {
            matrix = new Array2DRowRealMatrix(rows, columns);
        }

        public void setRows(int rows) {
            matrix = new Array2DRowRealMatrix(rows, matrix.getColumnDimension());
            fireTableStructureChanged();
        }

        public void setColumns(int columns) {
            matrix = new Array2DRowRealMatrix(matrix.getRowDimension(), columns);
            fireTableStructureChanged();
        }

        @Override
        public int getColumnCount() {
            return matrix.getColumnDimension();
        }

        @Override
        public int getRowCount() {
            return matrix.getRowDimension();
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return Double.class;
        }

        @Override
        public void setValueAt(Object value, int row, int column) {
            matrix.setEntry(row, column, (double)value);
        }

        @Override
        public Object getValueAt(int row, int column) {
            return matrix.getEntry(row, column);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(300, 200);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {   
            public void run() {   
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLocationByPlatform(true);

                TestTableDims panel = new TestTableDims();
                frame.add(panel);
                frame.pack();

                frame.setVisible(true);
            }
        });
    }
}
tenorsax
  • 21,123
  • 9
  • 60
  • 107