简体   繁体   English

Java子对象运行Parent Object的方法

[英]Java Child Object run Parent Object s method

I decided using BorderLayout for swing design named Loginwards. 我决定将BorderLayout用于名为Loginwards的秋千设计。 And I wrote 5 Classes for 5 side of BorderLayout as PageStart, LineStart, Center, LineEnd, PageEnd. 我为BorderLayout的5面编写了5个类,分别为PageStart,LineStart,Center,LineEnd,PageEnd。

I have undecorated Loginwards and designed PageStart for use minimize,resize,quit.(for my own images, rules...) button quit is simple because it have worked like this 我未经装饰的Loginwards并设计了PageStart以便最小化,调整大小,退出。(对于我自己的图像,规则...)按钮退出很简单,因为它的工作原理如下:

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

        }
    });

but for example minimize I could not solve. 但是例如最小化我无法解决。 I should have changed my Loginwards properties from another class object 我应该从另一个类对象更改了我的Loginwards属性

Sum up 总结

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

MinimizeButton is a static method, so pass Loginwards instance as it's parameter, then make use of it in your listener: 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;
}

Btw, method names should start with lowercase... see naming conventions for Java 顺便说一句,方法名称应以小写字母开头...请参阅Java的命名约定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM