[英]Java swing graphics not updating
我有一個使用Swing圖形的Java應用程序,該圖形具有2D文本字段數組,每個文本字段都在整個應用程序中正確更新其文本。 每次更改時,我都會更改文本字段的文本,然后將其背景變為綠色半秒鍾,然后將其變回白色。 問題是,在第一次更改之后,文本字段不再閃爍綠色。 當我注釋掉將背景轉換回白色的部分時,其余部分起作用,並且單元逐漸(正確)逐漸變為綠色,這表明它正在正常運行。 我試圖通過重新粉刷和重新驗證UI來解決此問題,但是它不起作用。 到底是怎么回事?
下面是我的代碼,用於更新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
,我不知道該怎么辦
我強烈建議花點時間閱讀Swing中的並發性,以了解為什么代碼無法正常工作的背景以及可能如何使用Swing計時器的解決方案
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.