file模拟tree java_FileTree.java

// FileTree.java

/***********************************************************

* Author: Jason

* email: tl21cen@hotmail.com

* CSDN blog: http://blog.csdn.net/UnAgain/

***********************************************************/

package tl.exercise.swing;

import java.awt.Component;

import java.io.File;

import java.util.Vector;

import javax.swing.Icon;

import javax.swing.JTree;

import javax.swing.event.TreeExpansionEvent;

import javax.swing.event.TreeExpansionListener;

import javax.swing.event.TreeModelListener;

import javax.swing.event.TreeSelectionEvent;

import javax.swing.event.TreeSelectionListener;

import javax.swing.filechooser.FileSystemView;

import javax.swing.tree.DefaultTreeCellRenderer;

import javax.swing.tree.TreeModel;

import javax.swing.tree.TreePath;

public class FileTree extends JTree {

static

final long serialVersionUID = 0;

private

FileList theList;

public

FileTree(FileList list) {

theList =

list;

setModel(new

FileSystemModel(new FolderNode()));

this.setCellRenderer(new FolderRenderer());

addTreeSelectionListener(new TreeSelectionListener() {

public void

valueChanged(TreeSelectionEvent tse) {

}

});

this.setSelectionRow(0);

}

public

void fireValueChanged(TreeSelectionEvent tse) {

TreePath tp

= tse.getNewLeadSelectionPath();

Object o =

tp.getLastPathComponent();

// theList.fireTreeSelectionChanged((PathNode)o);

theList.fireTreeSelectionChanged((FolderNode) o);

}

public

void fireTreeCollapsed(TreePath path) {

super.fireTreeCollapsed(path);

TreePath

curpath = getSelectionPath();

if (path.isDescendant(curpath)) {

setSelectionPath(path);

}

}

public

void fireTreeWillExpand(TreePath path) {

System.out.println("Path will expand is " + path);

}

public

void fireTreeWillCollapse(TreePath path) {

System.out.println("Path will collapse is " + path);

}

class

ExpansionListener implements TreeExpansionListener {

FileTree

tree;

public

ExpansionListener(FileTree ft) {

tree =

ft;

}

public void

treeCollapsed(TreeExpansionEvent tee) {

}

public void

treeExpanded(TreeExpansionEvent tee) {

}

}

}

class FileSystemModel implements TreeModel {

I_fileSystem theRoot;

char

fileType = I_fileSystem.DIRECTORY;

public

FileSystemModel(I_fileSystem fs) {

theRoot =

fs;

}

public

Object getRoot() {

return

theRoot;

}

public

Object getChild(Object parent, int index) {

return

((I_fileSystem) parent).getChild(fileType, index);

}

public

int getChildCount(Object parent) {

return

((I_fileSystem) parent).getChildCount(fileType);

}

public

boolean isLeaf(Object node) {

return

((I_fileSystem) node).isLeaf(fileType);

}

public

int getIndexOfChild(Object parent, Object child) {

return

((I_fileSystem) parent).getIndexOfChild(fileType, child);

}

public

void valueForPathChanged(TreePath path, Object newValue) {

}

public

void addTreeModelListener(TreeModelListener l) {

}

public

void removeTreeModelListener(TreeModelListener l) {

}

}

interface I_fileSystem {

final

public static char DIRECTORY = 'D';

final

public static char FILE = 'F';

final

public static char ALL = 'A';

public

Icon getIcon();

public

I_fileSystem getChild(char fileType, int index);

public

int getChildCount(char fileType);

public

boolean isLeaf(char fileType);

public

int getIndexOfChild(char fileType, Object child);

}

/**

* A data model for a JTree. This model

explorer windows file system directly.

*

*

* Perhaps there is a fatal bug with this

design. For speed, each of instances

* of this model contains file objects of

subdirectory, up to now, there isn't

* any method to release them until program be

end. I'm afraid that the memory

* would be full of if the file system is large

enough and JVM memery size

* setted too small.

*

*

* I won't pay more attention to solve it. it

isn't goal of current a exercise.

*

* @author Jason

*/

