package org.simantics.spreadsheet.ui; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JTextField; import org.simantics.databoard.Bindings; import org.simantics.databoard.binding.mutable.Variant; import org.simantics.spreadsheet.CellEditor; import org.simantics.spreadsheet.ClientModel; import org.simantics.spreadsheet.Spreadsheets; public class ExpressionTextListener implements FocusListener, KeyListener { final private JTextField text; final private CellEditor editor; String undoPoint = null; int currentRow; int currentColumn; public ExpressionTextListener(JTextField text, CellEditor editor) { this.text = text; this.editor = editor; } void setCell(String text, int row, int column) { this.text.setText(text); this.undoPoint = text; this.currentRow = row; this.currentColumn = column; } void apply() { if(undoPoint == null) { // No selection return; } String current = text.getText(); if(current.equals(undoPoint)) return; if(currentRow == -1 || currentColumn == -1) return; if (current.startsWith("=")) { editor.edit(null, Spreadsheets.cellName(currentRow, currentColumn), ClientModel.CONTENT_EXPRESSION, current, Bindings.STRING, null); } else { editor.edit(null, Spreadsheets.cellName(currentRow, currentColumn), Variant.ofInstance(current), null); } undoPoint = current; } void cancel() { if(undoPoint != null) text.setText(undoPoint); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { apply(); } if(e.getKeyCode() == KeyEvent.VK_ESCAPE) { cancel(); } } @Override public void keyPressed(KeyEvent e) { } @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { apply(); } }