美文网首页Java学习笔记
java Swing和JFrame,UI多线程文件复制

java Swing和JFrame,UI多线程文件复制

作者: 两分与桥 | 来源:发表于2018-09-25 11:54 被阅读37次
Java擅长开发服务器端的程序

GUI-->Graph User Interface
图形用户接口,用图形的方式,来显示计算机操作的界面,
这样更方便更直观。

CLI-->Command line user Interface
命令行用户接口,就是常见的Dos命令操作,需要记忆一些
常用的命令,操作不直观。

用java Swing 和 JFrame写的界面记事本程序,十分简单,有打开文件,保存文件,退出程序的功能,事件的绑定是通过监听器实现的


1.png

当文件内容过多时,会自动出现滚动条


2.png
下面就是整个实现代码了
package day17;

import java.awt.FileDialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class MainFrame extends JFrame implements ActionListener{
    public static void main(String[] args) {
        MainFrame frame = new MainFrame();
    }
    
    private JTextArea textArea;
    private JButton buttonSaveOther;
    private JButton buttonCancel;
    private JButton buttonSure;
    private File nowFile;
    private JMenuItem fileItem;

    public MainFrame() {
        initFrame();
        this.setVisible(true);
    }

    //界面布局
    public void initFrame() {
        //创建窗口
        this.setTitle("My title");
        //设置窗口大小,位置,左上角是原点
        this.setBounds(270, 80, 810, 640);
        
        //设置JFrame的布局为null
        this.setLayout(null);
        
        Font font = new Font("宋体", Font.BOLD, 27);
        
        textArea = new JTextArea();
        textArea.setFont(font);
        
        //滚动面板
        JScrollPane pane = new JScrollPane(textArea);
        pane.setBounds(30, 30, 750, 400);
        
        this.add(pane);
        
        buttonSaveOther = new JButton("另存为");
        //设置按钮的位置(相对于所在容器的),大小
        buttonSaveOther.setBounds(75, 500, 120, 50);
        buttonSaveOther.addActionListener(this);
        this.add(buttonSaveOther);
        
        buttonSure = new JButton("保存");
        buttonSure.setBounds(345, 500, 120, 50);
        buttonSure.addActionListener(this);
        this.add(buttonSure);
        
        buttonCancel = new JButton("退出");
        buttonCancel.setBounds(615, 500, 120, 50);
        buttonCancel.addActionListener(this);
        this.add(buttonCancel);
        
        //添加窗口事件处理程序,使用适配器
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭窗口");
                System.exit(-1);
            }
        });
        
        //添加菜单栏
        JMenuBar menuBar = new JMenuBar();
        //添加菜单
        JMenu menu = new JMenu("文件");
        
        //添加菜单项
        fileItem = new JMenuItem("打开");
        fileItem.addActionListener(this);
        menu.add(fileItem);
        menu.addSeparator();
        
        menuBar.add(menu);
        this.setJMenuBar(menuBar);
    }

    //绑定监听事件
    @Override
    public void actionPerformed(ActionEvent e) {
        Object event = e.getSource();
        FileWriter writer = null;
        FileReader reader = null;
        if(buttonSaveOther == event) {
            try {
                System.out.println("另存为按钮");
                FileDialog dialog = new FileDialog(this, "保存位置", FileDialog.SAVE);
                dialog.setVisible(true);
                nowFile = new File(dialog.getDirectory(), dialog.getFile());
                System.out.println(dialog.getFile());
                System.out.println(dialog.getDirectory());
                writer = new FileWriter(nowFile);
                writer.write(textArea.getText());
                
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if(writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                System.out.println("关闭文件流");
            }
        }else if(buttonSure == event) {
            System.out.println("保存按钮");
            
            try {
                writer = new FileWriter(nowFile);
                writer.write(textArea.getText());
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if(writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                System.out.println("关闭文件流");
            }
            
        }else if(buttonCancel == event) {
            System.out.println("退出按钮");
            this.dispose();
        }else if(fileItem == event) {
            System.out.println("打开文件按钮");
            try {
                FileDialog dialog = new FileDialog(this, "打开位置", FileDialog.LOAD);
                dialog.setVisible(true);
                nowFile = new File(dialog.getDirectory(), dialog.getFile());
                System.out.println(dialog.getFile());
                System.out.println(dialog.getDirectory());
                reader = new FileReader(nowFile);
                char[] c = new char[1024];
                int len = -1;
                String str = "";
                while((len = reader.read(c)) != -1) {
                    str = str + new String(c, 0, len);
                }
                textArea.setText(str);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                if(reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                System.out.println("关闭文件流");
            }
        }
    }
}

一个多线程文件复制器


3.png 4.png

实现代码
下面这个就是整个UI界面的代码,对各个控件的排版和事件监听

package mulcopier;

import java.awt.FileDialog;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

public class CopyUI extends JFrame implements ActionListener{
    private static final long serialVersionUID = 5521199214537722822L;
    private JTextField textSrc;
    private JTextField textAim;
    private JTextField textNumberThread;
    private JButton buttonStart;
    private JButton buttonSrc;
    private JButton buttonAim;
    public JProgressBar bar;

    public static void main(String[] args) {
        CopyUI copyui = new CopyUI();
    }
    
    public CopyUI() {
        init();
    }
    
    private void init() {
        this.setTitle("多文件复制");
        this.setBounds(270, 80, 800, 600);
        this.setLayout(null);
        
        Font fontText = new Font("宋体", Font.ITALIC, 20);  --字体类
        Font fontLab = new Font("宋体", Font.BOLD, 27);


        JLabel labSrcPath = new JLabel("源文件");  --面板中label文字
        labSrcPath.setFont(fontLab);
        labSrcPath.setBounds(30, 30, 100, 60);
        
        textSrc = new JTextField();  --所对应的输入框
        textSrc.setFont(fontText);
        textSrc.setBounds(150, 30, 400, 60);

        buttonSrc = new JButton("打开源文件路径");
        buttonSrc.setBounds(580, 40, 150, 40);
        buttonSrc.addActionListener(this);  --类本身实现了ActionListener接口,在对应方法中区分事件
        
        this.add(labSrcPath);  --添加至面板中
        this.add(textSrc);
        this.add(buttonSrc);
        
        
        JLabel labAimPath = new JLabel("目标路径");  --跟上方类似
        labAimPath.setFont(fontLab);
        labAimPath.setBounds(20, 130, 150, 60);
        
        textAim = new JTextField();
        textAim.setFont(fontText);
        textAim.setBounds(150, 130, 400, 60);
        
        buttonAim = new JButton("打开目标文件路径");
        buttonAim.setBounds(580, 140, 150, 40);
        buttonAim.addActionListener(this);
        
        this.add(labAimPath);
        this.add(textAim);
        this.add(buttonAim);
        
        
        JLabel labNumberThread = new JLabel("线程数量");
        labNumberThread.setFont(fontLab);
        labNumberThread.setBounds(20, 230, 150, 60);
        
        textNumberThread = new JTextField();
        textNumberThread.setBounds(150, 230, 400, 60);
        
        buttonStart = new JButton("开始");
        buttonStart.setBounds(100, 350, 100, 40);
        buttonStart.addActionListener(this);

        this.add(labNumberThread);
        this.add(textNumberThread);
        this.add(buttonStart);
        

        //添加窗口事件处理程序,使用适配器,监听窗口关闭事件,使得关闭的同时结束程序
        //点击右上角的关闭按钮默认不会结束程序
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("关闭窗口");
                System.exit(-1);
            }
        });
        
        bar = new JProgressBar();  --进度条
        bar.setBounds(50, 420, 700, 50);
        this.add(bar);
        
        this.setVisible(true);  -- 设置面板可见
    }

    @Override
    public void actionPerformed(ActionEvent e) { --区分并处理事件
        if(e.getSource() == buttonStart) {
            System.out.println("点击开始按钮");
            String srcPath = textSrc.getText();
            String aimPath = textAim.getText();
            int count = Integer.parseInt(textNumberThread.getText());
            System.out.println("源文件路径:" + srcPath + ", 目标文件路径:" + aimPath + ", 线程数:" + count);
            
            Copier copier = new Copier(this, srcPath, aimPath, count);
            copier.startCopy();  --这个类在下面可以看到
            
        }else if(e.getSource() == buttonSrc){
 --点击打开源文件路径按钮会弹出一个查找文件对话框,选择对应的文件后,所选的文件路径会出现在对应的输入框中
            System.out.println("打开源文件路径");
            FileDialog dialog = new FileDialog(this, "源文件路径", FileDialog.LOAD);
            dialog.setVisible(true);
            String srcPath = dialog.getDirectory() + dialog.getFile();
            if(srcPath == "nullnull") {
                textSrc.setText("");
            }else {
                textSrc.setText(srcPath);               
            }
            System.out.println(srcPath);
        }else if(e.getSource() == buttonAim){
            System.out.println("打开目标文件路径");
            FileDialog dialog = new FileDialog(this, "目标文件路径", FileDialog.LOAD);
            dialog.setVisible(true);
            String aimPath = dialog.getDirectory() + dialog.getFile();
            if(aimPath == "nullnull") {
                textAim.setText("");
            }else {
                textAim.setText(aimPath);               
            }
            System.out.println(aimPath);
        }
    }
}
package mulcopier;

