JavaFX拖放:仅接受一些文件扩展名

时间:2016-06-22 08:19:23

标签: java javafx drag-and-drop

我想做什么: 当用户尝试将某些内容拖放到窗口中时,只有当拖动文件包含扩展名(.mp3,.ogg,.wav)时才能执行此操作。如果文件没有此扩展名,则无法执行删除操作我不希望链接等被丢弃。

例如,只接受 html 非常简单:

  controller.setOnDragOver((over) -> {
            Dragboard board = over.getDragboard();
            if (board.hasHtml())
                over.acceptTransferModes(TransferMode.LINK);

        });

如何为此添加过滤器?

1 个答案:

答案 0 :(得分:3)

您可以在DragBoard DragEvent中设置的事件处理程序中使用Node Scene方法返回的DragEvent Stage方法VBox }或public class Main extends Application { @Override public void start(Stage primaryStage) { try { VBox root = new VBox(); Scene scene = new Scene(root,400,400); // Extensions that are valid to be drag-n-dropped List<String> validExtensions = Arrays.asList("jpg", "png"); root.setOnDragOver(event -> { // On drag over if the DragBoard has files if (event.getGestureSource() != root && event.getDragboard().hasFiles()) { // All files on the dragboard must have an accepted extension if (!validExtensions.containsAll( event.getDragboard().getFiles().stream() .map(file -> getExtension(file.getName())) .collect(Collectors.toList()))) { event.consume(); return; } // Allow for both copying and moving event.acceptTransferModes(TransferMode.COPY_OR_MOVE); } event.consume(); }); root.setOnDragDropped(event -> { boolean success = false; if (event.getGestureSource() != root && event.getDragboard().hasFiles()) { // Print files event.getDragboard().getFiles().forEach(file -> System.out.println(file.getAbsolutePath())); success = true; } event.setDropCompleted(success); event.consume(); }); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } // Method to to get extension of a file private String getExtension(String fileName){ String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0 && i < fileName.length() - 1) //if the name is not empty return fileName.substring(i + 1).toLowerCase(); return extension; } public static void main(String[] args) { launch(args); } } 获取当前拖动的文件列表。

您可以使用例如getFilesgetDragboard或通过实现自己的函数来检查此列表中的扩展名以获取文件的扩展名。如果dragboard文件的扩展名与预定义的扩展名不匹配,则只需使用files =[ './file-name-1.rb', './file-name-2.rb', ] files.each do |file| require file end

示例

在此示例中,我创建了一个private static final String TABLE = "dataOne"; private static final String COL_ID = "ID"; private static final String COL_CONTENT = "CONTENT"; private static final String CREATE_BDD = "CREATE TABLE " + TABLE + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_CONTENT + " TEXT NOT NULL);"; public SQLiteBase(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BDD); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE " + TABLE + ";"); onCreate(db); }} ,其内部private static final int VERSION_BDD = 1; private static final String NOM_BDD = "sharedOne.db"; private static final String TABLE = "dataOne"; private static final String COL_ID = "ID"; private static final int NUM_COL_ID = 0; private static final String COL_CONTENT = "CONTENT"; private static final int NUM_COL_CONTENT = 1; private SQLiteDatabase bdd; private SQLiteBase sqLiteBase; public SQLiteWorker(Context context){ sqLiteBase = new SQLiteBase(context, NOM_BDD, null, VERSION_BDD); } public void open(){ //on ouvre la BDD en écriture bdd = sqLiteBase.getWritableDatabase(); } public void close(){ //on ferme l'accès à la BDD bdd.close(); } public SQLiteDatabase getBDD(){ return bdd; } public long insertDate(DataOne data){ ContentValues values = new ContentValues(); values.put(COL_CONTENT, data.getContent()); return bdd.insert(TABLE, null, values); } public int updateData(int id, DataOne data){ ContentValues values = new ContentValues(); values.put(COL_CONTENT, data.getContent()); return bdd.update(TABLE, values, COL_ID + " = " +id, null); } public int removeDataWithID(int id){ return bdd.delete(TABLE, COL_ID + " = " +id, null); } public DataOne cursorToDataOne(Cursor c){ DataOne data = new DataOne(); data.setContent(c.getString(NUM_COL_CONTENT)); data.setId(c.getInt(NUM_COL_ID)); return data; } public DataOne getDataOneWithId(int id){ Cursor c = bdd.query(TABLE, new String[]{COL_ID, COL_CONTENT}, COL_ID + " = \"" + id + "\"", null, null, null, null); return cursorToDataOne(c); } public static Cursor getDatas(String id, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder sqliteQueryBuilder = new SQLiteQueryBuilder(); sqliteQueryBuilder.setTables(TABLE); if(id != null) { sqliteQueryBuilder.appendWhere("_id" + " = " + id); } if(sortOrder == null || sortOrder == "") { sortOrder = COL_ID; } Cursor cursor = sqliteQueryBuilder.query(getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder); return cursor; }} 仅接受扩展名为&#34; jpg&#34;和&#34; png&#34;放在上面。如果删除成功,则会打印文件的绝对文件路径。

getReadableDatabase()