gpt4 book ai didi

java - 在线程进行额外处理之前和之后重新绘制玻璃板

转载 作者:行者123 更新时间:2023-12-01 14:15:54 25 4
gpt4 key购买 nike

我正在尝试使用玻璃 Pane 使框架变灰,同时单独的线程执行一些图像处理(img proc)。在 img proc 线程完成后,玻璃板应该再次变得不可见。我已经确认玻璃 Pane 运行正常,但在 img proc 线程(实际上在等待和通知工作的情况下按预期执行)启动之前不会发生重绘。这是我所拥有的:

GlassPane 类:

class GlassPane extends JComponent implements MouseListener
{
GlassPane()
{
super();
setLayout(new BorderLayout());
setOpaque(false); // So that Color's alpha channel is used
addMouseListener(this);
}
@Override
protected void paintComponent(Graphics g)
{
Rectangle bounds = g.getClipBounds();

g.setColor(new Color(255,255,255,160));

g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
}
...
}

构建框架的组件时:

gPane = new GlassPane();
rootFrame.setGlassPane(gPane);
setGlassPane( false );
...
public void setGlassPane( boolean gray )
{
if( gray )
keyCatcher.disable();
else
keyCatcher.enable();

gPane.setVisible(gray);
gPane.repaint(); // Also tried gPane.repaint(0);
gPane.invalidate();
}

在按钮的操作监听器中:

...
System.out.println( "Answer button pressed..." );
ctrlr.grayOut();

new Thread( new Runnable()
{
public void run(){
int responses[];
ImgProc ip = new ImgProc(ctrlr);
ArrayList<ColorModel> model = ctrlr.getColorModel();
responses = ip.findResponses( camContent.getCrntImage(), model, (source == ansAndDisplayBtn) );
ctrlr.setResponses(responses);
synchronized(lock)
{
lock.notifyAll();
System.out.println( "Notified..." );
}
}
}).start();

synchronized(lock)
{
try {
System.out.println( "Waiting..." );
lock.wait();
System.out.println( "Responses retreived..." );
} catch (InterruptedException e1) {
e1.printStackTrace();
}
qContent.answer();
qContent.updateResponses();

if( scrnMode )
{
proj_qContent.answer();
proj_qContent.updateResponses();
}
}
ctrlr.showFull();
...

其中 ctrlr.grayOut()ctrlr.showFull() 只是:

public void grayOut()
{
((MainUI) mainUI).setGlassPane(true);
}

public void showFull()
{
((MainUI) mainUI).setGlassPane(false);
}

我已经阅读了很多内容 Painting in AWT and Swing以及执行此类操作的其他线程。在我看来,我正在做与那些成功者相同的事情......我是否缺少一些微妙的东西?

最佳答案

此:lock.wait(); 会阻塞事件分派(dispatch)线程,以便不会发生任何绘制。我会使用 SwingWorker为了繁重的任务。也就是说,将图像处理放入 doInBackground() 中,并将 wait 之后的内容放入 done() 中。

// Inform the user the task is running
ctrlr.grayOut();

new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
// process the image
...
return null;
}

@Override
protected void done() {
// Everything done, inform the user
...
ctrlr.showFull();
}
}.execute();

关于java - 在线程进行额外处理之前和之后重新绘制玻璃板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18106761/

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