簡體   English   中英

如何在超類構造函數中從子類構造函數插入代碼?

[英]How can I insert code from subclass constructor in superclass constructor?

所以我有這個超類,它使JPanel具有一些組件。 現在,我需要子類來制作一些單選按鈕,並將其顯示在buttonMin之前。 現在是我的問題:如何在需要的超類中從子類中調用代碼(請參見代碼以了解應在何處調用代碼)?

我的超人

public class RecordLine extends JPanel{

    public RecordLine(Product product){
        JTextField fieldName = new JTextField();
        fieldName.setText(product.getName());
        this.add(fieldName);

        Component horizontalStrut = Box.createHorizontalStrut(20);
        this.add(horizontalStrut);

        //Subclass code should be executed here

        Component horizontalStrut_1 = Box.createHorizontalStrut(20);
        this.add(horizontalStrut_1);

        JButton buttonMin = new JButton("-");
        this.add(buttonMin);
    }
}

我的子類

public class RecordLineDrinks extends RecordLine {

    public RecordLineDrinks(Product product) {
        super(product);

        JRadioButton rdbtnFles = new JRadioButton("Fles");
        this.add(rdbtnFles);
    }

}

您不能直接...您可以使您的超類抽象化,然后實現在構造函數中途調用的方法

public abstract class RecordLine extends JPanel{
    abstract void midwayUpdate();

接着

public class RecordLineDrinks extends RecordLine {

    public RecordLineDrinks(Product product) {
        super(product);

    }
    void midwayUpdate() {
        JRadioButton rdbtnFles = new JRadioButton("Fles");
        this.add(rdbtnFles);

    }

}

您將有一個“模板方法”。

在超類中定義(但不一定在那里做任何事情),並從超類的方法中調用。

在子類中,您可以重寫該方法來執行操作。

 //Subclass code should be executed here
 this.addExtraButtons();

如果在構造函數中執行此操作,則必須小心一點,因為它將在實例完全初始化之前被調用。 可能更干凈一些,可以將所有這些代碼移到其他setup()方法中。

您可能需要更改您的類結構,提供一種可用於創建UI的方法(即createView ),通過該方法可以通過getter訪問其他組件。

這樣,您可以更改createView工作方式。

問題在於,您將負責完全在子類中重新創建UI,因此您需要為其他UI組件使用getter方法。

另一個選擇是,如果您知道要在哪里添加新組件,則可以提供方法的默認實現,這些方法不執行任何操作,但允許子類進行修改

public class RecordLine extends JPanel{

    public RecordLine(Product product){
        JTextField fieldName = new JTextField();
        fieldName.setText(product.getName());
        this.add(fieldName);

        Component horizontalStrut = Box.createHorizontalStrut(20);
        this.add(horizontalStrut);

        //Subclass code should be executed here

        Component horizontalStrut_1 = Box.createHorizontalStrut(20);
        this.add(horizontalStrut_1);

        addBeforeMinButton();

        JButton buttonMin = new JButton("-");
        this.add(buttonMin);
    }

    protected void addBeforeMinButton() {
    }
}

但這通常意味着您需要事先知道如何修改UI

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM