gpt4 book ai didi

java - JTextPane 文本可能由于范围问题而未更新

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

我正在尝试更改 JTextPane 的内容。我认为问题在于范围问题。您无法编译此代码,但您明白了...由于多线程,这可能是一个困难的问题。 TYIA

C:\ucdhb2\gaia\inigui\inigui15\src\inigui13.java:259: error: local
variable theframe is accessed from within inner class; needs to be declared final
theframe.mainfield.getStyledDocumemt().insertString(1, "hellooo",
null);
^ C:\ucdhb2\gaia\inigui\inigui15\src\inigui13.java:259: error: cannot
find symbol
theframe.mainfield.getStyledDocumemt().insertString(1, "hellooo",
null);
^ symbol: method getStyledDocumemt() location: variable mainfield of type JTextField
2 errors

代码

   class inigui13 extends applet  {

Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
JTextField mainfield;

public void init() {

inigui13 theframe = new inigui13();
theframe.setSize(700, 525);
theframe.setVisible(true);

try {

echoSocket = new Socket("192.168.2.3", 9900);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream() ) );
} catch (UnknownHostException e) {

System.err.println("Sstemexit");
System.exit(1);

} catch (IOException e) {

System.err.println("IOFailed");
System.exit(1);
}


Runnable readsock = new Runnable() {

public void run() {

boolean recvread = true;

while( recvread ) {

BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));

try {


theframe.mainfield.getStyledDocumemt().insertString(1, "hellooo", null);

} catch( IOException e ){}

}

}

try {

out.close();
in.close();
echoSocket.close();
} catch( IOException e ){}


}

};


Thread readsockt = new Thread(readsock);
readsockt.start();
}


public inigui13 {

mainfield = new JTextPane;
this.add(mainfield);
}
};
}

最佳答案

切勿永远从任何线程其他更新、更改或修改任何 UI 组件,然后是事件调度线程 。这几乎涵盖了 Swing 的前 10 条戒律。

您的代码是何时使用 SwingWorker 的经典示例.

您可能想通读 Concurrency in Swing

示例

public class StreamReaderWorker extends SwingWorker<Object, String> {

private JTextPane field;

public StreamReaderWorker(JTextPane field) {
this.field = field;
}

@Override
protected void process(List<String> chunks) {
for (String chunk : chunks) {
try {
field.getStyledDocument().insertString(1, "chunk", null);
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
}

@Override
protected String doInBackground() throws Exception {
boolean recvread = true;
while (recvread) {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
try {
publish("hellooo");
} catch (IOException e) {
}
}
return null;
}
}

关于java - JTextPane 文本可能由于范围问题而未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13618605/

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