import java.io.File;
import java.io.RandomAccessFile;
import javax.swing.JProgressBar;

 * 复制器
public class Copier {
    private CopyUI copyui;
    private String srcPath;
    private String aimPath;
    private int count;
    
    public Copier(CopyUI copyui, String srcPath, String aimPath, int count) {
        this.copyui = copyui;
        this.srcPath = srcPath;
        this.aimPath = aimPath;
        this.count = count;
    }
    
    public void startCopy() {
        File file = new File(srcPath);
        int fileSize = (int) file.length();
        System.out.println("文件大小" + fileSize);
        
        copyui.bar.setMaximum(fileSize);
        
        int average = fileSize/count;
        int size = 0;
        
        for(int i=0; i<count; i++) {
            if(i == count-1) {
                size = fileSize-i*average;
            }else {
                size = average;
            }
            
            //动态添加bar
            JProgressBar bar = new JProgressBar();
            bar.setBounds(50, 480+i*30, 700, 20);
            copyui.add(bar);
            MyThread t = new MyThread(copyui, bar, srcPath, aimPath, average*i, size);
            
            t.start();
        }
        System.out.println("所有线程分配结束");
    }
}

 * 复制文件的线程
class MyThread extends Thread {
    private CopyUI copyui;     // 所有线程的总进度条
    private JProgressBar bar;  // 线程各自对应的进度条
    private String srcPath;
    private String aimPath;
    private int start; // 开始写入位置
    private int size;  // 负责写入的量
    
