如何在返回前暂停/等待

  • 本文关键字:暂停 等待 返回 java
  • 更新时间 :
  • 英文 :


搜索数据数组会生成一个可单击的结果按钮面板。 我需要强制 "return recordNumber;" 等待执行,直到单击其中一个结果,以便返回可以返回适当的 recNo。

每次我尝试实现 wait(( 通知(( 结果按钮面板都无法填充

public int Search() throws InterruptedException
{
JFrame searchFrame = new JFrame();
JPanel searchPanel = new JPanel();
searchPanel.setLayout( new BoxLayout( searchPanel, BoxLayout.Y_AXIS ) );
resultsButton = new JButton[ recordCount ];
resultsRecNo = new int[ recordCount ];
searchString = JOptionPane.showInputDialog( this, "Search for", "" );
System.out.println( " searchString = "+searchString );
resultNo = 0;
if ( searchString != null && searchString.isEmpty() == false  )
{
offset = 0;
for ( recNo = 0; recNo < recordCount; recNo++ )
{
byteArray = Arrays.copyOfRange( dataArray, offset, offset+recordSize );
tmp = new String( byteArray );
found = tmp.toLowerCase().contains( searchString.toLowerCase() );
if ( found == true )
{
resultsRecNo[ resultNo ] = recNo + 1;
resultsButton[ resultNo ] = new JButton( "recNo"+(recNo+1)+" : "+tmp );
// create results buttons
resultsButton[ resultNo ].addActionListener( new ActionListener() { int getRecNo = resultsRecNo[ resultNo ]; public void actionPerformed( ActionEvent e ) { setRecord( getRecNo ); searchFrame.dispatchEvent(new WindowEvent(searchFrame, WindowEvent.WINDOW_CLOSING)); } } );
searchPanel.add( resultsButton[ resultNo ] );
resultNo++;
}
offset = offset + recordSize;
}
if ( resultNo == 0 )
{
resultsButton[ resultNo ] = new JButton( " No Results Found " );
resultsButton[ resultNo ].addActionListener( new ActionListener() { int getRecNo = 0; public void actionPerformed( ActionEvent e ) { setRecord( getRecNo ); searchFrame.dispatchEvent(new WindowEvent(searchFrame, WindowEvent.WINDOW_CLOSING)); } } );
searchPanel.add( resultsButton[ resultNo ] );
}
JScrollPane resultsScrollPane = new JScrollPane( searchPanel );
resultsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
resultsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
resultsScrollPane.setLayout(new ScrollPaneLayout());
searchFrame.add( resultsScrollPane );
searchFrame.setSize( frameWidth, frameHeight );
searchFrame.setVisible( true );
}
System.out.println( "getRecNo = "+getRecNo+" : recordNumber = "+recordNumber );
return recordNumber;
} /////////////////////////// End Of Method Search()
public void setRecord( int recno)
{
recordNumber = recno;
System.out.println("setRecord : "+recordNumber);
}

我需要返回记录编号来等待,直到其中一个结果按钮被点击

在处理 Swing 或 JavaFX 时,永远不应该阻塞主线程,否则 UI 会冻结,这是糟糕的用户体验。查看此 Oracle 教程,了解如何在单独的线程上异步处理此类任务。

但是,在您的特定情况下,我相信它要简单得多。如果你想对用户点击某个按钮做出反应,那么在侦听器中做你需要做的任何事情会更有意义。你为什么不在侦听器中实现你的逻辑,而不是尝试将所有内容都融入search方法中?这样,您的函数将立即返回,并且应用程序仅在用户单击发生时才会对用户单击做出反应,并且您不会冻结任何内容。

如果你真的需要来自用户的同步交互(即用户在任何事情发生之前需要执行的操作(,你可以像从用户那里收集搜索字符串一样,使用一个对话框,正如气垫船满鳗鱼指出的那样。

作为旁注,这里有一些提示,可以使你的代码更容易推理,这将是解决问题的第一步:

  • 您似乎有大量的全局变量。这不好,尽量保持尽可能少的状态,甚至没有状态。
  • 不要把你的听众写在一行上,这是不可读的
  • 将您的方法拆分为大约 5-15 行的较小方法,并具有好名称

最新更新