![](/img/trans.png)
[英]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.