    public MyThread(CopyUI copyui,JProgressBar bar, String srcPath, String aimPath, int start, int size) {
        this.copyui = copyui;
        this.bar = bar;
        this.srcPath = srcPath;
        this.aimPath = aimPath;
        this.start = start;
        this.size = size;
    }
    
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始位置:" + start + ",写入量:" + size);
        RandomAccessFile rafSrc = null;
        RandomAccessFile rafAim = null;
        try {
            rafSrc = new RandomAccessFile(srcPath, "r");
            rafAim = new RandomAccessFile(aimPath, "rw");
            
            rafSrc.seek(start);
            rafAim.seek(start);
            
            int len = -1;
            byte[] buffer = new byte[1024];
            int number = size;
            bar.setMaximum(size);
            while((len = rafSrc.read(buffer)) != -1) {
                rafAim.write(buffer, 0, len);
                number = number - 1024;
                
                bar.setValue(bar.getValue()+1024);  // 设置线程自己的进度条
                
                synchronized (copyui) {     // 设置所有线程共用的进度条
                    int value = copyui.bar.getValue();
                    copyui.bar.setValue(value + 1024);
                }
                
                if(number < 1024 && number > 0) {
                    len = rafSrc.read(buffer);
                    rafAim.write(buffer, 0, number);
                    
                    bar.setValue(bar.getValue()+number);
                    
                    synchronized (copyui) {
                        int value = copyui.bar.getValue();
                        copyui.bar.setValue(value + number);
                    }
                    System.out.println(Thread.currentThread().getName() + "开始位置:" + start + ",写入" + size + "完毕");
                    break;
                }
//              System.out.println("number = " + number + ", size = " + size);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(rafSrc != null) {
                    rafSrc.close();
                }
                if(rafAim != null) {
                    rafAim.close();
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println("已关闭文件流");
        }
    }
}

相关文章

  • java Swing和JFrame,UI多线程文件复制

    用java Swing 和 JFrame写的界面记事本程序,十分简单,有打开文件,保存文件,退出程序的功能,事件的...

  • Java自学-图形界面 容器

    Swing 的容器 JFrame和JDialog java的图形界面中,容器是用来存放 按钮,输入框等组件的。 窗...

  • 实验5---Swing UI设计(简易计算器)

    一、实验目的 本实验的目的是掌握JAVA容器类JFrame和JPanel的使用;掌握Swing常用布局的使用;掌握...

  • JavaSwing学习笔记(一)

    一:JFrame(Swing框架类) 运行结果: 二:JDialog(Java对话框) 运行结果: 注意事项: 1...

  • Java----Swing窗口

    package stu;//包名import javax.swing.JFrame;import javax.sw...

  • 五子棋

    一、知识准备 swing组件完成图形用户界面,窗体 JFrame创建窗体,是swing中基础的类之一 public...

  • Data Structure_JavaSwing

    Java Swing的基础 首先需要注意的就是JFrame这个类,如果在main类整直接new一个出来是没有任何的...

  • java GUI复习笔记

    常见Swing组件类 1.JFrame窗体框架类setDefaultCloseOperation()是用来设定窗口...

  • GUI

    计算机的坐标是从左上角开始。 Frame 依赖awt JFrame依赖swing 和Frame的操作基本一致 添...

  • java中调用python

    运行流程:Java Swing 界面接收用户输入 --> Java 将用户输入写到本地文件中 --> Java 调...

网友评论

    本文标题:java Swing和JFrame,UI多线程文件复制

    本文链接:https://www.haomeiwen.com/subject/zunkoftx.html