Results 1 to 13 of 13
  1. #1
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default [SOLVED]Making an array public or any variable to use across classes and Java files?

    I'm sort of new to Java as you can already see from me posting in this forum.
    What I want to know is how can I make an array, or any variable for that matter public so any class or java file within the workspace can use it?
    For example I'm making a tic tac toe game and I wanted to use a method that would check for the player and change the variable so the program would know whose turn it was. However my program would not detect the variable "player" and would say it couldn't be found. I found a solution around that by creating a temp variable and sending over the player variable and returning a different named variable. Now I want to check if a button already contains an image however whenever I attempt to check an array within the file that contains my methods it says that the array can't been found. How do I go about making this array public and for future use any variable so I can use it across classes and files within the workspace?
    Here's my code.

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JOptionPane;
    
    
    public class TicTacToe extends JFrame implements ActionListener
    {
    	JButton tic[][] = new JButton[3][3];
    	private Methods method;
    	public int player = 0;
    	public int temp;
    
    	public TicTacToe()
    	{
    		Container contentPane = getContentPane();
    		contentPane.setLayout(null);
    		contentPane.setBackground(Color.white);
    
    		method = new Methods();
    
    
    		setTitle("Tic Tac Toe Game");
    		setSize(600,630);
    		setLocation(200,200);
    		setResizable(false);
    		setDefaultCloseOperation(EXIT_ON_CLOSE);
    
    		int xps = 0;
    		int yps = 0;
    		int b = 0;
    		for(int x=0;x<3;x++)
    		{
    			for(int a=0;a<3;a++)
    			{
    				tic[a][b] = new JButton("-");
    				tic[a][b].setBounds(xps,yps,200,200);
    				tic[a][b].addActionListener(this);
    				contentPane.add(tic[a][b]);
    				xps+=200;
    
    			}
    				yps+=200;
    				xps=0;
    				b++;
    
    		}
    
    
    
    
    	}
    
    
    
    	public void actionPerformed(ActionEvent e)
    	{
    
    		if(e.getSource() instanceof JButton)
    {
    
    
    
    			JButton clicked = (JButton)e.getSource();
    
    
    
    
    			if(player == 0)           //moves for player 1
    		{
    
    
    
    			 if(clicked == tic[0][0])
    			{
    				tic[0][0].setIcon(new ImageIcon("Cross.jpg"));
    				tic[0][0].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[1][0])
    			{
    				tic[1][0].setIcon(new ImageIcon("Cross.jpg"));
    				tic[1][0].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[2][0])
    			{
    				tic[2][0].setIcon(new ImageIcon("Cross.jpg"));
    				tic[2][0].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[0][1])
    			{
    				tic[0][1].setIcon(new ImageIcon("Cross.jpg"));
    				tic[0][1].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[1][1])
    			{
    				tic[1][1].setIcon(new ImageIcon("Cross.jpg"));
    				tic[1][1].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[2][1])
    			{
    				tic[2][1].setIcon(new ImageIcon("Cross.jpg"));
    				tic[2][1].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[0][2])
    			{
    				tic[0][2].setIcon(new ImageIcon("Cross.jpg"));
    				tic[0][2].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[1][2])
    			{
    				tic[1][2].setIcon(new ImageIcon("Cross.jpg"));
    				tic[1][2].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    			else if(clicked == tic[2][2])
    			{
    				tic[2][2].setIcon(new ImageIcon("Cross.jpg"));
    				tic[2][2].setText("x");
    				temp = method.move(player);
         			player = temp;
    			}
    
    		}
    
    		else if (player == 1)									//moves for player 2
    			{
    
    
    				if(clicked == tic[0][0])
    				{
    					if(tic[0][0].getText() != "x")
    					{
    					tic[0][0].setIcon(new ImageIcon("Circle.jpg"));
    					tic[0][0].setText("o");
    					temp = method.move(player);
         				player = temp;
         				}
    				}
    
    				else if(clicked == tic[1][0])
    				{
    					tic[1][0].setIcon(new ImageIcon("Circle.jpg"));
    					tic[1][0].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[2][0])
    				{
    					tic[2][0].setIcon(new ImageIcon("Circle.jpg"));
    					tic[2][0].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[0][1])
    				{
    					tic[0][1].setIcon(new ImageIcon("Circle.jpg"));
    					tic[0][1].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[1][1])
    				{
    					tic[1][1].setIcon(new ImageIcon("Circle.jpg"));
    					tic[1][1].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[2][1])
    				{
    					tic[2][1].setIcon(new ImageIcon("Circle.jpg"));
    					tic[2][1].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[0][2])
    				{
    					tic[0][2].setIcon(new ImageIcon("Circle.jpg"));
    					tic[0][2].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[1][2])
    				{
    					tic[1][2].setIcon(new ImageIcon("Circle.jpg"));
    					tic[1][2].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    
    				else if(clicked == tic[2][2])
    				{
    					tic[2][2].setIcon(new ImageIcon("Circle.jpg"));
    					tic[2][2].setText("o");
    					temp = method.move(player);
         				player = temp;
    				}
    			}
    
    
    
    
    }
    
    
    
    
    	}
    
    	public static void main(String args[])
    	{
    		TicTacToe frame = new TicTacToe();
    		frame.setVisible(true);
    	}
    }
    and my methods file

    Java Code:
    import javax.swing.JOptionPane;
    
    public class Methods {
    
    
    
        public  Methods()
        {
        }
    
    public int move(int player)
    {
    
    	if(player == 0)
    	{
    		player = 1;
    	}
    	else if(player == 1)
    	{
    		player = 0;
    	}
    	return player;
    }
    
    
    
    
    
    }
    Last edited by Jonatan10; 12-12-2010 at 06:05 PM.

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    It's not clear to me why you want a separate Methods class. You can certainly put your move() method right in your TicTacToe class. Anyway, player is a public instance variable, which means that if a class has access to a TicTacToe object, it can change the value of that object's player. Your Methods class doesn't know anything about any TicTacToe object, and the player variable in its move() method is a separate local int. If you want your Methods object to know about your TicTacToe object, one way to set that up is to pass a reference to a Methods constructor. So in the Methods class, you have this:
    Java Code:
    public class Methods {
        private TicTacToe ticTacToe;
        
        public Methods(TicTacToe ticTacToe) {
            this.ticTacToe = ticTacToe;
        }
    
        public void move() {
            if (ticTacToe.player == 0) {
                ticTacToe.player = 1;
            } else {
                ticTacToe.player = 0;
            }
        }
    }
    Notice that move() doesn't need a parameter, because it's working on the instance variable player of its own instance variable ticTacToe.

    And then in your TicTacToe class you have this:
    Java Code:
        public TicTacToe() {
            ...
            private Methods methods = new Methods(this);
            ...
        }
    Also, you didn't ask about this, but you have a whole lot of duplicated code, and you already have discovered the trick to getting rid of it:
    Java Code:
    			JButton clicked = (JButton)e.getSource(); [COLOR="Blue"]// that's the hard part. Now...
                            clicked.setIcon(icons[player]);
                            clicked.setText(tokens[player]);
                            methods.move();
                            checkForEndOfGame(); // write this method too[/COLOR]
    I'll let you work out how to initialize the icons and tokens arrays.

    -Gary-

  3. #3
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default

    I realize I could put the methods within the tictactoe class but we have been taught to use a different methods class so we can used to the idea of having a seperate one so we could maybe in the future use the same methods with another program. For this reason I wanted to know how to make the variables accessible across the classes.
    I'm really new to this stuff so I'm sorry for asking but I want to understand what all this is doing.
    Why did you add this to the new Methods(this);?
    Also, what exactly does the last part of code do? I'm assuming that I would have to create an array for images and then another array for text so that way based on who the player is it will set the text x and the image x for player one and the set an o and the picture for player 2?
    and one last thing for the check for end of game method. That's why I was originally asking how I could make the tic array public so I could make a method that checks the text of the button because If I attempt to do that right now
    with this method for example.
    Java Code:
    public void check()
    {
    	if(tic[0][0].getText() = "x")
    	{
    
    	}
    }
    I get the error.
    "cannot find symbol variable tic"
    would passing the value of the variable to my method as a parameter be the only way to use it?

  4. #4
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    If that check() method is in your Methods class, then it will also need a reference to your TicTacToe object in order to access its instance variables and methods. That's what that this parameter was about -- it associates the TicTacToe object this with the Methods object you are creating. (The keyword this within a Java class file is a pointer to the currently running object.) Once you have the reference, you can do
    Java Code:
        if (ticTacToe.tic[0][0].getText().equalsIgnoreCase("X")) {
            ...
        }
    It's still bad style, though. Those methods really belong in the TicTacToe class directly. There are good reasons for putting certain methods in separate classes, but these methods don't fit those reasons.

    -Gary-

  5. #5
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default

    So I see what you did now. You made it so I can access all the variables and stuff of the tictactoe class through it. So now I can use any variable within it by using
    ticTacToe.(thing here)
    Another question. I know how to create string array for tokens but how do I create an array that holds images for icon?
    I understand why you say that having the methods in a different file isn't really useful but I think my teacher required it.
    Last edited by Jonatan10; 12-12-2010 at 03:48 PM.

  6. #6
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Java Code:
            public ImageIcon[] icons = new ImageIcon[];
            icons[0] = new ImageIcon("Cross.jpg");
            icons[1] = new ImageIcon("Circle.jpg");
    Note that the first new initializes the array, but does not initialize any ImageIcon objects.

    Don't settle for "I think the teacher required it." Don't let your teachers require crass stupidities. If it doesn't make sense to you, don't do it. Talk to your instructor and get some clarification on when it's a good idea to put methods in a separate class.

    -Gary-

  7. #7
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Jonatan10 View Post
    So now I can use any variable within it by using
    ticTacToe.(thing here)
    Any public instance variable or method (or package-protected, if the other class is in the same package). And it's still a bad approach, as it breaks the principle of encapsulation. The whole idea of object-oriented programming is that each class of objects is responsible for its own state and behavior, and other classes of objects interact with it only through its public API. It's a very bad idea to let other objects mess around with your instance variables directly unless you have a very good reason to do it that way.

    -Gary-

  8. #8
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default

    Thank you, I got it.
    How do I check an array or any variable for a string?
    I want to check if it has one. Not for a specific one.
    Like I know I can use token.contains() to check for a specific string but how do I check for the existence of one?

    He might not have required it for this program but he required it for a previous geometry program so I decided to do it for this one as well. I do see why he required it on the previous one and why it's not such a great idea on this one though.

  9. #9
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Quote Originally Posted by Jonatan10 View Post
    How do I check an array or any variable for a string?
    I want to check if it has one. Not for a specific one.
    Like I know I can use token.contains() to check for a specific string but how do I check for the existence of one?
    That's not what you want to do. You're not checking the array, but checking the button at a certain array position.
    Java Code:
            if (tic[0][0].getText().equals("x") { // or "o" or "-"
                ...
    If you really want to check for the existence of any String (including the empty String ""), you would do:
    Java Code:
            if (tic[0][0].getText() != null) {
                ...
    -Gary-

  10. #10
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default

    Yes. Sorry I want to check the button.
    What I want to do is if it has a string (x or o) then I don't want to post another image onto it.
    However, whenever I do
    Java Code:
    	if(clicked.getText() != "x" || "o" )
    			{
    			clicked.setIcon(icon[player]);
                clicked.setText(token[player]);
                method.move();
    
    			}
    I get the error "operator || cannot be applied to boolean,java.lang.String" I don't understand what that means.
    and whenever I use
    Java Code:
    if(clicked.getText() = null )
    I get the error "unexpected type"

  11. #11
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default

    Ok so I finally got it.
    I used
    Java Code:
    if(clicked.getText().equals("-"))
    Since the buttons originally had that then it works.
    However. I still want to know why I got the previous errors and I also want to know why I have to use .equals instead of = is it because it is a string? if so why does != still work?

  12. #12
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    != works for checking if it's not null, because if it's not null it's != null. :) == checks whether it's a reference to the same object. If you have a String "X" in your code, and the user enters a String "X" at the console, they are not the same object, so == will not indicate a match.
    Java Code:
    	if(clicked.getText() != "x" || "o" )
    The expression 'clicked.getText() != "x"' is a boolean, and "o" is a java.lang.String. You can't use || with a boolean and a java.lang.String. You could use it with two booleans, like this:
    Java Code:
    	if(!(clicked.getText().equals("x") || clicked.getText().equals("o")))
    Also, don't forget that "=" is assignment and "==" is comparison.

    -Gary-

  13. #13
    Jonatan10 is offline Member
    Join Date
    Dec 2010
    Posts
    11
    Rep Power
    0

    Default

    Ah!
    I forgot that = is an assignment and == is comparison.
    Need to remember that.
    Thank you so much for all the help!

Similar Threads

  1. Replies: 1
    Last Post: 08-11-2009, 02:00 PM
  2. Replies: 5
    Last Post: 06-26-2009, 03:03 AM
  3. How to access private data types from public classes?
    By kevzspeare in forum New To Java
    Replies: 3
    Last Post: 03-07-2009, 04:19 AM
  4. Need help with Java classes for making a program.
    By TheDarkReverend in forum Advanced Java
    Replies: 2
    Last Post: 11-28-2008, 04:50 AM
  5. Public class variable
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-03-2007, 09:58 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •