How to fire a method after editing an Integer column in Jtable

Asked

Viewed 315 times

0

I need to call a method that shows the user any message.

This method should be called at the exact moment the user finishes editing a Jtable column of type Integer and the user has not entered an integer number.

That is, the method should be called when the column turns 'red'.

Below I’ll put an example image that the article used in one of its posts, just to illustrate when the event should be called.

inserir a descrição da imagem aqui

Below is the code I’m developing.

 public class Dados {
        /**
         * @return the coluna0
         */
        public String getColuna0() {
            return coluna0;
        }
        /**
         * @param coluna0 the coluna0 to set
         */
        public void setColuna0(String coluna0) {
            this.coluna0 = coluna0;
        }
        /**
         * @return the colunaInteiro
         */
        public Integer getColunaInteiro() {
            return colunaInteiro;
        }
        /**
         * @param colunaInteiro the colunaInteiro to set
         */
        public void setColunaInteiro(Integer colunaInteiro) {
            this.colunaInteiro = colunaInteiro;
        }
        private String coluna0;
        private Integer colunaInteiro;
    }

.

public class TesteTableModel extends AbstractTableModel {

    private String colunas[] = {"Coluna0", "colunaInteiro"};
    private List<Dados> dados;
    private final int COLUNA_0 = 0;
    private final int COLUNA_INTEIRO = 1;

    public TesteTableModel(List<Dados> dados) {
        this.dados = dados;
    }

    //retorna se a célula é editável ou não
    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    //retorna o total de itens(que virarão linhas) da nossa lista
    @Override
    public int getRowCount() {
        return dados.size();
    }

    //retorna o total de colunas da tabela
    @Override
    public int getColumnCount() {
        return colunas.length;
    }

    //retorna o nome da coluna de acordo com seu indice
    @Override
    public String getColumnName(int indice) {
        return colunas[indice];
    }

    //determina o tipo de dado da coluna conforme seu indice
    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case COLUNA_0:
                return String.class;
            case COLUNA_INTEIRO:
                return Integer.class;
            default:
                return String.class;
        }
    }
    //preenche cada célula da tabela
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Dados dados = this.dados.get(rowIndex);
        switch (columnIndex) {
            case COLUNA_0:
                return dados.getColuna0();
            case COLUNA_INTEIRO:
                return dados.getColunaInteiro();
            default:
                return null;
        }
    }
}

.

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class GuiPrincipal extends JFrame {

    private JTable table;
    List<Dados> dados = new ArrayList<Dados>();

    public GuiPrincipal(JTable table) throws HeadlessException {
        this.table = table;
    }

    public void addDadosInDados() {
        Dados dado = new Dados();
        dado.setColuna0("Dado qualquer");
        dado.setColunaInteiro(1);
        dados.add(dado);
    }

    public GuiPrincipal() {
        setLayout(new FlowLayout());
        setSize(new Dimension(700, 300));
        setLocationRelativeTo(null);
        setTitle("Exemplo JTable");
        addDadosInDados();// add dados em dados       
        table = new JTable(new TesteTableModel(dados));
        table.setShowVerticalLines(false);
        table.setIntercellSpacing(new Dimension(0, 0));
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    // este é o método onde é executado nosso programa
    public static void main(String[] args) {
        GuiPrincipal gui = new GuiPrincipal();
        gui.setVisible(true);
    }
}

How do I fire a method at this very moment?

  • Vinicius, this code is not compileable. Test it and check the error, so it is possible to test.

  • In fact the code works just tested, only it was not separated the classes in the question and without the "package with the location of the file in each one", I changed and I will test the response code.

  • It only works in your IDE. I pasted all classes separately and the code does not compile, as there are missing methods in the Data class. That’s why you should create a separate project when creating one [mcve].

  • Vinicius, Oce changed the doubt to something completely different, so I reversed the question. It is therefore important to provide executable code, so that the answers are according to the question.

  • I took the same code and put it into a whole new application, tested it in the Netbeans IDE and the Intelij IDE. In both the code ran. What methods didn’t work when you tested them? How did you run the code, if you tell me try to run it the same way and thus fix these errors.

  • Note the use of the Data class within the Main Guideway. You are calling the add method, which does not exist in this class. Anyway, the possible solutions are in the answer, there are two ways, if one does not serve, surely the other will serve, because there are no other ways.

  • The jFrame Add? Anyway, that wasn’t the question.

  • Vinicius, the ways to do what you want are in the answer, I ask you to read again, because I suggested 2 different ways, not just the one you used first.

Show 3 more comments

1 answer

2


Try applying one of the suggested forms below:

1 - Using PropertyChangeListener

It is possible to monitor when there is some cell editing in the table by adding a PropertyChangeListener to it, filtering only when there is notification of cell editing listeners:

table.addPropertyChangeListener(e -> {
    
    if("tableCellEditor".equals(e.getPropertyName())) {
        if(!table.isEditing())
            JOptionPane.showMessageDialog(this,"fim da edição em alguma celula");
    }
});

A problem like this is that it will enter conditional whenever any cell in the table exits edit mode.


2 - Using a TableCellEditor

This form is a little more complicated, because in situations where you have a specific type of data in the column, you may need to create a TableCellEditor own, as can be seen in this example of another answer, but to simplify the demonstration, I used the class DefaultTableCellEditor.

class ShowMessageCellEditor extends DefaultCellEditor{

    public ShowMessageCellEditor(JTextField textField) {
        super(textField);
    }
    
    @Override
    public boolean stopCellEditing() {
        JOptionPane.showMessageDialog(null, "celula modificada");
        return super.stopCellEditing();
    }
}

And to apply in the specific column:

table.getColumnModel().getColumn(1).setCellEditor(new ShowMessageCellEditor(new JTextField()));

In the method getColumn(index) you must pass the index of the column of the table that you want the action to occur when finished editing. Remember that indexes in java start at 0 and not 1.

The columns of a JTable use editors implementing the interface CellEditor, and this interface has the method stopCellEditing(), which detects when editing in the cell has been stopped, and accepts the change made, even if it is partial, then notifying all hearers that that cell is no longer in edit mode.

Previously, the version was using fireEditingStopped(), but the function of this method is only to notify hearers of the event, is within the stopCellEditing() that you must fire your method.


References:

  • I still develop in a source that does not support "lambda Expressions". I will search how to convert.

  • @Viniciussilva is therefore not: https://answall.com/a/193456/28595

  • That’s correct. After calmly analyzing your answer I was able to reach the expected result using solution number 2.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.