gpt4 book ai didi

java - 等待 AWT 重绘完成

转载 作者:行者123 更新时间:2023-12-03 05:09:59 25 4
gpt4 key购买 nike

我有一个框架,它全部是一种颜色,但在角落里有一些文字。我设置颜色,实际从显示器读取颜色,然后根据这些测量值进行一些计算。

问题是,调用repaint()会导致Frame在我进行测量之后被绘制。我假设这是由于 repaint() 委托(delegate)给 EDT,但由于实际绘画工作之前/期间发生的测量,我得到了不正确的结果。

我最初的想法是在绘制完成时放置一个监听器,但我重新绘制以更新文本的频率比更新颜色的频率要高得多,而且我不想监听这些事件。如何等待实际绘画任务完成后再进行测量?

最佳答案

令人惊叹的发现......

EventQueue.invokeLater(new Runnable() {
@Override
public void run() {

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
@Override
public void eventDispatched(AWTEvent event) {

PaintEvent pe = (PaintEvent) event;

String type = "";
if (pe.getID() == PaintEvent.PAINT) {
type = "PAINT";
} else if (pe.getID() == PaintEvent.PAINT_FIRST) {
type = "PAINT_FIRST";
} else if (pe.getID() == PaintEvent.PAINT_LAST) {
type = "PAINT_LAST";
} else if (pe.getID() == PaintEvent.UPDATE) {
type = "UPDATE";
}

System.out.println(type + "; pe.UpdateRec = " + pe.getUpdateRect() + "; pe.component = " + pe.getComponent());

}
}, AWTEvent.PAINT_EVENT_MASK);

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);


}
});

现在,因为重绘请求可以快速思考,所以我很想在其中放置一个小的“延迟”,该延迟会在最后一个请求完成后不久触发......

private Timer updateTimer;

// ...

EventQueue.invokeLater(new Runnable() {
@Override
public void run() {

updateTimer = new Timer(250, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// Update compulations here...
}
});
updateTimer.setRepeats(false);
updateTimer.setCoalesce(true);

Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {

@Override
public void eventDispatched(AWTEvent event) {
updateTimer.restart();
}
}, AWTEvent.PAINT_EVENT_MASK);
}
}

这个想法是在最后一次重绘请求和开始编译之间至少留出 250 毫秒的时间。您可能想尝试一下这些值,看看什么适合您......

更新

您也可以尝试JComponent.paintImmediately

Paints the specified region in this component and all of its descendants that overlap the region, immediately.

It's rarely necessary to call this method. In most cases it's more efficient to call repaint, which defers the actual painting and can collapse redundant requests into a single paint call. This method is useful if one needs to update the display while the current event is being dispatched.

关于java - 等待 AWT 重绘完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12577386/

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