class FolderNode implements I_fileSystem {

//

private static FolderNode theRoot;

private

static FileSystemView fsView;

private

static boolean showHiden = true;;

private

File theFile;

private

Vector all = new Vector();

private

Vector folder = new Vector();

/**

* set that whether apply hiden file.

*

* @param ifshow

*/

public

void setShowHiden(boolean ifshow) {

showHiden =

ifshow;

}

public

Icon getIcon() {

return

fsView.getSystemIcon(theFile);

}

public

String toString() {

// return fsView.

return

fsView.getSystemDisplayName(theFile);

}

/**

* create a root node. by default, it should be

the DeskTop in window file

* system.

*

*/

public

FolderNode() {

fsView =

FileSystemView.getFileSystemView();

theFile =

fsView.getHomeDirectory();

prepareChildren();

}

private

void prepareChildren() {

File[] files = fsView.getFiles(theFile, showHiden);

for (int i = 0; i < files.length; i++) {

all.add(files[i]);

if

(files[i].isDirectory()

&&

!files[i].toString().toLowerCase().endsWith(".lnk")) {

folder.add(files[i]);

}

}

}

private

FolderNode(File file) {

theFile =

file;

prepareChildren();

}

public

FolderNode getChild(char fileType, int index) {

if (I_fileSystem.DIRECTORY == fileType) {

return new

FolderNode(folder.get(index));

} else if (I_fileSystem.ALL == fileType) {

return new

FolderNode(all.get(index));

} else if (I_fileSystem.FILE == fileType) {

return

null;

} else {

return

null;

}

}

public

int getChildCount(char fileType) {

if (I_fileSystem.DIRECTORY == fileType) {

return

folder.size();

} else if (I_fileSystem.ALL == fileType) {

return

all.size();

} else if (I_fileSystem.FILE == fileType) {

return

-1;

} else {

return

-1;

}

}

public

boolean isLeaf(char fileType) {

if (I_fileSystem.DIRECTORY == fileType) {

return

folder.size() == 0;

} else if (I_fileSystem.ALL == fileType) {

return

all.size() == 0;

} else if (I_fileSystem.FILE == fileType) {

return

true;

} else {

return

true;

}

}

public

int getIndexOfChild(char fileType, Object child) {

if (child instanceof FolderNode) {

if

(I_fileSystem.DIRECTORY == fileType) {

return

folder.indexOf(((FolderNode) child).theFile);

} else if (I_fileSystem.ALL == fileType) {

return

all.indexOf(((FolderNode) child).theFile);

} else if (I_fileSystem.FILE == fileType) {

return

-1;

} else {

return

-1;

}

} else {

return

-1;

}

}

}

class FolderRenderer extends DefaultTreeCellRenderer {

private

static final long serialVersionUID = 1L;

public

Component getTreeCellRendererComponent(JTree tree, Object

value,

boolean sel,

boolean expanded, boolean leaf, int row,

boolean

hasFocus) {

I_fileSystem

node = (I_fileSystem) value;

Icon icon = node.getIcon();

setLeafIcon(icon);

setOpenIcon(icon);

setClosedIcon(icon);

return

super.getTreeCellRendererComponent(tree, value, sel, expanded,

leaf, row, hasFocus);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import os from PyQt5.QtCore import Qt from PyQt5.QtGui import QPixmap, QIcon from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout, QHBoxLayout, QTreeView, QFileSystemModel class ImageViewer(QWidget): def init(self, folder_path): super().init() self.folder_path = folder_path self.image_dict = {} self.current_image = None self.setWindowTitle("Image Viewer") self.setFixedSize(1000, 600) self.image_label = QLabel(self) self.image_label.setAlignment(Qt.AlignCenter) self.tree_view = QTreeView() self.tree_view.setMinimumWidth(250) self.tree_view.setMaximumWidth(250) self.model = QFileSystemModel() self.model.setRootPath(folder_path) self.tree_view.setModel(self.model) self.tree_view.setRootIndex(self.model.index(folder_path)) self.tree_view.setHeaderHidden(True) self.tree_view.setColumnHidden(1, True) self.tree_view.setColumnHidden(2, True) self.tree_view.setColumnHidden(3, True) self.tree_view.doubleClicked.connect(self.tree_item_double_clicked) self.main_layout = QHBoxLayout(self) self.main_layout.addWidget(self.tree_view) self.main_layout.addWidget(self.image_label) self.load_images() self.update_image() def load_images(self): for file_name in os.listdir(self.folder_path): if file_name.lower().endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp")): file_path = os.path.join(self.folder_path, file_name) self.image_dict[file_name] = file_path current_image = list(self.image_dict.keys())[0] def update_image(self): if self.current_image is not None: pixmap = QPixmap(self.image_dict[self.current_image]) self.image_label.setPixmap(pixmap.scaled(self.width() - self.tree_view.width(), self.height(), Qt.KeepAspectRatio, Qt.SmoothTransformation)) def tree_item_double_clicked(self, index): file_name = self.model.fileName(index) if file_name in self.image_dict: self.current_image = file_name self.update_image() def keyPressEvent(self, event): if event.key() == Qt.Key_A: self.previous_image() elif event.key() == Qt.Key_D: self.next_image() elif event.key() in [Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5]: self.save_text_file(event.key() - Qt.Key_0) def previous_image(self): if self.current_image is not None: file_names = list(self.image_dict.keys()) current_index = file_names.index(self.current_image) if current_index > 0: self.current_image = file_names[current_index - 1] else: self.current_image = file_names[-1] self.update_image() def next_image(self): if self.current_image is not None: file_names = list(self.image_dict.keys()) current_index = file_names.index(self.current_image) if current_index < len(file_names) - 1: self.current_image = file_names[current_index + 1] else: self.current_image = file_names[0] self.update_image() def save_text_file(self, number): if self.current_image is not None: file_name = self.current_image txt_file_path = os.path.join(self.folder_path, os.path.splitext(file_name)[0] + ".txt") with open(txt_file_path, "w") as file: file.write(str(number)) if name == "main": import sys app = QApplication(sys.argv) viewer = ImageViewer("D:/图片/wallpaper") viewer.show() sys.exit(app.exec_())这份代码实现不了使用键盘的A键向上翻页以及D键向下翻页,也实现不了键盘数字键生成相应txt文档,帮我分析一下错在哪里
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值