【问题标题】:Static variables in Netbeans GUI builderNetbeans GUI 构建器中的静态变量
【发布时间】:2014-02-28 18:30:27
【问题描述】:

我使用 Netbeans 和 GUI 构建器开发了一个 Java 应用程序,它是一个相当复杂的 GUI,我认为这将比任何其他方式更容易,而且到目前为止确实如此。现在我的应用程序几乎完成了,我正在整理代码,我注意到我必须将一些变量设为静态才能将它们传递给代码中的方法。 问题是 GUI 构建器生成的只读代码的数量,这意味着我无法将变量传递给使用它们的方法,但我根本看不到绕过它的方法。

例如:

private void increaseSaturationButton(java.awt.event.ActionEvent evt) {                                         
increaseSaturation(colouredImage);
}

我无法编辑行private void increaseSaturationButton(java.awt.event.ActionEvent evt) { 如果colouredImage 不是静态的,那么我无法将它传递给此方法并使用increaseSaturation(); 调用它。有什么办法可以解决这个问题,或者这只是使用 GUI 构建器的一个缺点?还是只是我笨?

在此先感谢

【问题讨论】:

  • 我有这个保存问题,你需要做的是自己复制并粘贴代码;这样你就可以随心所欲了。
  • 我认为你应该重新考虑你的静态变量策略。我从来不需要将变量设为静态,以便将它们传递给自动生成的代码方法。

标签: java user-interface netbeans static


【解决方案1】:

您可以访问像colouredImage 这样的非静态变量,只要它们在同一个类中。这是一个例子。

public class MyClass {

    // Non-static field
    private int value;
    public static int otherValue;

    // Constructor
    public MyClass(int value, int otherValue) { 
        this.value = value;
        MyClass.otherValue = otherValue;
    }

    private void increaseValuesButton(java.awt.event.ActionEvent evt) {
        value++; // Works just fine
        MyClass.otherValue++; // Also works fine
    }

}

您还可以访问其他类的非私有静态方法,因此如果由于您的 GUI 构建器的限制而无法通过 colouredImage,您可以简单地向其他类索要它,例如 OtherClass.getColouredImage() .

您还可以访问其他类的静态公共字段,但这会破坏封装。

【讨论】:

  • 这会起作用,但在主要方法中我收到一个错误,说non-static variable cannot be referenced from a static context 这是我之前遇到的
  • @user2517280 如果您的主要方法负责设置 colouredImage,那么您的 colouredImage 可能应该是静态的。我编辑了我的答案,以展示如何从非静态上下文访问任何类的静态成员。不过,我不能说我同意让您的主要方法负责设置图像。 Main 应该只控制程序的流程。
【解决方案2】:

所以是的,这就是我用来最大化我的代码定制的方法。将“变量”替换为您希望对其执行操作的变量的名称。如果您需要执行不同的操作,例如 mouselistener:只需让 NetBeans 添加执行的操作,复制并粘贴它,复制然后从 GUI 的“设计”区域删除变量组件,然后再次粘贴设计。

public Terminal() {
            initComponents();  //default init components - this is the one generated by netbeans
            cinit(); // custom init components - this is the custom one
        }

        private void cinit() /* custom init components */ {
            Variable.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    VariableActionPerformed(evt);
                }
            });
        }

        public void VariableActionPerformed(java.awt.event.ActionEvent evt) {
            // to do code goes here
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2017-12-30
    相关资源
    最近更新 更多