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

62
LINES

< > BotCompany Repo | #1035146 // JFileDropTarget

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

Libraryless. Click here for Pure Java version (14860L/88K).

sclass JFileDropTarget extends MetaWithChangeListeners is Swingable {
  settable S msg = "Drop file here or click the button";
  
  // currently dropped file
  settableWithVar File file;
  
  settable File defaultDirectory;
  
  // file can also be null
  event fileSelected(File file);
  
  SingleComponentPanel scp = scp();
  
  *() {
    varFile().onChange(file -> {
      updateComponent();
      fileSelected(file);
    });
  }
  
  cachedVisualize {
    if (!scp.hasComponent())
      scp.setComponent(makeComponent());
    ret jHandleFileDrop((IVF1<File>) l1 setFile, scp);
  }
  
  void updateComponent {
    scp.setComponent(makeComponent());
  }

  JComponent makeComponent() {
    var file = file();
    ret file == null
      ? noFileComponent()
      : componentForFile(file);
  }
  
  // What to show before a file was selected/dropped
  JComponent noFileComponent() {
    ret withBorder(BorderFactory.createDashedBorder(Color.gray, 2, 5, 5, true),
      jfullcenter(vstackWithSpacing(
        jcenteredlabel(msg),
        jThreadedButton("Open file...", l0 openDialog)
      )));
  }
  
  swappable JComponent componentForFile(File file) {
    ret jfullcenter(jFilePathLabel(file).visualize());
  }
  
  void setComponent(JComponent component) {
    scp.setComponent(component);
  }
  
  void openDialog {
    new JFileChooser fc;
    fc.setDialogTitle("Open file");
    fc.setCurrentDirectory(or(defaultDirectory(), userDir()));
    if (fc.showOpenDialog(scp) == JFileChooser.APPROVE_OPTION)
      setFile(fc.getSelectedFile());
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035146
Snippet name: JFileDropTarget
Eternal ID of this version: #1035146/11
Text MD5: 7bb34338122681235926aaa31834d643
Transpilation MD5: acfb29376523b37dbf70dd52b4f00922
Author: stefan
Category: javax / gui
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-04-28 15:34:51
Source code size: 1611 bytes / 62 lines
Pitched / IR pitched: No / No
Views / Downloads: 197 / 346
Version history: 10 change(s)
Referenced in: [show references]