简体   繁体   中英

How to access variable from action listener/class constructor to use in main method in java

I have a frame with a combo box that displays different shapes and a button, for the button I added an action listener which will get the selected item from the combo box and store it as a string which i declared as a public class variable, in my main method i want to access this string to make a finch robot draw that shape but I can't seem to access it no matter what I try

public class DrawShape 
{
    private JFrame frame;
    private String[] choices = {"circle", "square", "triangle", "rectangle", "quit"};
    public String choice = "";

    //class constructor 
    public DrawShape() 
    {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        JPanel p = new JPanel();
        final JComboBox cb = new JComboBox(choices);
        JButton button = new JButton("Done");

        p.add(cb);
        p.add(button);
        frame.add(p);

        //create an action listener that, when button is clicked, gets the selected choice and stores it to
        //the string variable 'choice'
        button.addActionListener(new ActionListener()
                {
                    @Override 
                    public void actionPerformed(ActionEvent e)
                    {
                        choice = (String)cb.getSelectedItem();
                    }
                }) ;

        frame.pack();


    }
    public static void main(String[] args)
    {
        new DrawShape();
        System.out.println(choice);
    }
}

I wouldn't recommend the use of non-private variables. However, you need to keep a reference to the object you created and then access the fields through that reference as if you were calling methods on an object.

    DrawShape draw = new DrawShape();
    System.out.println(draw.choice);

However, you should see null as this is called immediately after you construct the object rather than from the listener.

You probably want the code executed from the listener. So either put the print code in the listener, or have the listener call another method with that in.

GUI programming tends to be event driven. Don't expect to be able to sequence the user interaction - the user drives.

you should use getters/setters in this case. Your action listener would call the getter method which would in turn get what is in the combobox.

Here is an example of how that works: https://www.codejava.net/coding/java-getter-and-setter-tutorial-from-basics-to-best-practices

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM