gpt4 book ai didi

java - JFrame 在连续运行代码时卡住

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

我在使用 JFrame 时遇到问题,它会卡住连续运行代码。下面是我的代码:

  1. 单击 btnRun 后,我调用了函数 MainLoop():

    ActionListener btnRun_Click = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
    MainLoop();
    }
    };
  2. MainLoop() 的实现:

    void MainLoop()
    {
    Hopper = new CHopper(this);
    System.out.println(Hopper);
    btnRun.setEnabled(false);
    textBox1.setText("");
    Hopper.getM_cmd().ComPort = helpers.Global.ComPort;
    Hopper.getM_cmd().SSPAddress = helpers.Global.SSPAddress;
    Hopper.getM_cmd().Timeout = 2000;
    Hopper.getM_cmd().RetryLevel = 3;


    System.out.println("In MainLoop: " + Hopper);

    // First connect to the validator
    if (ConnectToValidator(10, 3))
    {
    btnHalt.setEnabled(true);
    Running = true;

    textBox1.append("\r\nPoll Loop\r\n"
    + "*********************************\r\n");
    }

    // This loop won't run until the validator is connected
    while (Running)
    {
    // poll the validator
    if (!Hopper.DoPoll(textBox1))
    {
    // If the poll fails, try to reconnect
    textBox1.append("Attempting to reconnect...\r\n");
    if (!ConnectToValidator(10, 3))
    {
    // If it fails after 5 attempts, exit the loop
    Running = false;
    }
    }
    // tick the timer
    // timer1.start();
    // update form
    UpdateUI();
    // setup dynamic elements of win form once
    if (!bFormSetup)
    {
    SetupFormLayout();
    bFormSetup = true;
    }

    }

    //close com port
    Hopper.getM_eSSP().CloseComPort();

    btnRun.setEnabled(true);
    btnHalt.setEnabled(false);
    }
  3. MainLoop() 函数中,while 循环持续运行,直到 Running 为 true 问题是,如果我想停止 while 循环,我必须将 Running 设置为 false通过另一个按钮 btnHalt 完成:

    ActionListener btnHalt_Click = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
    textBox1.append("Poll loop stopped\r\n");
    System.out.println("Hoper Stopped");
    Running = false;
    }
    };

但是btnHalt没有响应,整个帧都卡住了,也没有在 textarea 中显示任何日志。

最佳答案

Swing 是一个单线程框架。也就是说,有一个线程负责将所有事件分派(dispatch)给所有组件,包括重绘请求。

任何停止/阻止该线程的操作都会导致您的 UI“挂起”。

Swing 的第一条规则,永远不要在事件调度线程上运行任何阻塞或耗时的任务,相反,您应该使用后台线程。

这会让你陷入 Swing 的第二条规则。切勿在 EDT 之外创建、修改或与任何 UI 组件交互。

有多种方法可以解决这个问题。您可以使用 SwingUtilities.invokeLaterSwingWorker

SwingWorker 通常更容易,因为它提供了许多简单易用的方法,可以自动重新同步对 EDT 的调用。

通读 Concurrency in Swing

已更新

只是为了让你明白;)

您的 MainLoop 方法不应在 EDT 上下文中执行,这是非常糟糕的。

此外,您不应该与除 EDT 之外的任何线程中的任何 UI 组件进行交互。

关于java - JFrame 在连续运行代码时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15540319/

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