1

I have a client-server application and i am using swing in the client side. My swing client has one main window (jframe) and lots of panels, toolbars and menubar in it. I want to remove all client action/mouse events (or simply grab and do nothing) while client is waiting response from server by means of glasssPane. Here is the code i wrote:

private final static MouseAdapter mouseAdapter = new MouseAdapter() 
{
  public void mouseClicked(MouseEvent e) 
  {
   System.out.println("MouseClicked..!");
  }
 };

private static Cursor WAIT_CURSOR = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
private static Cursor DEFAULT_CURSOR = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);

and

public static void startWaitCursor(JComponent comp)
{
  MainWindow root = ((MainWindow) comp.getTopLevelAncestor());

  root.getGlassPane().setCursor(WAIT_CURSOR);
  root.getGlassPane().addMouseListener(mouseAdapter);
  root.getGlassPane().setVisible(true);
}

public static void stopWaitCursor(JComponent comp)
{    
  MainWindow root = ((MainWindow) comp.getTopLevelAncestor()); 

  root.getGlassPane().setCursor(DEFAULT_CURSOR);
  root.getGlassPane().setVisible(false);
}

but i am not able to manage the grab mouse events. Changing cursors at the glassPane is working fine but either i am not able to add mouseAdapter or am not able to make glasssPane become to the top level component.

Any idea?

Thanks.

4

2 回答 2

1

我意识到我的代码正在运行,但我的问题与线程有关。我的代码是这样的:

startWaitCursor(); 
work(); // server request that takes time 
stopWaitCursor();

并将其更改为:

startWaitCursor(); 
SwingUtilities.invokeLater(new Runnable() {
poblic void run() { 
try 
{ 
work(); // server request 
} 
finally 
{ 
stopWaitCursor(); 
}

通过进行此修改,我可以在客户端等待来自服务器的响应时看到我在 startWaitCursor() 方法中所做的设置。

但是还是有一个小问题。在 startWaitCursor() 方法中,我禁用了玻璃窗格的键、鼠标和焦点事件,但即使显示 glassPane,主框架仍会捕获事件。

addMouseListener(new MouseAdapter() {});
addMouseMotionListener(new MouseMotionAdapter() {});
addKeyListener(this);
setFocusTraversalKeysEnabled(false);

在服务器响应到达客户端并调用 stopWaitCursor() 方法后,主框架中处理的事件。

如果我在客户端等待时禁用我的应用程序的主框架,而不是将光标更改为 wait_cursor,如果我没有禁用主框架,则光标正在更改但事件排队。

干杯...

于 2010-02-18T10:14:30.630 回答
1

在挖掘了几天的摆动线程问题后,我终于找到了真正的答案:SwingWorker

现在我的最终代码是这样的,

startWaitCursor();
SwingWorker worker = new SwingWorker() {
   public Object doInBackground() 
   {
      doWork(); // time consuming server request
      return null;
   }
   public void done() 
   {
      stopWaitCursor();
   }
};
worker.execute();

在 startWaitCursor() 方法中,我将玻璃窗格设置为可见(具有 alpha 值背景),显示一条消息以警告用户正在执行耗时的工作,将光标设置为 wait_cursor(沙漏)并使用所有键、鼠标事件。这就对了。

通过使用 SwingWorker,我的客户端实际上是响应式的(它就像没有发出服务器请求一样工作)但是由于我显示玻璃窗格并消耗所有键和鼠标事件,所以感觉就像没有响应。

真是一种解脱.. SwingWorker 摇滚...

干杯..

于 2010-02-21T13:16:27.480 回答