我有一个使用 Swing 图形的 java 应用程序,该图形有一个 2D 文本字段数组,每个文本字段都在整个应用程序中正确更新其文本。在每次更改迭代时,我都会更改文本字段的文本,然后将其背景设置为绿色半秒,然后将其变回白色。问题是,在更改的第一次迭代之后,文本字段不再闪烁绿色。当我注释掉将背景转换回白色的部分时,其余部分将起作用,并且单元格将逐渐变为绿色(正确地),这表明它正在正常工作和执行。我尝试通过重新绘制和重新验证用户界面来解决这个问题,但它不起作用。这是怎么回事?
下面是我更新 UI 的代码。
try {
textfieldArray[row][col].repaint();
textfieldArray[row][col].revalidate();
textfieldArray[row][col].setBackground(Color.green);
textfieldArray[row][col].repaint();
textfieldArray[row][col].revalidate();
Thread.sleep(300);
textfieldArray[row][col].setBackground(Color.white);
textfieldArray[row][col].repaint();
textfieldArray[row][col].revalidate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
最佳答案
Swing 是一个单线程框架,它也不是线程安全的。这意味着两件事。
首先,您不应该在事件调度线程的上下文中执行任何长时间运行或阻塞的操作,并且...
其次,您永远不应该从事件调度线程的上下文之外更新/修改 UI 或 UI 所依赖的任何内容。
这意味着您的 Thread.sleep 正在阻塞 EDT,从而阻止处理绘制请求。
相反,您需要某种方法可以在指定的延迟后触发更新。如果这还不能让 Swing Timer
尖叫,我不知道还有什么可以做到
我强烈建议您花时间阅读 Concurrency in Swing了解为什么您的代码无法工作的背景,可能是 How to Use Swing Timers寻求解决方案
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField field;
public TestPane() {
setLayout(new GridBagLayout());
field = new JTextField("All your bases beloging to us", 20);
JButton blink = new JButton("Blink");
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
field.setForeground(null);
field.setBackground(null);
}
});
timer.setRepeats(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(field, gbc);
blink.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
field.setForeground(Color.WHITE);
field.setBackground(Color.GREEN);
timer.start();
}
});
add(blink, gbc);
}
}
}
关于Java swing 图形未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52731997/