Jtable only accept float numbers in your cell

Asked

Viewed 267 times

-1

I’m using this code to accept only numbers in the jtable cell, but I’d like to know how to accept . too. Someone can help me?

I’m using Java Language on the netbeans platform.

TableColumn col = tabela.getColumnModel().getColumn(1);
col.setCellEditor(new MyTableCellEditor());

class MyTableCellEditor extends AbstractCellEditor
  implements TableCellEditor{
  JComponent component = new JTextField();
  public boolean stopCellEditing(){
    String s = (String)getCellEditorValue();
    boolean valido = true;
    for(int i = 0; i < s.length(); i++){
      Character caractere = s.charAt(i);
      if(!Character.isDigit(caractere)){
        valido = false;
        break;
      }
    }    
    if(!valido){
      JOptionPane.showMessageDialog(null, 
         "Valor inválido");
      return false; 
    }
    return super.stopCellEditing();
  }
  public Component getTableCellEditorComponent(
    JTable table, Object value,
    boolean isSelected, int rowIndex, int vColIndex){
    if(isSelected){
      //
    }
    ((JTextField)component).setText((String)value);
    return component;
  }
  public Object getCellEditorValue() {
    return ((JTextField)component).getText();
  }
}

follows the jtable

DefaultTableModel modelo = new DefaultTableModel(null, new String[]{
    "ID", //  0
    "Ordem", //  1
    "Linha", //  2
    "Linha_Tipo", //  3
    "Setor", //  4
    "Perfil", //  5
    "Bpcs", //  6
    "Desc_Perfil", //  7
    "Projeto", //  8
    "OEM", //  9
    "Nº_Desenho", // 10
    "Nº_Plano", // 11
    "Operação", // 12
    "Equipamento", // 13
    "Desc_Teste", // 14
    "Complemento", // 15
    "Cod_Teste", // 16
    "Espec_Min", // 17
    "Espec_Max", // 18
    "Espec_Unid", // 19
    "Espec_Texto", // 20
    "Referência", // 21
    "Frequência", // 22
    "Freq_Unid", // 23
    "Produto", // 24
    "Origem", // 25
    "Tipo", // 26
    "Especificação", // 27
    "Freq_Texto", // 28
    "Laboratorio", // 29
    "Resultado_Numerico", // 30
    "Resultado_Texto", // 31
    "Observação", // 32
    "Aprovado"}) {         // 33

    @Override
    public boolean isCellEditable(int linha, int coluna) {
        switch (coluna) {
            case 30:
            case 31:

                String tipo = (String) getValueAt(linha, 26);
                if (tipo != null) {
                    switch (tipo) {
                        case "Min e Max":
                        case "No Min":
                        case "No Max":

                            return coluna == 30;

                        case "Texto":
                            return coluna == 31;
                        default:
                            return false;
                    }
                }
                return false;
            case 32:
            case 33:
                return true;
            default:
                return false;
        }
    }
};
  • Using Tablemodel, just set the column to Double that doesn’t even need to make a celleditor.

  • would have an example?

  • Yes, I’m testing a shape here.

1 answer

1


A solution without changing your code a lot is to add one more condition after the one that checks if the character is digit, which will check if the character is not floating point too:

for (int i = 0; i < s.length(); i++) {
    Character caractere = s.charAt(i);
    if (!Character.isDigit(caractere)) {
        if(!caractere.equals('.')){
        valido = false;
        break;
        }
    }
}

But since the goal is to allow only floating point numbers, I think using TableModel is much easier. What you would need is just to define in the method getColumnClass in the second column is Float. See the example below:

import java.awt.BorderLayout;
import java.awt.EventQueue;

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

public class JTableTest extends JFrame {

    public void createAndShowGUI() {

        Object columnNames[] = { "Any type Column", "Only Float Column",};

        DefaultTableModel model = new DefaultTableModel(null, columnNames) {

            @Override
            public Class<?> getColumnClass(int columnIndex) {

                    return columnIndex == 1 ? Float.class : super.getColumnClass(columnIndex); 
            }
        };

        model.addRow(new Object[]{});

        JTable table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);

        this.add(scrollPane, BorderLayout.CENTER);

        pack();
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String args[])  {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JTableTest().createAndShowGUI();

            }
        });
    }
}

Running:

inserir a descrição da imagem aqui

  • It worked diegofm, thank you very much!! Without wanting to abuse his good will, you know how I do to tab and it move only by columns 30, 31, 32 and 33? when giving tab he moves by all.

  • @Rafaelchaves you can try the solution of this answer here, I think it will serve you: https://stackoverflow.com/a/13869185/5524514

  • I couldn’t solve with this solution.

  • @Rafaelchaves is talking about the solution of my answer or the link?

  • From the link, your answer was perfect and you even gave me two options. Perfect!!!

  • @Rafaelchaves is simple: you will copy that code from the link and apply in your table, the only modification is in the method isSelectable, instead of returning true, you return like this: return index0 >= 30 && index1 <= 33

  • but is he not back to 30 after arriving at 33? he arrives there and stays only in that column.

  • @Rafaelchaves this is characteristic of the swing API in sync with the operating system window manager.

  • 1

    I understood diegofm! Thank you so much for your help, you helped so much!

  • Isn’t there another way to jump to the bottom line? I’ve reached a point where I need him to do it and this method doesn’t help anymore.

  • @Rafaelchaves the purpose of this question was Jtable aceitar apenas números tipo float na sua célula, and for that, the answer answered. That doubt there is another, that must be asked in another question, as you already did yesterday. ;)

Show 6 more comments

Browser other questions tagged

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