0

My JTable has a column to enter the price of a product. I want to make it possible to enter numbers in the cell. The cell only accepts numbers.

I did a method with a keylistener but I did not get results.

My code for the cell in the table:

public class TextAreaEditor extends DefaultCellEditor {
   protected JScrollPane scrollpane;
   protected JTextArea textarea;

   public TextAreaEditor() {
      super(new JCheckBox());
      scrollpane = new JScrollPane();
      textarea = new JTextArea(); 
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
     // textarea.setBorder(new TitledBorder("This is a JTextArea"));
      scrollpane.getViewport().add(textarea);
   }

   public Component getTableCellEditorComponent(JTable table, Object value,
                                   boolean isSelected, int row, int column) {
      textarea.setText((String) value);

      return scrollpane;
   }

   public Object getCellEditorValue() {
      return textarea.getText();
   }
}

public class TextAreaRenderer extends JScrollPane implements TableCellRenderer
{
   JTextArea textarea;

   public TextAreaRenderer() {
      textarea = new JTextArea();
      textarea.setLineWrap(true);
      textarea.setWrapStyleWord(true);
     // textarea.setBorder(new TitledBorder("This is a JTextArea"));
      getViewport().add(textarea);
   }

   public Component getTableCellRendererComponent(JTable table, Object value,
                                  boolean isSelected, boolean hasFocus,
                                  int row, int column)
   {
      if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
         textarea.setForeground(table.getSelectionForeground());
         textarea.setBackground(table.getSelectionBackground());
      } else {
         setForeground(table.getForeground());
         setBackground(table.getBackground());
         textarea.setForeground(table.getForeground());
         textarea.setBackground(table.getBackground());
      }

      textarea.setText((String) value);
      textarea.setCaretPosition(0);
      return this;
   }
}

Any suggestions would be welcome.

TT.
  • 15,774
  • 6
  • 47
  • 88
  • 1
    *"I did a method with a keylistener but I did not get results"* - That's your first mistake, a better solution would either use a `JFormattedTextField` or a `DocumentFilter`. The `TableModel`'s `setValueAt` or it's underlying model should also be validating the input. You can have a look at [Implementing a Document Filter](https://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) for more details – MadProgrammer Aug 16 '18 at 22:46
  • 1
    See https://stackoverflow.com/questions/16224777/cell-validation-in-jtable – c0der Aug 17 '18 at 13:37

0 Answers0