3 Replies - 616 Views - Last Post: 23 June 2013 - 03:52 PM Rate Topic: -----

#1 crummydo  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 223
  • Joined: 06-January 09

calling on variables from the main class

Posted 23 June 2013 - 11:58 AM

I may be going about this the entirely wrong way but I am still learning how to work Java out in the right manner. I know my code gets messy and I start getting myself confused, but to be honest I am usually just following along with what the instructor does and then just build on top of it. Anyway, I am on the last phase of the class and we are supposed to be building a full on GUI that displays a window for ordering a product (or several) complete with name and address of course. We don't actually have to have the order print to a file like I thought we would (as per the task list), but I still want to know for myself if this is possible.

I have a button handler that I want to write the order to a file, but this event isn't in the main class (again I was just going off of what the instructor showed us and built off it), yet I need to call on variables from the main class. I don't understand how to do that or if it is possible. Or maybe I need to put that action elsewhere? Here is the full code below.

package monkeynaroundphase5;

 * Imports

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

 * @author adamcrum

public class MonkeyNAroundPhase5 extends JFrame 

    public static void main(String[] args) throws IOException 
        // JFrame
        JFrame window = new MonkeyNAroundPhase5();
        window.setLayout(new FlowLayout(FlowLayout.LEFT));
        window.getContentPane().setBackground (Color.WHITE);
    public MonkeyNAroundPhase5()
        setTitle("Monkey'N Around! Order System");
        setSize(450 , 700);

        // Application Intro
        JLabel introText = new JLabel ("<html><h2><center><font color = blue>Welcome to Monkey'N Around's <br>Online Ordering System!</font></center></h2><br> To Place an order, please enter your customer information on the <br>lines below and select the products you would like to order.<br><br> When you are finished, click on the Add to Cart button to place <br>the order. <br><br>If you need to stop and cancel, select the cancel button.<br><br></html>");
        // Customer Inputs
        JLabel customerName = new JLabel ("Customer Name: ");
        JTextField custNameInput = new JTextField();
        JLabel streetAddress1 = new JLabel ("Street Address 1: ");
        JTextField stAdd1Input = new JTextField();
        JLabel streetAddress2 = new JLabel ("Street Address 2: ");
        JTextField stAdd2Input = new JTextField();
        JLabel cityAddress = new JLabel ("City: ");
        JTextField cityAddInput = new JTextField();
        JLabel stateAddress = new JLabel ("State: ");
        JTextField stateAddInput = new JTextField();
        JLabel zipAddress = new JLabel ("Zip Code: ");
        JTextField zipAddInput = new JTextField();
        // Cart Buttons
        JButton addToCart = new JButton("Add to Cart");
        //Button Handler for Add To Cart
        AddCartButtonHandler atc = new AddCartButtonHandler(); 
        //Button Handler for  Cancel
         JButton cancelOrder = new JButton("Cancel Order");
        CancelButtonHandler cancel = new CancelButtonHandler();
        // Pane Construction
        Container pane = getContentPane();
        GridLayout grid = new GridLayout(0 , 1);
        //Show all labels and buttons
    private class AddCartButtonHandler implements ActionListener 
        public void actionPerformed(ActionEvent e) 
         // this is the section where I am having issues
          String newOrder = "***** Begin New Order *****\n" 
          + custNameInput + "\n"
          + stAdd1Input +"\n"
          + stAdd2Input +"\n"
          + cityAddInput +","
          + stateAddInput + "  "
          + zipAddInput +"\n";
          // how do I get this class to see the above variables from the main class?
            File ordersFile = new File ("/users/adamcrum/Desktop/UserOrders.txt");
            FileWriter var1 = null; 
            try {
                var1 = new FileWriter(ordersFile,true);
            } catch (IOException ex) {
                Logger.getLogger(MonkeyNAroundPhase5.class.getName()).log(Level.SEVERE, null, ex);
            PrintWriter var2 = new PrintWriter(var1);
    private class CancelButtonHandler implements ActionListener
        public void actionPerformed (ActionEvent e)

Is This A Good Question/Topic? 0
  • +

Replies To: calling on variables from the main class

#2 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 143
  • View blog
  • Posts: 342
  • Joined: 22-April 13

Re: calling on variables from the main class

Posted 23 June 2013 - 12:17 PM

Are you required in the assignment to use seperate classes for your ActionListener? It's small enough that you won't need a handler. Just extend the ActionListener from your main class.

Anyways if you do want to call variables from your main class,

MainClassName name = new MainClassName();

Again, I recommend using one class for this.
Was This Post Helpful? 0
  • +
  • -

#3 skuz  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 6
  • Joined: 13-June 13

Re: calling on variables from the main class

Posted 23 June 2013 - 12:17 PM

I would probably go about this by creating functions that retrieve the information. Here's an example of how one of these works:

// This class has the data you want.
public class Foo {
    private int number = 0;
    // This is the getter function. All it does is return the value held in number.
    public int getNumber() {
        return number;

    // You may also use setters, but I don't think you need them in this case. Here's how one would work
    public void setNumber(int i) {
        number = i;

    public static void main(String[] args)
        // Go about getting the number from use, or wherever

// Now we need a class to access the variable. In your case, this would be AddCartButtonHandler
public class GetData {
    public GetData() {
        int num = (new Foo()).getNumber();
        System.out.print("The number is " + num);

However, in your case, you create all of your controls in your constructor. For this to work, I would move them to your class body (hence making them global variables) and instead of returning the entire JTextField, you could simply return its text by doing something like this in your getters:

public class MonkeyNAroundPhase5 extends JFrame {
    // Define your components as global variables
    private JTextField custNameInput;

    // THIS is how I would set up your getters.
    public String getCustName() {
        return custNameInput.getText();

    // Your constructor, where you continue to define components
    public MonkeyNAroundPhase5() {
        custNameInput = new JTextField();

And then from there, it would be easy enough for you to call getCustName() in your handler class to write to the file.

Note however, that because your handler class is declared inside the MonkeyNAroundPhase5 class, when you create the components as global variables, you may be able to access them in the handler without the getters. Not to sure about that but worth trying it out.
Was This Post Helpful? 0
  • +
  • -

#4 Flukeshot  Icon User is offline

  • A little too OCD
  • member icon

Reputation: 417
  • View blog
  • Posts: 1,030
  • Joined: 14-November 12

Re: calling on variables from the main class

Posted 23 June 2013 - 03:52 PM

Because Java is an Object Oriented language, it's advisable to keep it out of the static context. That means, instantiate your objects in main(), but let the objects run the important code.

To expand on skuz's post, you would want to have some validation in your mutators and accessors. Plainly allowing your mutators and accessors to change private member values is just the same as if they were public.
private int number = 0;

public void setNumber(int i) {
   if(number<0 || number>1000)
      System.out.println("number out of range");
      number = i;

Something like that would be sufficient validation for a simple task.

Lastly, to make long strings more code-window friendly, you can split them up with concatenation.
String s = "this is a very very very very very very very very very very very very very very very very very very long string";
//could be written as
String s = "this is a very very very very very very " + 
   "very very very very very very " + 
   "very very very very very very long string";

Hope these little points can help.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1