gpt4 book ai didi

Java LibGDX SwingWorker 卡住 GUI( block uploader )

转载 作者:太空宇宙 更新时间:2023-11-04 13:41:42 26 4
gpt4 key购买 nike

我目前正在开发一个 block uploader (用Java)来将文件上传到私有(private)服务器。一切工作正常,但是当应用程序上传文件时,它会卡住窗口。上传后一切恢复正常,但上传过程中则不然。我知道它会上传,因为它可以工作并且会在控制台中显示进度。因此,我尝试将所有计算移动到不同的线程上。它仍然正常运行,但卡住了。此外,我读到了有关 SwingWorker 的内容,并尝试了一下,但它仍然卡住了主 GUI。

这是 SwingWorker 的类(所有方法都是按顺序排列的,因此您不应该迷失方向,并且每个方法都包含解释目的的注释)(代码很多,但您实际上应该只需要查看 BeginUpload() 方法,因为这是循环所在的位置)

public class ChunkUploader extends SwingWorker<String, Object> {
public String Text="";
public String Text2="";

boolean Uploading=false;
private String Actual="";
private int CurrentChunk=0;

private int BytePosition=0;

private int ChunkSize=100000;
private String Contents="";
private String FileName;
private int PackageNumber;
private String ByteString;
private boolean Finalize;
private String Password;
private int TotalChunks;
private byte[] bytes;
TextPrompt Prompt;

public double Progress=0;

public boolean done=false;
public ChunkUploader(String FileName) {
//Prepares the thing
this.FileName=FileName;
Prompt = new TextPrompt();
}

@Override
protected String doInBackground() throws Exception {
//Calls the first method
PrepareUpload(FileName);
return null;
}

private void PrepareUpload(String FileName) {
//Loads the file and then prompts for a password;
if(Gdx.files.absolute(FileName).exists()) {
Actual=FileName;
System.out.println(FileName);///C:/T/Image.png
Uploading=true;
String pp[]=FileName.split("/");
this.FileName=pp[pp.length-1];
System.out.println(this.FileName);///C:/T/Forgive.txt
FileHandle h=Gdx.files.absolute(Actual);
Text = "Loading file..."+Actual;
bytes = h.readBytes();
Text2="";
Prompt.Prepare("Password", this);
Gdx.input.getTextInput(Prompt, "Input Dynamic Password:", "");
}
}

public void PromptReturn(String Return, String Text) {
//Reads the user input into the variable Password. Starts the upload
if(Return.equals("Password")) {
Password=Text;
BeginUpload();
}
}

private void BeginUpload() {
//Splits the data to chunks and encodes it Base64. Sends the data to Return();

Text = "Total size: "+Integer.toString(Contents.length());
TotalChunks=(int) Math.ceil(bytes.length/ChunkSize);
TotalChunks++;
String CurrentSend="";
CurrentChunk=0;

String All="";

Text2="Starting Upload...";

for(int i=0; i<TotalChunks; i++) {
byte[] temp=GetByteRange(CurrentChunk*ChunkSize, GetWidth(CurrentChunk*ChunkSize, bytes.length, ChunkSize));
System.out.print(Double.toString(100*BytePosition/bytes.length)+"% complete.");
Text = Double.toString(100*BytePosition/bytes.length)+"% complete.";
BytePosition=GetWidth(CurrentChunk*ChunkSize, bytes.length, ChunkSize);

CurrentSend=Base64.getEncoder().encodeToString(temp);CurrentChunk, false, Password, TotalChunks, FileName);
String p="";
while(p.isEmpty()) {
try {
p=Return(CurrentSend, CurrentChunk, false);
} catch (Exception e) {
e.printStackTrace();
}
}
All = All+CurrentSend;
CurrentChunk=CurrentChunk+1;
}
Text2="Finalizing...";
String p="";
while(p.isEmpty()) {
try {
p=Return(CurrentSend, TotalChunks, true);
} catch (Exception e) {
e.printStackTrace();
}
}
Text2="Upload should be complete.";
}

