gpt4 book ai didi

java - JFrame没有实时更新

转载 作者:行者123 更新时间:2023-11-30 03:06:19 26 4
gpt4 key购买 nike

我的项目包含两部分:逻辑模块和 GUI 界面。两人都将自己的引用资料发送给对方。

当用户发送消息时,我有一个关键监听器。在这个监听器中,我在逻辑之前调用相同的 gui 更改,在逻辑之后调用相同的更改。问题是这两个更改将在执行结束时同时显示。

如何强制实时更新GUI?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main {

// Init DecisionEngine and GUIApplication
private static final Logic _logic = new Logic();
private static final GUI _gui = new GUI();

public static void main(String[] args) {
// Set DecisionEngine reference in GUIApplication and viceversa
_gui.setLogicReference(_logic);
_logic.setGUIRefecence(_gui);

// User send a message
_gui.textInput.addKeyListener(new KeyListener(){
@Override public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ENTER) {

_gui.somethingChaged1();// CHANGE 1 GUI
_logic.thinking();// LOGIC PROCESSING (3sec)
_gui.somethingChaged2();// CHANGE 2 GUI

e.consume();// Stopping adding an Enter after message
}
}
@Override public void keyTyped(KeyEvent e) {}
@Override public void keyReleased(KeyEvent e) {}
});
}

private static class Logic {
GUI gui_ref;

public Logic() {}
private void setGUIRefecence(GUI _gui) {gui_ref = _gui;}
private void thinking() {
try {Thread.sleep(3000);} catch (InterruptedException ex) {}
}
}

private static class GUI {

Logic logic_ref;
private JFrame frame;
public JTextArea textInput;
private JLabel isTyping;

public GUI() {

frame = new JFrame();
textInput = new javax.swing.JTextArea(5, 20);
isTyping = new JLabel("Normal mode");

frame.setSize(new Dimension(200,300));
frame.add(textInput, BorderLayout.PAGE_START);
frame.add(isTyping, BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
frame.setVisible(true);
}

private void setLogicReference(Logic _logic) {logic_ref = _logic;}
private void somethingChaged1() {isTyping.setText("loading...");System.out.println("status changed in 'loading...'");}
private void somethingChaged2() {isTyping.setText("is done.");System.out.println("status changed in 'is done.'");}
}

}

最佳答案

只是为了澄清我在 markbernard's answer 中发表的评论,应该这样做:

    @Override public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
// Change the GUI from the EDT (current thread):
_gui.somethingChaged1();

// start a new Thread to do the long processing:
Thread t = new Thread(new Runnable() {
public void run() {
_logic.thinking();// LOGIC PROCESSING (3sec)

// when the processing in this new Thread is complete,
// update the GUI again via the EDT:
SwingUtilities.invokeLater(new Runnable(){
public void run() {
_gui.somethingChaged2();
}
});
}
}, "Logic Code");
t.start();

e.consume();// Stopping adding an Enter after message
}
}

关于java - JFrame没有实时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34701386/

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