Java子对象运行Parent Object的方法

时间:2018-09-06 12:10:26

标签: java swing class user-interface

我决定将BorderLayout用于名为Loginwards的秋千设计。我为BorderLayout的5面编写了5个类,分别为PageStart,LineStart,Center,LineEnd,PageEnd。

我没有装饰Loginwards并设计了PageStart以便最小化,调整大小和退出。(对于我自己的图像,规则...)按钮退出很简单,因为它的工作原理如下

button.addActionListener(new ActionListener() {
    @Override
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);

        }
    });

但是例如最小化我无法解决。我应该已经从另一个类对象

更改了Loginwards属性。

总结

public class Loginwards extends Jframe
{   ...
    JFrame frame = new JFrame("BorderLayoutDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(PageStart.Panel(), BorderLayout.PAGE_START);
    ...
}


public class PageStart{
   public static JPanel Panel(){
     JPanel panel = new JPanel();
     FlowLayout pagestart = new FlowLayout(FlowLayout.RIGHT);
     panel.setLayout(pagestart);
     panel.add(MinimizeButton()); 
     panel.add(ResizeButton()); 
     panel.add(QuitButton()); 
   }
   public static JButton MinimizeButton(){
    JButton button = new JButton();
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
        // I Should be able to reach Loginwards here.
        }
    });
    return button;
}

1 个答案:

答案 0 :(得分:1)

MinimizeButton是静态方法,因此将Loginwards实例作为参数传递,然后在侦听器中使用它:

public static JButton MinimizeButton(Loginwards loginwards){
    JButton button = new JButton();
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // Invoke whatever you need on Loginwards...
            loginwards.doSomething();
        }
    });
    return button;
}

顺便说一句,方法名称应以小写开头...请参见naming conventions for Java