public byte[] GetByteRange(int Start, int End) {
byte[] temp = new byte[End-Start];

for(int i=Start; i<End; i++) {
temp[i-Start] = bytes[i];
}

return temp;
}

public int GetWidth(int Position, int Size, int ChunkSize) {
if(Position+ChunkSize<=Size) {
int p=ChunkSize+Position;
return p;
}
else {
return Size;
}
}

public String Return(String ByteString, int PackageNumber, boolean finalize) throws Exception {
//Sends the file data to the server.
String url = "http://www.stackoverflow.com/";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "Pass="+Password+"&FileName="+FileName+"&PackageNumber="+Integer.toString(PackageNumber)+"&FinalPackageNum="+TotalChunks+"&Bytes="+ByteString;
if(finalize==true) {
urlParameters=urlParameters+"&State=Final&FinalPackageNum="+Integer.toString(TotalChunks);
}
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(urlParameters.getBytes(StandardCharsets.UTF_8));
wr.flush();
wr.close();

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(response.toString());
System.out.println("___________________");
return response.toString();
}
}

这是在其上创建 ChunkUploader 类的 LibGDX 屏幕。

public class FileUploadScreen implements Screen {
String FilePath;
String Text="";
String Text2="";

ChunkUploader Uploader;
OrthographicCamera camera;

MyGame game;
public FileUploadScreen(String FilePath, MyGame game) {
this.game=game;
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
this.FilePath = FilePath;
Uploader = new ChunkUploader(FilePath);
Uploader.execute();
}
@Override
public void render(float delta) {
Text=Float.toString(delta);
game.MainFont.setColor(Color.WHITE);
game.Screen.set(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.update();
game.batch.setProjectionMatrix(camera.combined);

Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
game.batch.begin();
game.MainFont.draw(game.batch, Text, 100, game.Screen.y-50);
game.MainFont.draw(game.batch, Text2, 100, game.Screen.y-100);
game.batch.end();
}
}

为了更好地衡量,这里是文本提示:

public class TextPrompt implements TextInputListener {
private String Text="";
public boolean Active;
private String Return;
private ChunkUploader parent;

public TextPrompt() {
Active = false;
}
public void Prepare(String Return, ChunkUploader Parent) {
Active = true;
this.Return=Return;
this.parent=Parent;
}
@Override
public void input(String text) {
Text = text;
Active = false;
parent.PromptReturn(Return, Text);
}
@Override
public void canceled() {
Text = "";
Active = false;
}
public String GetInput() {
return Text;
}
}

同样,只要文件没有上传,一切都会正常运行。我只是很困惑,因为如果它在单独的线程上上传,那么它不应该与 GUI 冲突。谁能告诉我我做错了什么?

最佳答案

好吧,看来这有一些问题。首先,ChunkUploader类中的所有方法都需要通过doInBackground()来调用。当你查看 PromptReturn 方法内部时,BeginUpload();被调用。

为了解决这个问题,我们需要发挥一点创意。以下是应该进行的更改:

需要创建一个可由 doInBackground() 和 PromptReturn() 访问的 boolean 变量。它的初始值应该是 false。

接下来,对前几个方法进行更改:

private boolean Begin = false;

public void PromptReturn(String Return, String Text) {
//Reads the user input into the variable Password. Starts the upload
if(Return.equals("Password")) {
Password=Text;
//BeginUpload();
Begin = true;
}
}

@Override
protected String doInBackground() throws Exception {
//Calls the first method, and waits to call the second.
PrepareUpload(FileName);
boolean run=true;
while(run) {
if(Begin) {
BeginUpload()
run=false;
}
}
return null;
}

此外值得注意的是,您使用的 Base64 编码器仅适用于桌面应用程序。您应该考虑切换到 this Base64 encoder/decoder.它以您使用的方式满足您当前的所有需求,并且非常容易实现。只需将 Base64.java 复制到您的项目中,您现在就可以将其用于桌面和 Android。

关于Java LibGDX SwingWorker 卡住 GUI( block uploader ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31195844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com