gpt4 book ai didi

java - 当输入以编程方式更新时,如何刷新 zk 中的文本框?

转载 作者:行者123 更新时间:2023-12-02 04:03:03 25 4
gpt4 key购买 nike

有一个文本框,我想在我的 apache tomcat 7 服务器上用作 ZK 中的控制台形式。现在,当其内容以编程方式更改时,它不会更新,但我只想这样做。每当我的java更改字符串时,它都应该及时显示它,但是如何呢?

(修改了ZK的现有代码)

我的index.zul:

<zk>
<window id="PDFmodifier" border="normal" height="98%"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('toolbox.pdfconverter.FileUploadVM')">
<label value="PDFmodifier"/>
<separator></separator>
<separator></separator>
<hbox>

<label value="Console log: " />
<textbox width="500px" height="400px" id="txt" readonly="true" multiline ="true" value="Press the Upload Button to upload any PDF file. PDFmodifier will cover the unwanted area. After processing, the showPDF button will be active and you can save the modified PDF"/>
<button label="Upload" upload="true"
onUpload="@command('onUploadPDF',upEvent=event)"> </button>

<button label="Show PDF" visible="@load(vm.fileuploaded)"
onClick="@command('showPDF')">
</button>
</hbox>

<iframe height="100%" width="100%" id="reportframe"
content="@bind(vm.fileContent)">
</iframe>
</window>

View 模型:

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;

import org.zkoss.bind.BindContext;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.io.Files;
import org.zkoss.util.media.AMedia;
import org.zkoss.util.media.Media;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zk.ui.select.Selectors;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

public class FileUploadVM {

private String filePath;
private boolean fileuploaded = false;
AMedia fileContent;

@Wire("#test")
private Window win;
@Wire("#txt")
Textbox txt;


public AMedia getFileContent() {
return fileContent;
}

public void setFileContent(AMedia fileContent) {
this.fileContent = fileContent;
}

public boolean isFileuploaded() {
return fileuploaded;
}

public void setFileuploaded(boolean fileuploaded) {
this.fileuploaded = fileuploaded;
}

@AfterCompose
public void initSetup(@ContextParam(ContextType.VIEW) Component view) {
Selectors.wireComponents(view, this, false);
Executions.getCurrent().getDesktop().getWebApp().getConfiguration().setMaxUploadSize(10 * 1024);//for larger files

}

@Command
@NotifyChange("fileuploaded")
public void onUploadPDF(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx)
throws IOException {

UploadEvent upEvent = null;
Object objUploadEvent = ctx.getTriggerEvent();
if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
upEvent = (UploadEvent) objUploadEvent;
}
if (upEvent != null) {
Media media = upEvent.getMedia();
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int min = now.get(Calendar.MINUTE);
String fileName = year+"_"+month+"_"+day+"_"+min+".pdf";
filePath = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
filePath = filePath + fileName;
System.out.println("filePath='"+filePath+"'");
Files.copy(new File(filePath), media.getStreamData());

PDFmodifier mod = new PDFmodifier(txt);//txt
filePath = mod.start(filePath);
System.out.println("Ergbnis-pfad='"+filePath+"'");
Messagebox.show("File Sucessfully altered. Press \"Show PDF\" to download file.");
fileuploaded = true;

}
}

@Command
@NotifyChange("fileContent")
public void showPDF() throws IOException {
File f = new File(filePath);
byte[] buffer = new byte[(int) f.length()];
FileInputStream fs = new FileInputStream(f);
fs.read(buffer);
fs.close();
ByteArrayInputStream is = new ByteArrayInputStream(buffer);
fileContent = new AMedia("report", "pdf", "application/pdf", is);

}
}

大大减少了java代码(虽然多了很多,但这个问题不需要):

import org.zkoss.zul.Textbox;
public class PDFmodifier {

String logText ="";
Textbox text;


public PDFmodifier(Textbox t)
{
text = t;
}

protected void printToTextbox(String txt)
{
logText += "\n"+txt;
text.setValue(logText);
}
}

一切正常,但我想改进它。感谢您提前阅读。

编辑:

索引.zul

<zk xmlns:n="native" xmlns:c="client">
<?page title="RemoveKlausNote" ?>
<window id="RemoveKlausNote"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('toolbox.pdfconverter.FileUploadVM')"
title="Bioinfo Teaching Toolbox" border="normal" width="1000px" position="center,top" mode="embedded">
<hbox>
<label value="Console log: " />
<textbox width="500px" height="200px" readonly="true" value="@bind(vm.getLogText())" multiline ="true"/>
<button label="Upload" upload="true"
onUpload="@command('onUploadPDF',upEvent=event)"> </button>

