javaFx(7)文本阅读器

一个简单的阅读器

效果示例

这里写图片描述

示例代码

这里写图片描述

FileItem类,用来处理文件,获取文件的前缀名和后缀名,同时获取文件的类型

package application;

import java.io.File;

public class FileItem {
    public String fileName;   // 文件名
    public String firstName;  // 前缀名
    public File file;
    public int type = BAD_FORMAT; // 1, 文本文件; 2,图片文件; -1, 不支持的文件类型

    // 文件类型常量
    public static final int TEXT = 1;
    public static final int IMAGE = 2;
    public static final int BAD_FORMAT = -1;

    private final String[] txtTypes = { "txt", "java" };
    private final String[] imageTypes = { "jpg", "jpeg", "png", "bmp" };

    // 构造函数,传入一个file并取得file的名字和类型
    public FileItem(File file) {
        this.file = file;

        // 取得文件名
        fileName = file.getName();
        firstName = getFileFirstName(fileName);

        // 根据文件后缀来判断文件的类型
        String suffix = getFileSuffix(fileName);
        type = BAD_FORMAT;
        if (contains(txtTypes, suffix))
            type = TEXT;
        else if (contains(imageTypes, suffix))
            type = IMAGE;

    }

    // 判断是否图片
    public boolean contains(String[] types, String suffix) {
        suffix = suffix.toLowerCase(); // 统一转成小写
        for (String s : types) {
            if (s.equals(suffix))
                return true;
        }
        return false;
    }

    // 获取文件名的后缀
    public String getFileSuffix(String name) {
        int pos = name.lastIndexOf('.');
        if (pos > 0)
            return name.substring(pos + 1);

        return ""; // 无后缀文件
    }

    // 获取文件名前缀
    public String getFileFirstName(String name) {
        int pos = name.lastIndexOf('.');
        if(pos > 0) {
            return name.substring(0, pos);
        }
        return "";
    }


}

FileListView类,该类继承与ListView类,使用的数据源是上面定义的FileItem类的ObservableList列表

package application;

import application.FileListView.MyListCell;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.ListCell;
/*
 * 左侧的文件列表
 */
import javafx.scene.control.ListView;
import javafx.util.Callback;

public class FileListView extends ListView<FileItem> {
    private ObservableList<FileItem> listData = FXCollections.observableArrayList();

    // 构造函数
    public FileListView() {
        setItems(listData);

        // 设置单元格生成器 (工厂)
        setCellFactory(new Callback<ListView<FileItem>, ListCell<FileItem>>()
        {

            @Override
            public ListCell<FileItem> call(ListView<FileItem> param)
            {
                return new MyListCell();
            }
        });


    }

    // 获取数据源
    public ObservableList<FileItem> data() {
        return listData;
    }
    // 设置单元格显示
    static class MyListCell extends ListCell<FileItem> {

        @Override
        protected void updateItem(FileItem item, boolean empty) {
            // FX框架要求必须先调用 super.updateItem()
            super.updateItem(item, empty);

            // 自己的代码
            if (item == null) {
                this.setText("");
            } else {
                this.setText(item.firstName);
            }
        }
    }

}

MyImagePane类继承于Pane,作用把Image封装成一个Pane,这个Pane完全显示图片,Image不属于Node,所以要包装成ImageView再添加到面板里

package application;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;

/*
 * 用于显示图片的工具类
 * 封装成一个容器
 * 这个容器显示整张图片
 * 适应父窗口
 */

public class MyImagePane extends Pane {
    ImageView imageView = new ImageView();
    Image image;

    public MyImagePane() {
        // 添加图片
        getChildren().add(imageView);
    }

    public void showImage(Image image) {
        this.image = image;
        imageView.setImage(image);
        layout();
    }

    @Override
    protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();

        // 对ImageView进行摆放,使其适应父窗口
        imageView.resizeRelocate(0, 0, w, h);
        imageView.setFitWidth(w);
        imageView.setFitHeight(h);
        imageView.setPreserveRatio(true);
    }
}

TextFileUtils类用于读写File文件

