Java using variable created in action listener [du

2019-09-21 06:57发布

问题:

This question already has an answer here:

  • Class scope variable vs method scope variable 3 answers

I am having issues with some java code. I cannot figure out how to solve it. Please note that the code is heavily simplifed.

In panelQuestion, I am creating a GUI with a button and two combo boxes. I add an action listener to the button.

When this button is clicked, a string with the values of the combo boxes is created, called objectName.

After having initialized the GUI, I create objects.

The issue is that I would like to be able to use the objectName in the main class so that I can check for some of its attributes.

For example, if the user was to choose Leicester and York, the string would be created (leicester_york), and that string would be used to check for that objects attributes.

However this does not work. I am told that objectName does not exist. Any help would be appreciated, thanks.

panelQuestion:

    import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;

public class ThreePanelLayout {

    private JComponent ui = null;
    private CardLayout cardLayout = new CardLayout();  
    String objectName;

    ThreePanelLayout() {
        initUI();
    }

    public void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        //create the 3 panels of the '3 panel layout'. 
        JPanel panel1 = new JPanel(new BorderLayout());//();
        panel1.setBackground(Color.RED);
        panel1.setBorder(new TitledBorder("Choose Option"));

        JPanel panel2 = new JPanel(new BorderLayout());
        panel2.setBackground(Color.GREEN);
        panel2.setBorder(new TitledBorder("Choose Two Stops"));

        JPanel panel3 = new JPanel();
        panel3.setBackground(Color.ORANGE);
        panel3.setBorder(new TitledBorder("Click an Option"));
        panel3.setLayout(cardLayout);


        // add the buttons to 1st panel
        JButton timeButton, priceButton, routeButton, adminButton, exitButton, inputRoute, saveRoute, retrieveRoute, backToMain; //DECLARING BUTTON
        timeButton    = new JButton("Time");
        priceButton   = new JButton("Price");
        routeButton   = new JButton("Route");
        adminButton   = new JButton("Admin");
        exitButton    = new JButton("Exit");  
        inputRoute    = new JButton("Input Route");
        saveRoute     = new JButton("Save Route");
        retrieveRoute = new JButton("Retrieve route");

        JPanel panelButtons = new JPanel(new GridLayout(5,1,5,5));
        panelButtons.add(timeButton);
        panelButtons.add(priceButton);
        panelButtons.add(routeButton);
        panelButtons.add(adminButton);
        panelButtons.add(exitButton);        
        panel1.add(panelButtons, BorderLayout.LINE_START);

        JPanel panelAdmin = new JPanel(new GridLayout(5,1));
        JPanel panelAdminSize = new JPanel();
        panelAdminSize.add(inputRoute);
        panelAdminSize.add(saveRoute);
        panelAdminSize.add(retrieveRoute);
        panelAdmin.add(panelAdminSize);  


        // adding the combos to the top of 2nd panel 

        String stops[] = {"Leicester","Loughborough","Nottingham","Derby","York"};

        JComboBox departingStop = new JComboBox();
        JComboBox finalStop = new JComboBox();
        for(int i = 0; i < stops.length; i++) {
            departingStop.addItem(stops[i]);
            finalStop.addItem(stops[i]);
        }

        JPanel panelCombo = new JPanel(new FlowLayout());
        panelCombo.add(departingStop);
        panelCombo.add(finalStop);
        panel2.add(panelCombo, BorderLayout.PAGE_START);

        // adding options to panel 3        
        // panel for when time is clicked
        JPanel panelTime = new JPanel (); //creating panel for time option
        JLabel timeLabel = new JLabel("The time between x and y is"); 
        panelTime.add(timeLabel);

        //panel for when price is clicked
        JPanel panelPrice = new JPanel ();
        JButton confirmPrice = new JButton("Confirm");
        JRadioButton singleRadio = new JRadioButton("Single"); 
        JRadioButton returnRadio = new JRadioButton("Return");
        ButtonGroup group = new ButtonGroup();
        group.add(singleRadio);
        group.add(returnRadio);
        panelPrice.add(singleRadio);
        panelPrice.add(returnRadio);   
        panelPrice.add(confirmPrice);

        // used for route button
        JPanel panelRoute = new JPanel();
        JLabel routeLabel = new JLabel ("Stop between X and Y");
        panelRoute.add(routeLabel);
        JButton sortButton = new JButton("Sort");
        panelRoute.add(sortButton);

        panel3.add(panelTime,"1");
        panel3.add(panelPrice,"2");
        panel3.add(panelRoute,"3");
        panel3.add(panelAdmin,"4");

        timeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                cardLayout.show(panel3, "1");

                Object comboValue  = departingStop.getSelectedItem();
                Object combo2Value = finalStop.getSelectedItem();
                objectName = comboValue + "_" + combo2Value;
                objectName = objectName.toLowerCase();
           }
        });

        priceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                cardLayout.show(panel3, "2");
            }
        });

        routeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                cardLayout.show(panel3, "3");
            }
        });

        adminButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                cardLayout.show(panel3, "4");
            }
        });

        exitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.exit(0);
            }
        });   

        // assembling panels
        panel2.add(panel3);
        panel1.add(panel2, BorderLayout.CENTER);
        ui.add(panel1);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {        
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                ThreePanelLayout o = new ThreePanelLayout();
                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);
                f.setContentPane(o.getUI());
                f.setSize(600,400);
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);

        Journey leicester_loughborough = new Journey();
        leicester_loughborough.setSingleCost(2.5);

        Journey leicester_nottingham = new Journey();
        leicester_nottingham.setSingleCost(3.5);

        Journey leicester_derby = new Journey();
        leicester_derby.setSingleCost(3.7);

        Journey leicester_york = new Journey();
        leicester_york.setSingleCost(23.5);

        objectName.getSingleCost(); //error comes up here

    }


}

Journey:

public class Journey
{

    public double singleCost;

    public void setSingleCost(double cost) {
        singleCost = cost;
    }

    public double getSingleCost() {
        return singleCost;
    }
}

I don't think this question is a duplicate. When using the solution objectName = this.objectName, the same issue arises.

回答1:

You need to declare this: String objectName as a member variable of the panelQuestion class!


Side note:

you need to read how an object works and what are their methods, members and what are they doing.... as I commented above objectName.getSingleCost() makes no sense, and is not compiling, the reason: objectName is a string object and strings have no method called getSingleCost

just because you do:

 String objectName;
 Object comboValue  = departingStop.getSelectedItem();
 Object combo2Value = finalStop.getSelectedItem();
 objectName = comboValue + "_" + combo2Value;

dosnt mean that now objectName mutated from string into a ComboBox...

same is invalid:

 Car tata = new Car();
 Robot kuka = new Robot();
 String foo = tata.getName() + kuka.getName();

now what is foo? a transformer?? NO, is still a String...

you can find thousands of tutorials... go search, read, learn and go 1 step after the other....



标签: java class