如何在其他JFrame中订阅GUI事件

时间:2011-11-15 14:32:22

标签: java events subscribe

从另一个JFrame订阅活动的最佳做法是什么?例如,我有一个“设置”表单,当用户在设置表单上按下ok时,我希望主表单知道这一点,以便它可以检索设置。

感谢。

这是我理想的界面:

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();
}

3 个答案:

答案 0 :(得分:2)

有人发布了一个事件,事情发生了变化,这里是设置。注册此特定事件的订阅者会收到有关它的通知并可以执行其工作,此处获取设置。这称为发布者/订阅者。

为此,您可以使用Eventbus或自行实施更小的内容。

答案 1 :(得分:2)

一种方法是只有一个JFrame。所有其他“自由浮动顶级容器”可以是模态对话框。访问主GUI将被阻止,直到当前对话框被解除,主框架中的代码可以在解除后检查对话框的设置。

答案 2 :(得分: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;
}