2014-04-10 44 views
-2

我有jFrame1,兩個JTextField。其中一個文本字段應加載我的jFrame2中的數據。在我的jFrame1中,我有一個打開jFrame2的按鈕。當您按下按鈕打開jFrame2時,您可以看到4個按鈕,並且當您按下其中一個按鈕時,jframe2應該關閉並在我的一個文本字段中加載一個字符串。發送從jframe2到jframe1的字符串

任何人都知道我該怎麼做?因爲我已經嘗試了幾個代碼,並沒有離開我。

這是我的示例代碼:

public class jFrame1 extends javax.swing.JFrame{ 

    public JTextField txt1; 
    private JButton btn1; 

    btn1.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
     jFrame2 jframe2 = new jFrame2(this); 
     jframe2.setVisible(true); 
     } 
    }); 


    ..... 

} 


public class jFrame2 extends javax.swing.JFrame{ 

    private JFrame jframe1; 

    public jFrame2(JFrame jframe){ 
     this.jframe1 = jframe; 
    } 

    ... 
    jframe1.txt1.setText("Hallo!"); 
    this.dispose(); 
    ..... 

} 
+2

你有什麼試過?顯示你的嘗試,然後我們會幫助你:)!沒有代碼=什麼都沒有發生< - 這是StackOverflow的golder原則! –

+0

編寫一個getter或者讓String爲public並使用JFrame的References直接訪問getter或String。 –

+0

是的!對不起,在這裏你可以閱讀我的示例代碼 – Despotars

回答

0

有太多的方法,

其中之一是提供一個構造函數,以你的框架與String參數並傳遞價值。

例如,

public class jFrame1 extends javax.swing.JFrame{ 

    public JTextField txt1; // Hope you have initialized this somewhere in your code else you will face a NPE. 
    private JButton btn1; 

    btn1.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
     jFrame2 jframe2 = new jFrame2(this, txt1.getText()); 
     jframe2.setVisible(true); 
     } 
    }); 


    ..... 

} 


public class jFrame2 extends javax.swing.JFrame{ 

    private JFrame jframe1; 
    private String text; 
    public JTextField txtDemo; 

    public jFrame2(JFrame jframe){ 
     this.jframe1 = jframe; 
    } 

    public jFrame2(JFrame jframe, String text){ 
     this.jframe1 = jframe; 
     txtDemo = new JTextField(text); 
    } 

    ... 

} 

你可以找到在這個SO question還答案。

在執行此操作之前,請參考The Use of Multiple JFrames, Good/Bad Practice?的答案,對JFrame和Swing給出了一個很好的解釋。

+0

感謝您的回覆。一個問題,在代碼的最後,在這個句子中:「jframe1.txt1.setText(text);」編譯器告訴我這一點:「找不到符號符號:變量txt1位置:JFrame類型的變量jframe1」 – Despotars

+0

你知道我該如何解決嗎? – Despotars

+1

如果您將運行,您將得到一個空指針,因爲jframe1中的'txt1'未初始化,並且此處演示了將'jframe1'中的'txt1'文本發送到'jframe2',並且將顯示此文本在'jframe2'的'txtDemo'中....請從java swing的基本教程開始。 –