Reputation:
I am trying to get a value from my Calculator (which is in its own separate class) to the JTextPane
in my other class. My only concern is that I am not able to do so because of the design of my program.
In my main class I have an inner class that opens up another frame when the JMenuItem
is clicked.
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
}
}
...
}
And in my other class I have an inner class for the Insert button (which allows the user to insert their answer into the JTextPane
if they wish).
***I've tried many things here such as creating a "getter" and "setter" that passes the value onto the Notepad class but have discovered that they don't work due to the setup of my program.
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
// ***
}
}
...
}
Another one of my problems is that when the JMenuItem
(Calculator) in the frame for my Notepad is clicked I receive a NullPointerException
because there is no value in the JLabel
(Answer for the calculator).
So how do I grab the value of the JLabel
from the Calculator and put it into the JTextPane
of my Notepad frame when Insert is clicked? Also if my program is not setup to perform such an action, do you have any re-design suggestions?
Upvotes: 1
Views: 1046
Reputation: 103135
Simplest way is to pass a reference to the NotePad into the Calculator class. The Calculator class will then look like this:
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);
}
// ***
}
}
And to call it in the Notepad class:
Calculate c = new Calculate(Notepad.this);
Having said that, it would be a good idea to look up some design patterns such as Observer which are precisely for updating one class when another is changed.
Upvotes: 3