【问题标题】:Updating a components position while code is running?在代码运行时更新组件位置?
【发布时间】:2019-07-09 08:12:04
【问题描述】:

我正在使用 Eclipse WindowBuilder 为我的 Java 程序构建 GUI。我目前被卡住了,因为我创建了一个按钮,并且我给 X 和 Y 位置提供了不同的变量。当单击按钮并发出事件时,这些变量会在“While”循环中发生变化。

我曾尝试研究多线程。但是,我认为这不是最可行的选择。另外,如果我做多线程,我不知道我必须将哪一点代码放在单独的线程中。

New button = Button button(X, Y, 100,100);

我正在尝试增加 x 和 Y 坐标

【问题讨论】:

  • 该按钮不会监控xy 的值。它只是使用当前值创建的。当 while 循环更改值时发送事件?按钮没有可以用来更新位置的方法setPosition()(或setX()setY())吗?
  • 它是 JButton 吗?如果我们能看到您的按钮实例化将会很有帮助。
  • 目前不在我的电脑上,但我会用代码更新。
  • 这是 Swing 还是 SWT?这些是完全不同的 GUI 系统。
  • 请提供minimal reproducible example,以便我们更容易理解您的需求,也可以改进您的代码。

标签: java eclipse swing swt windowbuilder


【解决方案1】:

Awt 和 Swing 不是线程安全的,因此,如果您尝试在同一个线程中更新 UI,您将出现“应用程序冻结”行为,并且如果您多次单击按钮,它的位置不会改变。您可以在执行循环的同时禁用该按钮,并且在开始循环之前检查该按钮是否未被禁用。例如:

walkerButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        walkerButtonActionPerformed(evt);
    }
});

private void walkerButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             

    // if walker button is disabled exit the method
    if (!walkerButton.isEnabled()) {
        return;
    }       

    // Disable the button before starting the loop
    walkerButton.setEnabled(false);

    int steps = 20;
    int stepDistance = 2;        

    while (steps > 0) {  
        // Set the walker button new location          
        int x = walkerButton.getX() + stepDistance;
        int y = walkerButton.getY() + stepDistance;
        walkerButton.setLocation(x, y);
        steps--;
    }  

    // Enable the button after the loop execution
    walkerButton.setEnabled(true);
} 

另请阅读: Java awt threads issue Multithreading in Swing

【讨论】:

  • 非常感谢,请问为什么停止按钮会起作用?
  • 因为 Awt 和 Swing 不是线程安全的,所以我改进了我的答案以帮助您更好地理解
  • @JustInitforsomeviews 如果答案可以帮助您解决问题,请投票
  • 喜欢,抱歉我对 StackOverflow 很陌生,所以还不知道礼仪:) @Eduardo Eljaiek
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多