我想知道在另一个动作之后修改对象的最佳方法是什么。
示例:我有一个带有一些组件的 JPanel,其中一个打开了一个新的 JPanel。在这个新的 JPanel 中,我有一个按钮来修改第一个 JPanel。
我发现了 2 个可行的解决方案,我想知道两者中哪一个是最好的(或另一个)。
第一个是在第一类中添加一个 Actionlistener:
public class SomePanel extends JPanel{
private JButton button = new JButton("Open New Frame");
private SomeOtherPanel otherPanel = new SomeOtherPanel();
private int value = 0;
public SomePanel(){
// initialization code
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
otherPanel.setVisible(true);
}
});
otherPanel.getButton().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
value = 1;
}
});
}
public class SomeOtherPanel extends JPanel{
private JButton button = new JButton("Modify First Panel value");
public SomeOtherPanel(){
}
public JButton getButton() {
return button;
}
}
第二个通过将第一个 JPanel 作为第二个的参数传递:
public class SomePanel extends JPanel{
private JButton button = new JButton("Open New Frame");
private SomeOtherPanel otherPanel = new SomeOtherPanel(this);
private int value = 0;
public SomePanel(){
// initialization code ... size, color ...
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
otherPanel.setVisible(true);
}
});
}
public void setValue(int value) {
this.value = value;
}
}
public class SomeOtherPanel extends JPanel{
private JButton button = new JButton("Modify First Panel value");
public SomePanel somePanel;
public SomeOtherPanel(SomePanel panel){
this.somePanel = panel;
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
somePanel.setValue(1);
}
});
}
public JButton getButton() {
return button;
}
}
这是正确的吗 ?