package application;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class TextFileUtils {
    public static String read(File f, String charset) throws Exception{
        FileInputStream fstream = new FileInputStream(f);
        try {
            int fileSize = (int)f.length();
             if(fileSize > 1024*512)
                    throw new Exception("File too large to read! size=" + fileSize);

            byte[] buffer = new byte[fileSize];
            // 读取到字符数组里
            fstream.read(buffer);
            return new String(buffer, charset);
        }finally {
            try{
                fstream.close();
            }catch(Exception e) {}
        }
    }

    public static void write(File f, String text, String charset) throws Exception
    {
        FileOutputStream fstream = new FileOutputStream(f);
        try{
            fstream.write( text.getBytes( charset ));
        }finally
        {
            fstream.close();
        }
    }
}

主类

package application;

import java.io.File;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.stage.Stage;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.Image;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;


public class Main extends Application {

    FileListView fileList = new FileListView();
    TabPane tabPane = new TabPane();

    @Override
    public void start(Stage primaryStage) {
        try {
            // 加载左侧文件列表
            initFileList();

            BorderPane root = new BorderPane();
            root.setLeft(fileList);
            root.setCenter(tabPane);

            Scene scene = new Scene(root,800,500);
            scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public void initFileList(){

        fileList.setPrefWidth(200);

        // 左侧加载小仙女目录下的文件
        File dir = new File("小仙女");
        File[] files = dir.listFiles();
        for(File f : files) {
            FileItem fitem = new FileItem(f);

            // 添加到左侧列表中 
            fileList.data().add(fitem);
        }

        // 列表是鼠标事件响应
        fileList.setOnMouseClicked((MouseEvent event)->{
            // 如果左键单击的话
            if(event.getClickCount() == 1 && event.getButton() == MouseButton.PRIMARY) {
                oneClicked();
            }
        });

    }


    // 单击处理
    public void oneClicked() {

        // 获取列表选中模块,获取索引
        int index = fileList.getSelectionModel().getSelectedIndex();
        FileItem fitem = fileList.data().get(index);

        try {
            openFile(fitem);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    // 打开左侧文件
    public void openFile(FileItem fitem) throws Exception{

        // 查看选项卡是否打开
        Tab tab = findTab(fitem);

        if(tab != null) {

            // 设置为选中的选项卡
            // int pos = tabPane.getTabs().indexOf(tab);  // 获取id
            tabPane.getSelectionModel().select(tab);
            return;
        }

        // 打开一个新的选项卡并选中

        Node currentView = null;

        if(fitem.type == FileItem.TEXT) {
            // 文本文件处理
            String str = TextFileUtils.read(fitem.file, "GBK");
            TextArea t = new TextArea();
            t.setText(str);
            currentView = t;

        }else if(fitem.type == FileItem.IMAGE) {
            // 图片文件处理

            // 获取文件的本地路径
            Image image = new Image(fitem.file.toURI().toString());
            MyImagePane t = new MyImagePane();
            t.showImage(image);
            currentView = t;

        }else throw new Exception("不支持打开该格式");

        // 创建新的选项卡并选中
        tab = new Tab();
        tab.setText(fitem.firstName);
        tab.setContent(currentView);
        tabPane.getTabs().add(tab);
        tabPane.getSelectionModel().select(tab);
    }


    // 查看在右侧选项卡是否打开
    public Tab findTab(FileItem fitem) {

        ObservableList<Tab> tabs = tabPane.getTabs();
        for(Tab tab : tabs) {
            if(tab.getText().equals(fitem.firstName)) {
                return tab;
            }
        }

        return null;

    }



    public static void main(String[] args) {
        launch(args);
    }
}

CSS文件

/* JavaFX CSS - Leave this comment until you have at least create one rule which uses -fx-Property */

.list-view .cell 
{
    -fx-font: 14px "Serif";
    -fx-padding: 10;
}

.text-area
{
    -fx-font: 16px "微软雅黑";
    -fx-padding: 10;
}

猜你喜欢

转载自blog.csdn.net/weixin_39778570/article/details/81274123