java - 尝试从 Java 和 NetBeans 中的 ConfigWindow 在 MainWindow 中设置配置变量

标签 java swing oop methods

是的,我现在已经按照 SSCEE 指南重现了我的问题。

以下 3 个类(类代码)应该准备好复制、粘贴和编译,供您查看我出了什么问题。

Menu():(这是我的主类)

    public class Menu extends javax.swing.JFrame {

    /**
     * Creates new form Menu
     */
    public Menu() {
    initComponents();
    }

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    cmdMainWindow = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    cmdMainWindow.setText("Main Window");
    cmdMainWindow.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdMainWindowActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(cmdMainWindow, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(cmdMainWindow)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void cmdMainWindowActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    MainWindow main = new MainWindow();
    main.setVisible(true);

}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new Menu().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton cmdMainWindow;
// End of variables declaration
    }

主窗口():

    public class MainWindow extends javax.swing.JFrame {

private MainWindow main;
public String strOptionOne;

/**
 * Creates new form MainWindow
 */
public MainWindow() {
    initComponents();
}



/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    lblOptionOne = new javax.swing.JLabel();
    cmdOptions = new javax.swing.JButton();
    txtOptionOne = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    lblOptionOne.setText("Option One");

    cmdOptions.setText("Options");
    cmdOptions.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdOptionsActionPerformed(evt);
        }
    });

    txtOptionOne.setEditable(false);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(lblOptionOne)
                .addComponent(cmdOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(txtOptionOne))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(lblOptionOne)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(txtOptionOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(11, 11, 11)
            .addComponent(cmdOptions)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void cmdOptionsActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
   ConfigWindow config = new ConfigWindow(main);
   config.setVisible(true);

}
     public String setOptionOne() {
  ConfigWindow config = new ConfigWindow(main);

strOptionOne = config.getOptionOne();
return strOptionOne;
}
/**
 * @param args the command line arguments
 */

// Variables declaration - do not modify
private javax.swing.JButton cmdOptions;
private javax.swing.JLabel lblOptionOne;
public javax.swing.JTextField txtOptionOne;
// End of variables declaration
    }

ConfigWindow():

    public class ConfigWindow extends javax.swing.JFrame {
private MainWindow main;
public String btnTxtOptionOne;

/**
 * Creates new form ConfigWindow
 */
public ConfigWindow(MainWindow main) {
    initComponents();
    this.main = main;
}


public String getOptionOne() {

if ("1".equals(grpOptionOne.getSelection())) {
    btnTxtOptionOne = "1";
    return this.btnTxtOptionOne;
}

if ("2".equals(grpOptionOne.getSelection())) {
    btnTxtOptionOne = "2";
    return this.btnTxtOptionOne;
}
return btnTxtOptionOne;
    }



/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    grpOptionOne = new javax.swing.ButtonGroup();
    lblOptionOne = new javax.swing.JLabel();
    btn1 = new javax.swing.JRadioButton();
    btn2 = new javax.swing.JRadioButton();
    cmdApplySettings = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    lblOptionOne.setText("Option One");

    grpOptionOne.add(btn1);
    btn1.setText("1");

    grpOptionOne.add(btn2);
    btn2.setText("2");

    cmdApplySettings.setText("ApplySettings");
    cmdApplySettings.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cmdApplySettingsActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(lblOptionOne)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(btn1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(btn2))
                .addComponent(cmdApplySettings))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(lblOptionOne)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btn1)
                .addComponent(btn2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cmdApplySettings)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void cmdApplySettingsActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
   main.txtOptionOne.setText(main.strOptionOne);
    dispose();
}

/**
 * @param args the command line arguments
 */

// Variables declaration - do not modify
private javax.swing.JRadioButton btn1;
private javax.swing.JRadioButton btn2;
private javax.swing.JButton cmdApplySettings;
private javax.swing.ButtonGroup grpOptionOne;
private javax.swing.JLabel lblOptionOne;
// End of variables declaration
    }

因此,所有代码都已完成,因为我刚刚修改了所有这些内容,所以我将再次提及问题所在。

当我从MainWindow转到ConfigWindow选择选项时,选择选项后,ConfigWindow中的方法获取所选按钮的值,然后MainWindow中的方法获取该值,并将其设置为MainWindow中的变量。然后,在 ConfigWindow 中单击“Apply”时,应该运行 MainWindow 中的方法,并使用所选选项设置 MainWindow 变量,但事实并非如此!

我已经将我的项目修剪成最基本的形式,现在单击“应用”时它会在 netbeans 中引发错误,而之前它根本没有执行任何操作,netbeans 中没有错误。

我希望我已经在这里完成了 SSCEE ...我正在努力!!!

最佳答案

这是源代码,根据您发布的内容进行了改进,压缩为单个源文件。仍有问题需要解决,但我放置了调试语句(打印出值),这应该有助于指出它仍然无法工作的原因。请参阅帖子底部的更多注释。

public class Menu117 extends javax.swing.JFrame {

    /**
     * Creates new form Menu
     */
    public Menu117() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        cmdMainWindow = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        cmdMainWindow.setText("Main Window");
        cmdMainWindow.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdMainWindowActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(cmdMainWindow, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE).addContainerGap()));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(cmdMainWindow).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>

    private void cmdMainWindowActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        MainWindow main = new MainWindow();
        main.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Menu117.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Menu117().setVisible(true);
            }
        });
    }
