Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're creating a "shadow" ButtonFrame variable inside of the b2's ActionListener. Yes the bf variable refers to a ButtonFrame object which is of the same class as the displayed ButtonFrame object, but it refers to a completely distinct and non-visualized object. The key to a solution is to get the text from the ButtonFrame object that is actually displayed, and this can be obtained from within an inner class via the <code>ButtonFrame.this</code> construct:</p> <pre><code> b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //!! ButtonFrame bf = new ButtonFrame(); if ("calculate".equals(e.getActionCommand())) { //!! note use of ButtonFrame.this: JOptionPane.showMessageDialog(frame, ButtonFrame.this.loanAmt.getText()); } } }); </code></pre> <p>Next consider using public getters rather than accessing fields such as the JTextField directly. This reduces the chances of the code causing side effects, such as changing the properties of the JTextField object inadvertently. </p> <p>For instance (changes denoted by //!! comment): </p> <pre><code>import java.awt.*; import java.awt.event.ActionListener; import javax.swing.*; import java.awt.event.ActionEvent; public class ButtonTest { public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class ButtonFrame extends JFrame { private JTextField loanAmt; // !! Make field private @SuppressWarnings("LeakingThisInConstructor") public ButtonFrame() { setTitle("SunStream Loan Calculator v2.0"); setSize(900, 900); ButtonPanel panel = new ButtonPanel(); panel.add(new JLabel("Enter your loan amount:")); loanAmt = new JTextField(40); panel.add(loanAmt); add(panel, BorderLayout.CENTER); } // !! create a public method to get JTextField's text // !! without exposing the JTextField itself. public String getLoanAmtText() { return loanAmt.getText(); } class ButtonPanel extends JPanel implements ActionListener { private Component frame; public ButtonPanel() { final JButton b2 = new JButton("Calculate"); add(b2, BorderLayout.SOUTH); b2.setActionCommand("calculate"); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // !! ButtonFrame bf = new ButtonFrame(); if ("calculate".equals(e.getActionCommand())) { //!! call public method on ButtonFrame object JOptionPane.showMessageDialog(frame, ButtonFrame.this.getLoanAmtText()); } } }); } @Override public void actionPerformed(ActionEvent ae) { throw new UnsupportedOperationException("Not supported yet."); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload