Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

206
LINES

< > BotCompany Repo | #1006540 - SimpleCRUD - create/read/update/delete for a concept class with simple fields [Swing]

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (19278L/143K).

sbool SimpleCRUD_searcher = true;

sclass SimpleCRUD<A extends Concept> {
  Class<A> cc;
  JTable table;
  JPanel buttons, panel;
  O renderer; // optional, func(A) -> Map
  O sorter; // optional, func(Cl<Concept>) -> Cl<Concept>
  S hID = "ID";
  Set<S> excludeFieldsFromEditing;
  S modifiedField; // field to hold last-modified timestamp
  TableSearcher tableSearcher;
  Set<S> multiLineFields; // string fields that should be shown as text areas
  Concepts concepts;
  Set<S> dontDuplicateFields;
  bool latestFirst;
  int formFixer = 12; // stupid value to make submit button appear

  *(Class<A> cc) { this(db_mainConcepts(), cc); }
  *(Concepts *concepts, Class<A> *cc) {}
  
  SimpleCRUD<A> show(S frameTitle) {
    make();
    showFrame(frameTitle, panel);
    this;
  }
  
  SimpleCRUD<A> show() {
    ret show(plural(shortClassName(cc)));
  }
  
  SimpleCRUD<A> showMaximized() { show(); maximizeFrame(panel); ret this; }
  
  JPanel makePanel() { ret make(); }
  JPanel make() {
    db();
    framesBot();
    ret make_dontStartBots();
  }
  
  JPanel make_dontStartBots() {
    // next line not in swing part to allow passing arguments
    // from outside like showConceptsTable_afterUpdate
    temp tempSetTL(showConceptsTable_concepts, concepts);
    temp tempSetTL(showConceptsTable_latestFirst, latestFirst);
    temp tempSetTL(showConceptsTable_sorter, sorter);
    table = makeConceptsTable(cc, wrapRenderer(renderer));
    swing {
      buttons = jRightAlignedLine(
        jbutton("Add...", r { newConcept() }),
        tableDependButton(table, jbutton("Edit", r {
          editConcept(selectedConcept())
        })),
        tableDependButton(table, jbutton("Delete", r {
          final L<A> l = selectedConcepts();
          withDBLock(concepts, r { for (A c : l) c.delete() });
        })),
        tableDependButton(table, jbutton("Duplicate...", r {
          duplicateConcept(selectedConcept())
        })));
        
      if (SimpleCRUD_searcher) {
        tableSearcher = tableWithSearcher2(table, withMargin := true);
        panel = centerAndSouthWithMargin(tableSearcher.panel, withBottomMargin(buttons));
      } else
        panel = centerAndSouthWithMargin(table, withBottomMargin(buttons));
      
      O fEdit = voidfunc(int row) {
        editConcept((A) concepts.getConcept(toLong(getTableCell(table, row, 0))))
      };
      tablePopupMenuItem(table, "Edit...", fEdit);
      onDoubleClick(table, fEdit);
    }
    ret panel;
  }
  
  O wrapRenderer(fO renderer) {
    ret renderer == null ? null : func(A a) {
      putAll(litorderedmap(hID, str(a.id)), (Map) callF(renderer, a))
    };
  }
  
  void newConcept {
    duplicateConcept(null);
  }
    
  void duplicateConcept(A oldConcept) {
    final A c = unlisted(cc);
    ccopyFieldsExcept(oldConcept, c, dontDuplicateFields);
    final Map<S, JComponent> map = makeComponents(c);
    Runnable r = r {
      concepts.register(c);
      saveData(c, map);
    };
    temp tempSetMCOpt(formLayouter1_fixer2 := formFixer);
    showFormTitled2("New " + shortClassName(cc), arrayPlus(mapToObjectArray(map), r));
  }

  void editConcept(final A c) {
    if (c == null) ret;
    final Map<S, JComponent> map = makeComponents(c);
    Runnable r = r { saveData(c, map) };
    temp tempSetMCOpt(formLayouter1_fixer2 := formFixer);
    showFormTitled2("Edit " + shortClassName(cc) + " #" + c.id, arrayPlus(mapToObjectArray(map), r));
  }
  
  A selectedConcept() {
    ret (A) concepts.getConcept(toLong(selectedTableCell(table, 0)));
  }
  
  A selected() { ret selectedConcept(); }
  
  int indexOfConcept(final A c) {
    if (c == null) ret -1;
    ret swing(func -> int {
      int n = tableRowCount(table);
      for row to n:
        if (toLong(getTableCell(table, row, 0)) == c.id)
          ret row;
      ret -1;
    });
  }
  
  L<A> selectedConcepts() {
    int[] rows = table.getSelectedRows();
    new L<A> l;
    for (int row : rows)
      l.add((A) concepts.getConcept(toLong(getTableCell(table, row, 0))));
    ret l;
  }
  
  Map<S, JComponent> makeComponents(A c) {
    Map<S, JComponent> map = litorderedmap();
    makeComponents(c, map);
    ret map;
  }
  
  JComponent fieldComponent(A c, S field) {
    Class type = getFieldType(cc, field);
    O value = getOpt(c, field);
    //print("Field type: " + field + " => " + type);
    if (type == bool.class)
      ret jCenteredCheckBox(isTrue(value));
    else if (contains(multiLineFields, field))
      ret typeWriterTextArea((S) value);
    else if (isSubtype(type, Concept))
      ret jcomboboxFromConcepts_str(concepts, type, (Concept) value);
    ifclass SecretValue
    else if (type == SecretValue.class)
      ret jpassword(strOrEmpty(getVar(value/SecretValue)));
    endif
    else try {
      ret autoComboBox(structureOrText_crud(value), new TreeSet<S>(map structureOrText_crud(collect(list(concepts, cc), field))));
    } catch e {
      printException(e);
      ret jTextField(structureOrText_crud(value));
    }
  }
  
  void saveComponent(A c, S field, JComponent comp) {
    comp = unwrap(comp);
    Class type = fieldType(c, field);
    ifclass SecretValue
      if (type == SecretValue.class) {
        S text = getTextTrim((JPasswordField) comp);
        cset(c, field, empty(text) ? null : SecretValue(text));
      } else
    endif
    if (comp instanceof JTextComponent)
      cset(c, field, convertToField(trimIf(!comp instanceof JTextArea, getText((JTextComponent) comp)), cc, field));
    else if (comp cast JComboBox) {
      S text = getTextTrim(comp);
      if (isSubtype(type, Concept))
        cset(c, field, getConcept(concepts, parseFirstLong(text)));
      else
        cset(c, field, convertToField(text, cc, field));
    } else if (comp instanceof JCheckBox)
      cset(c, field, isChecked((JCheckBox) comp));
    ifclass ImageChooser
      else if (comp instanceof ImageChooser)
        cUpdatePNGFile(c, field, comp/ImageChooser.getImage(), false);
    endif
  }
  
  L<S> fields() {
    if (excludeFieldsFromEditing != null && modifiedField != null) excludeFieldsFromEditing.add(modifiedField);
    ret listWithoutSet([S field : conceptFieldsInOrder(cc) | fieldType(cc, field) != Concept.Ref.class], excludeFieldsFromEditing);
  }
  
  void excludeFieldsFromEditing(S... fields) {
    excludeFieldsFromEditing = setPlus(excludeFieldsFromEditing, fields);
  }
  
  // override the following two methods to customize edit window
  
  void makeComponents(A c, Map<S, JComponent> map) {
    for (S field : fields())
      map.put(field, fieldComponent(c, field));
  }
  
  void saveData(A c, Map<S, JComponent> components) {
    for (S field : keys(components))
      saveComponent(c, field, components.get(field));
    if (modifiedField != null) cset(c, modifiedField, now());
  }
}

Author comment

Ref<PNGFile> fields can be saved, but are not shown automatically

download  show line numbers  debug dex   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, xrpafgyirdlv

No comments. add comment

Snippet ID: #1006540
Snippet name: SimpleCRUD - create/read/update/delete for a concept class with simple fields [Swing]
Eternal ID of this version: #1006540/84
Text MD5: ae1961f0eaf89fa297934de87a37f7c9
Transpilation MD5: 973d109a18c98b109115ae724376c034
Author: stefan
Category: javax / concepts / gui
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-09-06 20:16:52
Source code size: 6979 bytes / 206 lines
Pitched / IR pitched: No / No
Views / Downloads: 835 / 1793
Version history: 83 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1006540 & http://1006540.tinybrain.de