[英]How to modify/add code to the initComponents() method in Java using NetBeans?
[英]Other ways to add a parameter to initComponents [java-netbeans]
我在netbeans中的GUI Java項目遇到很大的問題。 眾所周知,netbeans編譯的代碼是只讀的,除了調用與initComponents相同的myInitComponents方法並在構造函數中調用之外,我還需要其他方法將參數添加到initComponents方法中。 現在我有這個:
public class MainFrame {
public MainFrame() {
DefaultStyledDocument doc = new DefaultStyledDocument();
myInitComponents(doc);
}
myInitComponents (DefaultStyledDocument doc) {
//components
textModel = new javax.swing.JTextPane(doc);
//components
}
initComponents () {
//components
}
通過這種方式,它可以工作,但是每次我在框架中進行更改時,都必須復制並插入myInitComponent中所有initComponents的新代碼。 此外,這是一種非常糟糕的方法。 還有其他方法可以添加該參數嗎? 任何幫助表示贊賞!
您可以向MainFrame構造函數添加參數,將其放置在字段中,並在GUI構建器的屬性表中使用自定義創建代碼。
在initComponents的代碼中可以插入一些免費的代碼。 創建自定義代碼就是這樣一個地方;
private final DefaultStyledDocument doc = new DefaultStyledDocument();
並在“自定義創建代碼”中:
new JTextPane(doc)
也可以用於自定義面板等。
我在netbeans中的GUI Java項目遇到很大的問題。 眾所周知,netbeans編譯的代碼是只讀的,除了調用與initComponents相同的myInitComponents方法並在構造函數中調用之外,我還需要其他方法將參數添加到initComponents方法中。
我認為您可能在使用構造函數進行初始化和使用setter訪問值之間感到困惑。
這就像問一個問題一樣好:如果您有一個具有諸如a,b和c之類的屬性的類,那么如何創建一個設置所有屬性的設置器。 這是您應避免的事情。 您可以為每個屬性創建一個單獨的setter和getter,而不是嘗試使用init
來設置所有屬性。
您應該這樣做:
class MyClass
{
private int a;
private int b;
private int c;
public MyClass(){
init();
}
private void init(){
a = 100;
b = 200;
c = 300;
}
public int getA(){return a;}
public int getB(){return b;}
public int getC(){return c;}
public void setA(int a){this.a = a;}
public void setB(int b){this.a = b;}
public void setC(int c){this.a = c;}
}
代替這個:
class MyClass
{
private int a;
private int b;
private int c;
public MyClass(){
init();
}
private void init(){
a = 100;
b = 200;
c = 300;
}
public void myInit(int a, int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
}
這是一種非常糟糕的方法。 還有其他方法可以添加該參數嗎?
因此,您問,如果還有一個屬性,請說int d
。 我應該如何將其添加到myInit()
的參數列表中。 因此,您已經開始在您的班級設計中看到這種方法的問題。
如果可能,我們嘗試在設計中實現低耦合和高內聚 。 當在單個方法中轉儲各種不相關的屬性時,您將趨向於低內聚性(這種方法無法執行非常具體的任務)。
如果嘗試使用像myInit()
這樣的單個方法並將其用作設置多個字段的設置器,則可能會導致許多問題。
因此,要回答您的問題,請對每個屬性使用單獨的設置器,除非這些屬性緊密相關,例如:
setLocation(int x, int y);
setBounds(int x, int y, int width, int height);
最后,我以非常簡單的方式解決了這個問題。 通過單擊定制代碼並將其添加為預創建代碼,我將DefaultStyleDocument所需的所有代碼插入initComponents()方法中。
public class MainFrame {
public MainFrame() {
myInitComponents();
}
//delete the myInitComponents() method
initComponents () {
//code useful for the DefaultStyledDocument..
DefaultStyledDocument doc = new DefaultStyledDocument();
//components
textModel = new javax.swing.JTextPane(doc);
}
希望這對某人有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.