将ActionLister添加到父

时间:2016-12-03 23:56:37

标签: java swing actionlistener

如果标题没有意义,我很抱歉,我会在下面详细解释。

我有一个班级

public View implements ActionListener {
    JFrame frame = new JFrame();
    frame.add(new controls().initialise());

}

和一个实现模型中某个部分的J组件的辅助类(EG控件部分)

public Controls {
    JButton button = new JButton;
// More code
}

现在在查看中,我希望能够添加访问该按钮并向其添加Actionlistener。

目前我正在做的是将一个Getter添加到Controls类,然后添加ActionListener

public modal implements ActionListener {
    JFrame frame = new JFrame();
    Controls c = new controls();
    frame.add(c.initialise());
    JButton button = c.getButton();
    c.AddActionListener(this);

}

哪个确实有效,虽然我的代码味道非常糟糕?所以我想知道是否有更好的方法来实现这个系统?

---编辑---

所以我也发现这样做的方式感觉更好但是我还不确定这是不是正确的做法?

由于按钮在主视图中初始化,它仍然不理想,但如果它只是我需要项目监听器的项目,我认为没关系?

public class view implements ActionListener {
    JButton jb1 = new JButton();
    JButton jb1 = new JButton();

    public view {
        JFrame frame = new JFrame();

        Controls c = new controls();
        JPanel cView = c.initialise(jb1, jb2);
        frame.add(cView);

        jb1.addActionListener(e -> {
            //Clicked button one
        });

        jb2.addActionListener(e -> {
            //Clicked button two
        });
    }
}

0 个答案:

没有答案