// Variables declaration - do not modify
    private javax.swing.JButton cmdMainWindow;
// End of variables declaration
}

class MainWindow extends javax.swing.JFrame {

    // This IS a MainWindow.  No need to keep a reference to one as well!
//private MainWindow main;
    public String strOptionOne;

    /**
     * Creates new form MainWindow
     */
    public MainWindow() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        lblOptionOne = new javax.swing.JLabel();
        cmdOptions = new javax.swing.JButton();
        txtOptionOne = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblOptionOne.setText("Option One");

        cmdOptions.setText("Options");
        cmdOptions.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdOptionsActionPerformed(evt);
            }
        });

        txtOptionOne.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(lblOptionOne).addComponent(cmdOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(txtOptionOne)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lblOptionOne).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(txtOptionOne, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(11, 11, 11).addComponent(cmdOptions).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>

    private void cmdOptionsActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ConfigWindow config = new ConfigWindow(this);
        config.setVisible(true);

    }
    /*
     * public String setOptionOne() { ConfigWindow config = new
     * ConfigWindow(this);
     *
     * strOptionOne = config.getOptionOne(); return strOptionOne;
    }
     */
    /**
     * @param args the command line arguments
     */
// Variables declaration - do not modify
    private javax.swing.JButton cmdOptions;
    private javax.swing.JLabel lblOptionOne;
    public javax.swing.JTextField txtOptionOne;
// End of variables declaration
}

class ConfigWindow extends javax.swing.JFrame {

    private MainWindow main;
    public String btnTxtOptionOne;

    /**
     * Creates new form ConfigWindow
     */
    public ConfigWindow(MainWindow main) {
        initComponents();
        this.main = main;
    }

    public String getOptionOne() {
        System.out.println(grpOptionOne.getSelection().getActionCommand());
        if ("1".equals(grpOptionOne.getSelection().getActionCommand())) {
            btnTxtOptionOne = "1";
        } else if ("2".equals(grpOptionOne.getSelection())) {
            btnTxtOptionOne = "2";
        } else {
            btnTxtOptionOne = "-1";
        }
        return this.btnTxtOptionOne;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        grpOptionOne = new javax.swing.ButtonGroup();
        lblOptionOne = new javax.swing.JLabel();
        btn1 = new javax.swing.JRadioButton();
        btn2 = new javax.swing.JRadioButton();
        cmdApplySettings = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lblOptionOne.setText("Option One");

        grpOptionOne.add(btn1);
        btn1.setText("1");

        grpOptionOne.add(btn2);
        btn2.setText("2");

        cmdApplySettings.setText("ApplySettings");
        cmdApplySettings.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdApplySettingsActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblOptionOne).addGroup(layout.createSequentialGroup().addComponent(btn1).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(btn2)).addComponent(cmdApplySettings)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(lblOptionOne).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btn1).addComponent(btn2)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(cmdApplySettings).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }// </editor-fold>

    private void cmdApplySettingsActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        System.out.println(evt);
        //main.txtOptionOne.setText(main.strOptionOne);
        main.txtOptionOne.setText(getOptionOne());
        dispose();
    }
    /**
     * @param args the command line arguments
     */
// Variables declaration - do not modify
    private javax.swing.JRadioButton btn1;
    private javax.swing.JRadioButton btn2;
    private javax.swing.JButton cmdApplySettings;
    private javax.swing.ButtonGroup grpOptionOne;
    private javax.swing.JLabel lblOptionOne;
// End of variables declaration
}
  1. SSCCE 需要一个源文件,但有 253 行,它并不是真正的“短”。如果您删除了那些(相当多余且令人恼火的)自动生成的 Netbeans 注释,并删除了不必要的代码块来设置 PLAF(与此问题无关),那么它可能会少于 150 行代码,这可能很短足以称为“SSCCE”。
  2. 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。在 Netbeans 中,这就像按组合键 Alt+Shift+F
    一样简单 上面看到的代码是我当前版本的 Netbeans 格式化代码的方式,尽管我怀疑较新的版本会省略第一个缩进,以便使方法签名从一行上的 char 0 开始(提供更多宽度来显示它们)。
  3. 强烈建议您暂时将 Netbeans 放在一边。在您熟悉基本的 Java 之前,它只会成为障碍。
  4. 此来源使用 3 个框架。应用程序通常(应该)只有一个用于主应用程序窗口的框架。另外两个可能会被放入 JDialog 中。或JOptionPane 。请参阅The Use of Multiple JFrames, Good/Bad Practice?了解更多详情。

关于java - 尝试从 Java 和 NetBeans 中的 ConfigWindow 在 MainWindow 中设置配置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15037561/

相关文章:

java - 从另一个类访问 JFrame

javascript - 基于原型(prototype)的面向对象。黄金三镖客?

c++ - 虚函数表指针在对象中的位置

java.util.NoSuchElementException : No line found

java - Java中根据条件访问字段

java - 如何更改默认JProgressBar的颜色?

java - 我可以使用 ObjectChangeListener 来监听任何对象的变化吗?

javascript - 使用javascript OOP中的方法动态获取属性

java - SAX解析器加载DTD文件

java - 尴尬的 OOP : Same method on different classes not inherited?