-2

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.

6
  • You can't do that. You need to create the variable outside of the handler if you want to use it outside of the handler. Look up variable scoping. Commented May 4, 2017 at 13:36
  • Why did you add the line from the answer there ? It is in a different context (static main context). You need to access it from the ThreePanelLayout instance, so in t he Runnable#run or in one method of this class. Commented May 4, 2017 at 13:47
  • @AxelH I am not sure I understand what you mean. If I put it in the ThreeLayoutPanel(), with initUI(),I am told that the variable does not exist when calling it. Commented May 4, 2017 at 13:52
  • objectName is a member variable, meaning it exist in an instance of the class ThreePanelLayout . You can only access it (when it exists) in this class, or from this class. There is no reason it would not work in the constructor. Please provide a minimal reproducible example to show us this specific problem, we don't need the UI component in that case. Commented May 4, 2017 at 13:55
  • @AxelH I think the issue might be when setting up the action listener which is where my variable is being assigned so removing that from my post would hinder people being able to help me. Commented May 4, 2017 at 13:59

1 Answer 1

0

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....

Sign up to request clarification or add additional context in comments.

8 Comments

better call it a member variable but answer is correct otherwise
Thanks for the answer. More issues however. When declaring my variable in panel question and calling it in my main, I am told that the non-static variable may not be called in a static context. Any idea how I could remedy to this?
@JonGoe, hummm can you please update the code...
@ΦXocę 웃 Пepeúpa ツ Just updated the post!
@JonGoe your are not listening, here is the declaration String objectName;, so you can't use a method that is not in the String documentation. In java, you can't use an instance of a String to use an other variable.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.