[英]Pass a value from one class to another
我试图从我的Calculator(在其单独的类中)到另一个类的JTextPane
中获取一个值。 我唯一担心的是,由于我的程序设计,我无法这样做。
在我的主类中,我有一个内部类,当单击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
}
}
...
}
在我的另一个类中,我有一个Insert类的内部类(允许用户根据需要将答案插入JTextPane
)。
***我在这里尝试了很多东西,比如创建一个“getter”和“setter”,它将值传递到Notepad类,但发现它们由于我的程序设置而无法工作。
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
的值并在单击Insert时将其放入记事本框架的JTextPane
中? 另外,如果未将我的程序设置为执行此类操作,那么您是否有任何重新设计建议?
最简单的方法是将对NotePad的引用传递给Calculator类。 Calculator类将如下所示:
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)是一个好主意,这些设计模式恰好可以在更改另一个类时更新一个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.