java - 将值从一个类传递到另一个类

标签 java swing inner-classes actionlistener jtextpane

我正在尝试从我的计算器(在它自己的单独类中)获取一个值到 JTextPane在我的另一个类(class)。我唯一担心的是,由于我的程序设计,我无法这样做。

在我的主类中,我有一个内部类,它在 JMenuItem 时打开另一个框架。被点击。


public class Notepad extends JFrame
{
    ...
    // Opens when the user clicks Calculator 
    // (JMenuItem in the JFrame of the Notepad class)
    private class Calculator implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            Calculate c = new Calculate();
            c.buildGUI();

            // I've tried creating a reference to the Insert class and tried to
            // retrieve the value from the JLabel in the Calculator but continuously
            // receive a NullPointerException
        }
    }
    ...
}

在我的其他类(class)中,我有一个用于“插入”按钮的内部类(如果他们愿意,它允许用户将他们的答案插入到 JTextPane 中)。

***我在这里尝试了很多东西,例如创建一个将值传递给记事本类的“getter”和“setter”,但发现由于我的程序设置,它们不起作用。


public class Calculate extends JFrame
{
    ...
    /* Insert
     * Inserts the answer into the 
     * text pane of the Notepad class
     */
    private class Insert implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String answer = proposal.getText(); // from the JLabel
            if (answer.isEmpty()) JOptionPane.showMessageDialog(frame, "Enter two numbers and hit the desired operator, please");
            // else, insert the answer
            // ***
        }
    }
    ...
}

我的另一个问题是当 JMenuItem单击记事​​本框架中的(计算器) 我收到 NullPointerException因为 JLabel 中没有值(计算器的答案)。

那么我该如何获取 JLabel 的值呢?从计算器中输入 JTextPane单击“插入”时我的记事本框架?另外,如果我的程序未设置为执行此类操作,您有任何重新设计的建议吗?

最佳答案

最简单的方法是将对记事本的引用传递到计算器类中。计算器类将如下所示:

  public class Calculator extends JFrame{

         Notepad notepad;

         public Caluclator(Notepad np){
             this();
             notepad = np;
             //any other code you need in your constructor
         }

         ...

         private class Insert implements ActionListener
         {
           public void actionPerformed(ActionEvent e)
           {
              String answer = proposal.getText(); // from the JLabel
                if (answer.isEmpty()) JOptionPane.showMessageDialog(frame, "Enter two numbers and hit the desired operator, please");
                else{
                     notepad.myJTextPane.setText(answer);
                }
            // ***
         }


}

并在记事本类中调用它:

   Calculate c = new Calculate(Notepad.this);

话虽如此,查找一些设计模式是个好主意,例如 Observer这恰恰是为了在一个类发生变化时更新一个类。

关于java - 将值从一个类传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8828979/

相关文章:

java - 使用 JavaFX 的 Jasper 报告

Java 模式对话框不会阻止代码执行

java - getObject(index, Long) 对于 null 返回 0

java - 快速修复 Class.forName 大小写问题

java - Eclipse SWT 浏览器显示反转的希伯来语

java - 使用 SwingWorker 和 JProgressBar 跟踪多个图像下载的进度

java - 如何访问未知的类方法

java - 访问struts.xml中的java内部类

java - 如何使内部类可打包

java - Android下载管理器保存到/system