在网上找了好久,基本上都是写死的。
于是我找了个大牛同学改了改,于是有了以下版本。小伙伴可以直接用哦,但不知道java的能不能实现,我这个是fx里面的
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import org.apache.mina.core.session.IoSession;
import javafx.scene.control.ProgressIndicator;
public class ProcessBar extends JFrame implements Runnable {
JProgressBar progress; // 进度条
ProgressIndicator ploading;
long fileSize = 0 ;
IoSession session = null;
int process = 0;
public ProcessBar(String str) {
super(str);
progress = new JProgressBar(1, 100); // 实例化进度条
ploading = new ProgressIndicator();
progress.setStringPainted(true); // 描绘文字
progress.setBackground(Color.PINK); // 设置背景色
this.add(progress);
this.setBounds(200, 300, 250, 50);
this.setResizable(false);
}
public void run() {
// while(true) {//这个是以前的版本,进度条写死的那种。不建议使用
// for(int i=0; i<100; i++) {
// try {
// progress.setValue(progress.getValue() + 1); // 随着线程进行,增加进度条值
//
// progress.setString(progress.getValue() + "%");
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// JOptionPane.showMessageDialog(this, "发送完成!");
// this.dispose();
// break;
// }
while(true) {
while (process < 100){
try {
if(session == null || session.getWrittenBytes() == 0){
process = 0;
}else{
process = (int)(session.getWrittenBytes() * 100 / fileSize);
System.out.println("WrittenBytes" + session.getWrittenBytes());
}
progress.setValue(process); // 随着线程进行,增加进度条值
progress.setString(process + "%");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
JOptionPane.showMessageDialog(this, "发送完成!");
this.dispose();
break;
}
}
public int getProcess() {
return process;
}
public void setProcess(int process) {
this.process = process;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public IoSession getSession() {
return session;
}
public void setSession(IoSession session) {
this.session = session;
}
public void setVisible(){
this.setVisible(true);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------
调用的时候:
ProcessBar pb = new ProcessBar("正在发送...");
//按钮触发的效果,以下触发内容与进度条关系不大,请大家根据自己需求进行修改
net_send1.setOnAction((ActionEvent e) -> {
// 先进行读条,后弹出完成框
new Thread(new Runnable() {
@Override
public void run() {
// 前台输入的IP号
String ip_arg = net_ip2.getText();
// 前台输入的端口号
String port_arg = net_dk2.getText();
int port = Integer.parseInt(port_arg);
// 前台获取的文件路径
String path = net_path1.getText();
try {
sendUtil.minaSend(ip_arg, port, path, pb);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}).start();
// 调用进度条
pb.setVisible();
thread = new Thread(pb);
thread.start();
});
本文介绍如何在 JavaFX 中创建一个动态进度条,通过示例代码展示了一个结合IoSession更新进度的方法,用于文件发送过程中的进度显示。进度条会根据发送的字节数动态更新,并在完成后提示用户。
554





