Re: [問題] 讓兩個JFrame互斥(一次只能Enabled一個 …

看板java作者 (sbr)時間16年前 (2009/06/07 14:48), 編輯推噓4(401)
留言5則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《kkman0120 (kk)》之銘言: : 我目前有兩個JFrame a跟b : a是主要的Frame : 是整個程式流程的主Frame... : 我想在某個事件發生後才呼叫b這個frame : 然後b被呼叫時a不可以被使用... : 等到b視窗被關閉後才可以繼續使用a : 我是有在b被喚起的那段程式碼上下各用a.setEnable(false) 跟setEnable(true) : 去包住b的那行程式碼 : 可是這樣還是沒有用 可以改用 modal dialog 來實做 b 的部分。 一個 java.awt.Dialog/javax.swing.JDialog 的 modal property 設定為 true 後(必須在 dialog 成為 displayable 之前)就成了 modal dialog。 當 modal dialog 成為 visible(執行 setVisible(true) 操作),calling thread 會 block 直到 dialog 被 dispose or hide。而且 modal dialog 出現時也會使得 其 owner frame/dialog/window 變成無法操作。 從 JRE 1.6 開始,modal 模式還可細分為三種: application modal document modal toolkit modal 其差異可以等到你有需要時再去看。 你先跑一下這個簡單的 demo code,看看是否就是你想要的效果。 package demo.swing; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; public class UsingModalDialog { public static void main(String[] args) { final JFrame frm = new JFrame("Main Frame"); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Click Me"); frm.getContentPane().add(button, BorderLayout.SOUTH); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JDialog dialog = new JDialog(frm); dialog.setModal(true); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setTitle("I am a modal dialog."); dialog.getContentPane().add( new JLabel("Try to click the button in the main frame.")); dialog.setSize(300, 300); dialog.setLocationRelativeTo(frm); dialog.setVisible(true); // block here until dialog is // disposed/hidden System.out.println("You close the dialog."); } }); frm.setSize(400, 400); frm.setLocationRelativeTo(null); frm.setVisible(true); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.173.138.178

06/07 14:50, , 1F
哦哦, 看起來不錯!!
06/07 14:50, 1F

06/07 15:34, , 2F
感謝 但是能否請問一下假如我的,main裡就是A這個Frame
06/07 15:34, 2F

06/07 15:36, , 3F
的程序內容的話 那該怎麼改?
06/07 15:36, 3F

06/07 15:38, , 4F
這的確是我要達到的功能QQ
06/07 15:38, 4F

06/07 16:16, , 5F
謝謝你 我會了 關鍵是dialog.setModal(true);這樣就ok了
06/07 16:16, 5F
文章代碼(AID): #1AAsAz33 (java)
文章代碼(AID): #1AAsAz33 (java)