[英]Switch between multiple JFrames
我是Java的新手,我正在嘗試進行一些測驗。 我在同一包中創建了3個JFrame。 在我的主機上,有兩個按鈕(一個用於英語版本,另一個用於德語版本)。 我想在按下這些按鈕后切換JFrame(這樣我就可以通過按“英語”來查看我的英語測驗框架並與之互動)。 查找它並沒有絲毫幫助我,因為我對它沒有真正的經驗。 甚至有可能這樣做嗎? 如果沒有,我該怎么辦?
標准方法是使用Card Layout ,它允許您在應用程序中不同點用不同的東西填充相同的JFrame時使用它。 因此,最初,您的JFrame將顯示加載屏幕,然后用戶按下按鈕,然后加載新的一組組件,而不會丟棄當前的JFrame。 在某些情況下,您可能還需要進行一些尺寸調整。
沒有看到任何代碼很難說,但是通常情況下,您要做的是:
new Frame(args);
this.dispose();
上面的代碼假定Frame
的構造函數負責啟動並使組件可見。 this.dispose();
處理當前的JFrame
(假設您的類擴展了JFrame
)。
創建一個Jframe窗口。 之后,使用所需的所有組件(如按鈕,文本字段和標簽)創建JPanels 。 確保面板的尺寸與Jframe的尺寸相同。 Panel在代碼方面與JFrame大致相同。
這段代碼將為您縫合所有內容:
panel.setSize(Jframe.getSize()) //That wont
panel.add(button); //Just remember you need to add more code to position the buttons correctly.
//If you using netbeans builder:
//You just have to use this one line in the constructor/intialiser method
frame.add(panel); //This will add the panel to the Jframe/Window
//No need to add extra code for positioning.
如果要在面板之間交換。 在按鈕按下方法中,使用此
frame.setContentPane(panel); //panel = panel you want to change too.
frame.repaint(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
frame.revalidate(); //Ensures that the frame swaps to the next panel and doesn't get stuck.
首次啟動Java應用程序時,必須設置內容窗格,否則它將顯示為空白窗口。
frame.setContentPane(panel); //Starting Panel
frame.setVisible(true); //Make the frame visible
抱歉,如果解釋不好,我沒有足夠的時間來充分解釋。
您的框架1中有兩個按鈕,對嗎? 因此,首先,雙擊顯示“英語”的按鈕。 假設該按鈕的變量名稱為jButton1。 在該按鈕內鍵入。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
EnglishFrame eng = new EnglishFrame();
eng.setVisible(true);
}
然后雙擊顯示“德語”的另一個按鈕(jButton2)。 在里面鍵入這個。
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
GermanFrame german = new GermanFrame();
german.setVisible(true);
}
this.dispose()-這將導致jFrame窗口關閉
然后,您創建其他兩種形式的對象。 (在您的情況下,英語和德語的表格)
.setVisible(true)-這將向您顯示表單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.