首页 > 解决方案 > 在代码运行时更新组件位置?

问题描述

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

我试过看多线程。但是,我认为这不是最可行的选择。此外,如果我执行多线程,我不知道我必须将哪一点代码放入单独的线程中。

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

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

标签: javaeclipseswingswtwindowbuilder

解决方案


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 线程问题 Swing 中的多线程


推荐阅读