Sheepwall
Sheepwall

Reputation: 175

JOptionPane.showInputDialog always returns null

I want to access a chosen value from a dialog, and just to test whether I can, I'm at the moment just using "System.out.print(selectedValue)". It seems that this value always is "null". How do I get the above function to print out whatever I chose in the dialog?

Code: (note I am also learning about multiple file projects, which is why it looks a bit weird with "package" and stuff)

package classfolder;

import java.applet.*;
import java.awt.*;
import javax.swing.*;

public class openWindow
{   

    public Object selectedValue;

    public openWindow()
    {       
        Object[] Categories = { "First", "Second", "Third" };
        Object selectedValue = JOptionPane.showInputDialog(null, "Choose one", "Input", JOptionPane.INFORMATION_MESSAGE, null, Categories, Categories[0]);
    }

}

import classfolder.*;

public class master
{

    public static void main(String[] arg)
    {
        openWindow window = new openWindow();
        System.out.println(window.selectedValue);

    }
}

What I get from console:

...address...>java master
null

Upvotes: 0

Views: 1100

Answers (1)

khelwood
khelwood

Reputation: 59113

This line

Object selectedValue = JOptionPane.showInputDialog(...);

declares a new local variable called selectedValue and sets it to the result of showInputDialog. This doesn't affect your instance variable selectedValue - it is a different variable.

If you want to assign your instance variable, you don't need to redeclare it; so change the line to

selectedValue = JOptionPane.showInputDialog(...);

Upvotes: 1

Related Questions