2011-11-15 3 views
2

別のJFrameからイベントを購読するベストプラクティスは何ですか?たとえば、私は「設定」フォームを持っています。ユーザーが設定フォームで大丈夫を押すと、メインフォームでこれを知り、設定を取得できます。他のJFrameのGUIイベントを購読する方法

ありがとうございました。

public void showSettingsButton_Click() { 
    frmSettings sForm = new sForm(this._currentSettings); 
    //sForm.btnOkay.Click = okayButtonClicked; // What to do here? 
    sForm.setVisible(true); 
} 

public void okayButtonClicked(frmSettings sForm) { 
    this._currentSettings = sForm.getSettings(); 
} 
+0

は*「別のフォームからイベントをサブスクライブするためのベストプラクティスは何ですか?」 *あなたは 'JFrame'を意味しますか?私はあなたのことを話していないことに注意してください。 –

+0

@AndrewThompson申し訳ありません。 C#では、フォームと呼ばれます。まだJavaの用語に精通していません。 – Eric

+1

A-Ha! Netbeansはまた、開発者を「フォーム」として「JFrames」と呼んでいる。質問を編集していただきありがとうございます。 –

答えて

2

誰かが何かがここで、設定を変更したこと、イベントをパブリッシュします。

は、ここに私の理想的なインタフェースです。この特定のイベントに登録した加入者は、それについて通知され、彼の仕事を行うことができます。ここで設定を取得します。これはパブリッシャ/サブスクライバと呼ばれます。

この場合、Eventbusを使用するか、自分で小さなものを実装することができます。

2

1つのアプローチは、ただ1つのJFrameを持つことです。他のすべての「フリーフローティングトップレベルコンテナ」はすべてモーダルダイアログです。メインGUIへのアクセスは、現在のダイアログが終了するまでブロックされ、メインフレーム内のコードは、ダイアログが閉じられた後でダイアログの設定をチェックすることができます。

0

興味のある方は、ここで私が最後にやったことがあります。私はそれが最良の方法であるかどうかはわかりませんが、私の目的のために働いています。

// Method called when the "Show Settings" button is pressed from the main JFrame 
private void showSettingsButton_Click() { 

    // Create new settings form and populate with my settings 
    frmSettings sForm = new frmSettings(this.mySettings); 

    // Get the "Save" button and register for its click event... 
    JButton btnSave = sForm.getSaveButton(); 
    btnSave.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseClicked(MouseEvent evt) { 
       SaveSettings(sForm); 
      } 
    }); 

    // Show the settings form 
    sForm.setVisible(true); 
} 

// Method called whenever the save button is clicked on the settings form 
private void SaveSettings(frmSettings sForm) { 
    // Get the new settings and assign them to the local member 
    Settings newSettings = sForm.getSettings(); 
    this.mySettings = newSettings; 
} 

そして、もし、私のように、あなたは.NETの観点から来ている、ここではC#バージョンである:

private void showSettingsButton_Click(object sender, EventArgs e) 
{ 
    frmSettings sForm = new frmSettings(this.mySettings); 
    sForm.btnSave += new EventHandler(SaveSettings); 
    sForm.Show(); 
} 

private void SaveSettings(object sender, EventArgs e) 
{ 
    frmSettings sForm = (frmSettings)sender; // This isn't the exact cast you need.. 
    Settings newSettings = sForm.Settings; 
    this.mySettings = newSettings; 
} 
関連する問題