最近實作了一個Frame,透過這個Frame可以將main thread block住。
如此一來,如果應用程式需要依序開啟幾個Frame而且 需視前一個Frame的結果來決定後者Frame的樣式便可以派上用場。
舉個實用例來說
如果要設計一個登入Frame,登入成功後才show出主 Frame,這時就可以派上用場
code sample :
BlockFrame.java
public class BlockFrame extends JFrame
{
public final static int BLOCKER_BLOCK = -1;
public final static int BLOCKER_NONE = 1;
protected int blocker = BLOCKER_BLOCK;
public int getBlocker()
{
return blocker;
}
protected synchronized void disposeNonBlock()
{
this.dispose();
blocker = BLOCKER_NONE;
notify();
}
public synchronized void doBlock()
{
while(this.getBlocker() == BLOCKER_BLOCK)
{
try
{
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
Login.java
public class LoginFrame extends BlockFrame implements ActionListener
{
protected JButton mybutton = new JButton();
public LoginFrame
{
// do someting here for GUI
mybutton.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
// do someting here for login when actionPerformed
// 關閉且解除 block狀態
disposeNonBlock();
}
}
Main.java
public class Main
{
public static void main(String[] args) throws Exception
{
try
{
LoginFrame frame = new LoginFrame();
// this will block main thread
frame.doBlock();
// after block, do someting for main frame or otherelse
}
catch(Exception ex)
{
ex.printStackTrace();
}
new Main();
}
}
留言列表