Pergunta

Good day, guys. I would just like to ask, how can I set the value of the next column value? Here, I have the counter "counter" which adds the number of true boolean values in the sampleTable. What I want to do is to set the value of the data in the next column of the table, for the "total". the "total" data should be the counter value. What should I do about this?

private void tableTest(){
    int nRow = sampleTable.getRowCount();
    int nCol = sampleTable.getColumnCount();
    int counter = 0;

    Object[][] tableData = new Object[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++){
        for (int j = 3 ; j < nCol ; j++){
            tableData[i][j] = sampleTable.getValueAt(i,j);
            System.out.println(tableData[i][j]);
            if(tableData[i][j] != null && tableData[i][j].equals(true)){
                counter++;
            }
        }
      /* if(nCol == 7){
                sampleTable.setValueAt(i, 7, counter);
            }else{
                tableData = new Object[nRow][nCol + 1];
                sampleTable.setValueAt(i, 7, counter);
            }*/
       System.out.println(counter);
       sampleTable.setValueAt(i,7,counter);
       counter = 0;
    }
}
Foi útil?

Solução

Without more to go on, it's impossible to know 1. What you're trying to do and 2. What you might be doing wrong...

The following example is really, simple. What it does is allows you to is make changes to the table and then hit the "Update" button which then goes through and calculates the total for each row...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TallyTableTest {

    public static void main(String[] args) {
        new TallyTableTest();
    }

    public TallyTableTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                try {
                    final MyTableModel model = new MyTableModel();
                    loadData(model);
                    JTable table = new JTable(model);

                    JButton update = new JButton("Update");
                    update.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            for (int row = 0; row < model.getRowCount(); row++) {
                                int counter = 0;
                                for (int col = 3; col < 7; col++) {
                                    Object value = model.getValueAt(row, col);
                                    if (value instanceof Boolean && (boolean)value) {
                                        counter++;
                                    }
                                }
                                model.setValueAt(counter, row, 7);
                            }
                        }
                    });

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new JScrollPane(table));
                    frame.add(update, BorderLayout.SOUTH);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);


                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });

    }

    public void loadData(MyTableModel model) throws IOException {
        // Fill your model here
    }

    public static class MyTableModel extends AbstractTableModel {

        protected static final String[] COLUMNS = new String[]{
            "ID", "First Name", "Last Name", "1", "2", "3", "4", "total"
        };
        protected static final Class[] COLUMN_TYPES = new Class[]{
            Integer.class, String.class, String.class,
            Boolean.class, Boolean.class, Boolean.class, Boolean.class,
            Integer.class
        };
        private List<Object[]> rows;

        public MyTableModel() {
            rows = new ArrayList<>(25);
        }

        public void addRow(Object[] data) {
            rows.add(data);
        }

        @Override
        public int getRowCount() {
            return rows.size();
        }

        @Override
        public int getColumnCount() {
            return COLUMNS.length;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return COLUMN_TYPES[columnIndex];
        }

        @Override
        public String getColumnName(int column) {
            return COLUMNS[column];
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object[] row = rows.get(rowIndex);
            return row[columnIndex];
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            Object[] row = rows.get(rowIndex);
            row[columnIndex] = aValue;
            fireTableCellUpdated(rowIndex, columnIndex);
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex >= 3 && columnIndex <= 6;
        }
    }

}

What the example does it updates the total in real time. What this means, is each time you change a column value for a row, it re-calculates that rows total and updates the model internally.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;

public class TallyTableTest {

    public static void main(String[] args) {
        new TallyTableTest();
    }

    public TallyTableTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                try {
                    final MyTableModel model = new MyTableModel();
                    loadData(model);
                    JTable table = new JTable(model);

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new BorderLayout());
                    frame.add(new JScrollPane(table));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });

    }

    public void loadData(MyTableModel model) throws IOException {
        // Fill your model here...
    }

    public static class MyTableModel extends AbstractTableModel {

        protected static final String[] COLUMNS = new String[]{
            "ID", "First Name", "Last Name", "1", "2", "3", "4", "total"
        };
        protected static final Class[] COLUMN_TYPES = new Class[]{
            Integer.class, String.class, String.class,
            Boolean.class, Boolean.class, Boolean.class, Boolean.class,
            Integer.class
        };
        private List<Object[]> rows;

        public MyTableModel() {
            rows = new ArrayList<>(25);
        }

        public void addRow(Object[] data) {
            rows.add(data);
        }

        @Override
        public int getRowCount() {
            return rows.size();
        }

        @Override
        public int getColumnCount() {
            return COLUMNS.length;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return COLUMN_TYPES[columnIndex];
        }

        @Override
        public String getColumnName(int column) {
            return COLUMNS[column];
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object[] row = rows.get(rowIndex);
            return row[columnIndex];
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            Object[] row = rows.get(rowIndex);
            row[columnIndex] = aValue;

            int counter = 0;
            for (int col = 3; col < 7; col++) {
                Object value = row[col];
                if (value instanceof Boolean && (boolean) value) {
                    counter++;
                }
            }
            row[7] = counter;
            fireTableCellUpdated(rowIndex, columnIndex);
            fireTableCellUpdated(rowIndex, 7);
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return columnIndex >= 3 && columnIndex <= 6;
        }
    }

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top