我正在尝试从我的计算器(在它自己的单独类中)获取一个值到 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/