For homework I'm asked to seperate a nested class from the main class.
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** This program displays the growth of an investment. */ public class InvestmentViewer2 { public static void main(String[] args) { JFrame frame = new JFrame(); // The button to trigger the calculation JButton button = new JButton("Add Interest"); // The application adds interest to this bank account final BankAccount account = new BankAccount(INITIAL_BALANCE); // The label for displaying the results final JLabel label = new JLabel("balance: " + account.getBalance()); // The panel that holds the user interface components JPanel panel = new JPanel(); panel.add(button); panel.add(label); frame.add(panel); class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double interest = account.getBalance() * INTEREST_RATE / 100; account.deposit(interest); label.setText( "balance: " + account.getBalance()); } } ActionListener listener = new AddInterestListener(); button.addActionListener(listener); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private static final double INTEREST_RATE = 10; private static final double INITIAL_BALANCE = 1000; private static final int FRAME_WIDTH = 400; private static final int FRAME_HEIGHT = 100; } I took the class AddInterestListener out of the main class, and put it in a new file. Now the account.getBalance() doesn't work anymore. I can't find how I would let the new class AddInterestListener target the account object that was created in the main class.
I also have a simple BankAccount class that creates the object. That has the 2 methods deposit(double x) and getBalance().
There is a hint on the homework question: Store a reference to the bank account. Add a constructor to the listener class that sets the reference.
I don't understand what they are saying. I've tried extending the class and then using super. to reach the method, but I'm stuck.
getBalance()? I don't see it in your class anywhere.