Search code examples
javajoptionpane

Trouble with JOptionPane variable from another class


I set up some simple code using JOptionPane to open a simple showMessageDialog when a button is clicked. Everything worked fine. Now I'm complicating things by retrieving a double variable from another class. I've tried a few different things, but I'm still getting a "not applicable for arguments" error. I've tried reading over the full Oracle documentation and watched a few YouTube videos, but I'm still struggling.

Three classes, one for the GUI, one for the event handling, and for retrieving the number from.

Here is the code excerpt:

public class TEST_GUI {

   private JButton testButton;

   public void GUI {
      //construction of the GUI occurs here
      testButton = new JButton("Tester");
   }



protected class EventHandler implements ActionListener {

    public void actionPerformed(ActionEvent testButtonClicked) {        

        if (testButtonClicked.getSource() == testButton){
            TesterClass tester = new TesterClass();
            JOptionPane.showMessageDialog(null,tester.getRetrievedNumber());
        }
    }
}



public class TesterClass {

    private double retrievedNumber;

    public TesterClass(){
        retrievedNumber = 1000.00;
    }

    public double getRetrievedNumber() {
        return this.retrievedNumber;
    }
}

Everything worked fine with the generic (null,"message") arguments, but it won't accept my double variable from the other class. I'd appreciate any guidance. Thanks!


Solution

  • Replace

    tester.getRetrievedNumber()
    

    with

    String.valueOf(tester.getRetrievedNumber());
    

    That said

    public static void showMessageDialog(Component parentComponent, Object message)
    

    Since we can see that showMessageDialog takes an object as 2nd parameter, AutoBoxing should work here and your double gets casted into a Double object.

    In Eclipse, it works fine using a primitive as parameter.

    Maybe the problem lays elsewhere but I can not find it. Maybe with more info...