<button label="Show PDF" visible="@load(vm.fileuploaded)"
onClick="@command('showPDF')">
</button>
</hbox>

<iframe height="100%" width="100%" id="reportframe"
content="@bind(vm.fileContent)">
</iframe>

</window>

View 模型:

public class FileUploadVM {

private String filePath;
private boolean fileuploaded = false;
AMedia fileContent;

@Wire("#test")
private Window win;

LogText logText = new LogText();

public AMedia getFileContent() {
return fileContent;
}

public void setFileContent(AMedia fileContent) {
this.fileContent = fileContent;
}

public boolean isFileuploaded() {
return fileuploaded;
}

public void setFileuploaded(boolean fileuploaded) {
this.fileuploaded = fileuploaded;
}

@AfterCompose
public void initSetup(@ContextParam(ContextType.VIEW) Component view) {
Selectors.wireComponents(view, this, false);
Executions.getCurrent().getDesktop().getWebApp().getConfiguration().setMaxUploadSize(10 * 1024);//for larger files
}


@NotifyChange("logText.log")
public void setLogText(String text) {
logText.setLog(text);
}

@NotifyChange("logText.log")
public String getLogText()
{
return logText.getLog();
}

@Command
@NotifyChange("fileuploaded")
public void onUploadPDF(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx)
throws IOException {

UploadEvent upEvent = null;
Object objUploadEvent = ctx.getTriggerEvent();
if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
upEvent = (UploadEvent) objUploadEvent;
}
if (upEvent != null) {
Media media = upEvent.getMedia();


String webAppPath = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
System.out.println("webAppPath='"+webAppPath+"'");


Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int min = now.get(Calendar.MINUTE);
String originalName = media.getName();

String fileName = originalName +year+"_"+month+"_"+day+"_"+min+".pdf";
String tmpPath = PDFmodifier.getTemp();
if (!tmpPath.endsWith(File.separatorChar+"")) tmpPath = tmpPath + File.separator;
filePath = tmpPath + fileName;
System.out.println("filePath='"+filePath+"'");

Files.copy(new File(filePath), media.getStreamData());

filePath = new PDFmodifier(logText).start(filePath);
System.out.println("Ergbnis-pfad='"+filePath+"'");
Messagebox.show("File Sucessfully altered. Press \"Show PDF\" to download file.");
fileuploaded = true;
}
}

LogText 对象:

public class LogText {

public String log;

public LogText()
{
log ="Press the Upload Button to upload any PDF file. PDFmodifier will cover the unwanted area. After processing, the showPDF button will be active and you can save the modified PDF";
}

public void setLog(String txt)
{
log += "\n"+txt;
}

public String getLog()
{
return log;
}
}

PDFmodifier(我不妨展示我的核心方法 start()):

protected void printToTextbox(String txt)
{
log.setLog("\n"+txt);

}

public String start(String uploadFile) throws IOException
{
setStringVariables(uploadFile);

System.out.println("Processing inputFile='"+inputFile+"'");
File f = new File(inputFile);
if (!f.exists()) {
System.err.println("inputFile not found)");
return null;
}
long startTime = System.currentTimeMillis();
//file can be opened and normally processed
if(accessChecker(inputFile)){
coverWithRectangle(inputFile, outputFile) ;
return outputFile;
}
//file needs further work
else
{
printToTextbox("Accessing PDFsam for split...");
if (createDirectory(outputDir)) {
long startTimeSplit = System.currentTimeMillis();
boolean splitOk = splitPDF(inputFile, outputDir);
long endTimeSplit = System.currentTimeMillis();
printToTextbox("Time for splitting [ms]: "+(endTimeSplit-startTimeSplit));

if (!splitOk) {
printToTextbox("PDF couldn't be split. Exiting.");
return null;
}
else
{
long startTimeMerge = System.currentTimeMillis();
boolean mergeOk = mergePDF(getAllFiles(),tempPDF,tempCSV);
long endTimeMerge = System.currentTimeMillis();
printToTextbox("Time for merging [ms]: "+(endTimeMerge-startTimeMerge));

if (mergeOk) {
coverWithRectangle(tempPDF, outputFile);
deleteTrash();
} else {
printToTextbox("ERROR: merge failed!");
}


}
}
writeLog(outputFile);
long endTime = System.currentTimeMillis();
printToTextbox("Total time needed [ms]: "+(endTime-startTime));
printToTextbox("outputFile='"+outputFile+"'");
return outputFile;
}

编辑2:

祖尔:

<textbox width="500px" height="200px"  readonly="true" value="@bind(vm.logText)" multiline ="true"/>
<timer id="timer" delay="50" repeats="true" onTimer="@command('refreshTextbox')" />

View 模型:

String logText;
LogText log = new LogText();

@NotifyChange("logText")
public void setLogText(String txt)
{
log.log ="\n"+txt;
logText = log.log;

}

@NotifyChange("logText")
public String getLogText()
{
logText = log.log;
return logText;
}

@Command
public void refreshTextbox()
{
logText = log.log;
BindUtils.postNotifyChange(null,null,this,"logText");

}

View 模型将 Textlog 对象传递给 Pdfmodifier 的新实例。一次绝望的尝试来解决这个问题。

最佳答案

您正在混合 2 种类型:MVVM 和 MVC。窗口和文本框采用MVC方式使用。

您可以更轻松地做到这一点:

在您的虚拟机中创建:

private String textField = "Press the Upload Button to upload any PDF file. PDFmodifier will cover the unwanted area. After processing, the showPDF button will be active and you can save the modified PDF";

并提供 getter 和 setter。

在 View 模型中更改为:

<textbox width="500px" height="400px" id="txt" readonly="true" multiline ="true" value=@bind(vm.textField)"/>

现在,当想要将更改保留到 GUI 时,您可以使用

@NotifyChange("textField")

但这仅适用于 setter 和命令。

您可以在 View 模型中使用其他方法来完成此操作,例如:

BindUtils.postNotifyChange(null,null,this,"textField");

编辑:

如果您的文本框需要在文件上传繁忙时多次更新,则需要单独的线程。

如果没有,你就快到了:

public void setLogText(String text) {
logText.setLog(text);
}

public String getLogText() {
return logText.getLog();
}

删除了此处的通知更改,不需要,也是显示文本的完美解决方案。

@Command
@NotifyChange({"fileuploaded","logText"})
public void onUploadPDF(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx)
throws IOException {

UploadEvent upEvent = null;
Object objUploadEvent = ctx.getTriggerEvent();
if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
upEvent = (UploadEvent) objUploadEvent;
}
if (upEvent != null) {
Media media = upEvent.getMedia();


String webAppPath = Executions.getCurrent().getDesktop().getWebApp().getRealPath("/");
System.out.println("webAppPath='"+webAppPath+"'");


Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH);
int day = now.get(Calendar.DAY_OF_MONTH);
int min = now.get(Calendar.MINUTE);
String originalName = media.getName();

String fileName = originalName +year+"_"+month+"_"+day+"_"+min+".pdf";
String tmpPath = PDFmodifier.getTemp();
if (!tmpPath.endsWith(File.separatorChar+"")) tmpPath = tmpPath + File.separator;
filePath = tmpPath + fileName;
System.out.println("filePath='"+filePath+"'");

Files.copy(new File(filePath), media.getStreamData());

filePath = new PDFmodifier(logText).start(filePath);
System.out.println("Ergbnis-pfad='"+filePath+"'");
Messagebox.show("File Sucessfully altered. Press \"Show PDF\" to download file.");
fileuploaded = true;
}

在此命令中添加了logText的notifychange。

现在还有一些其他改进:

<button label="Upload" upload="true"
onUpload="@command('onUploadPDF',upEvent=event)"> </button>

您不会在虚拟机中询问 upEvent,因此只需将其删除即可。

public void onUploadPDF(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx)
throws IOException {

可能是这样的:

 public void onUploadPDF(
@ContextParam(ContextType.TRIGGER_EVENT) UploadEvent evt)
throws IOException {

因为您要做的唯一一件事就是从 bindContext 获取触发事件,因此无需获取该对象,并且它会删除方法中的大量样板代码。

编辑2:

看起来您需要一个单独的线程来进行处理。 I created a fiddle这样你就可以看到我是如何做到的。

但是如果链接失效了:

@Command
@NotifyChange("timer")
public void longOperation() {
timer = true;
Thread r = new Thread(new Runnable() {

@Override
public void run() {

log = "button pressed, initializing now";
sleep(5000); // this is a private method for calling Thread.sleep
log = "initialized done, processing now";
sleep(5000);
log = "finished";
timer = false;
}
});
r.start();
}

@Command
@NotifyChange({"log","timer"})
public void refreshTextbox(){
if (!timer) {
Clients.showNotification("timer stopped");
}
}

和祖尔:

关于java - 当输入以编程方式更新时,如何刷新 zk 中的文本框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686575/

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