Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: Munchor on March 03, 2011, 12:14:42 pm

Title: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 03, 2011, 12:14:42 pm
I have a few doubts here:

Code: [Select]
public class Main extends JApplet {
    public static void main(String[] args) {
        MyFunction(); //This won't work
    }
    public void MyFunction() {
        System.out.println("Hello World");
    }
}

This won't work, I know I need to declare MyFunction as an object, but I'm not sure of how to do it :S


Spoiler For Spoiler:

package applettouppercase;

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

//////////////////////////////////////////////////////////////// ToUpperCase
public class Main extends JApplet {

    //=================================================== instance variables
    private JTextField _inField  = new JTextField(20);
    private JTextField _outField = new JTextField(20);

    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new JFrame();
        window.setTitle("ToUpperCase Example");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //... JApplet works fine as content pane in a window!
        ToUpperCase myToUpperCaseFunction = new ToUpperCase();
       

        window.pack();                       // Layout components.
        window.setLocationRelativeTo(null);  // Center window.
        window.setVisible(true);
    }

    //================================================== applet constructor
    public void ToUpperCase() {
        //... Create or set attributes of components.
        _outField.setEditable(false);    // Don't let user change output.
        JButton toUpperButton = new JButton("To Uppercase");

        //... Add listener to button.
        toUpperButton.addActionListener(new UpperCaseAction());

        //... Add components directly to applet.  Don't need content pane.
        setLayout(new FlowLayout());
        add(_inField);
        add(toUpperButton);
        add(_outField);
    }

    /////////////////////////////////// inner listener class UpperCaseAction
    class UpperCaseAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //... Convert text in one textfield to uppercase in another.
            String data = _inField.getText();  // Get the text
            String out  = data.toUpperCase();  // Create uppercase version.
            _outField.setText(out);            // Set output field
        }
    }
}

This is my proper code (in the spoiler) and the function I need to declare as an object in the Main function is ToUpperCase().

Thanks much.
   
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 03, 2011, 08:05:17 pm
i'm slightly confused. i know to make your code above work is declaring the method header of MyFunction as static, shown below
Code: [Select]
public static void MyFunction(){
}

you cannot "declare MyFunction as an object" as you put it. MyFunction is a method (java's word for subroutine or function) which cannot be instantiated as an object. in java, classes contain instance variables, 0 or more constructors, and methods. think of a class as a blueprint for an object. it tells the JVM how to instantiate an object.

i see you've found this site (http://www.leepoint.net/notes-java/index.html). its examples are well done and the site is helpful, though it lacks information about how OOP in java operates. Anyway, the problem with the code in the spoiler is that you're trying to make an object from class ToUpperCase, which does not exist because you have not defined it. if you notice, in the original example your code is from, the class name is ToUpperCase. you changed the class name to Main.
replacing
Code: [Select]
ToUpperCase myToUpperCaseFunction = new ToUpperCase();
with
Code: [Select]
window.setContentPane(new Main());

should fix the problem.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Deep Toaster on March 03, 2011, 08:49:20 pm
And Main is a reserved word in Java (for the main() function, which is run when a Java app starts). Even if you are allowed to use Main as the class name there, you're better off choosing a more descriptive name. The name of your class is going to be what objects of that class are called, remember.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 03, 2011, 10:43:40 pm
Main isn't reserved, you can have a method called Main since java is case-sensitive. you cannot have another method "main" though. but you can have a variable "main" or an interface or class "main", though as Deep Thought said, it's not the best idea. the class name should reflect the type of objects the class is a blueprint for. it doesn't make sense to have a class called "Cereal" when the instance variables hold a string name, double GPA and an int gradeLevel. it makes more sense to name that class "Student".
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 04, 2011, 09:06:14 pm
That's actually not entirely correct.  You can have many main functions, but only one is defined as THE main function that is called.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 07, 2011, 02:14:59 pm
Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MyFunction myToUpperCaseFunction = new MyFunction();
MyFunction();

}

public void MyFunction()
{
System.out.println("Hello");
}

}

It didn't really work, it says MyFunction cannot be resolved to a type :S
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 07, 2011, 05:51:56 pm
Code: [Select]
Of course that won't work.  Because MyFunction needs to be a class.  What you need is this:
public class MyFunction {
public static void main(String[] args)
{
MyFunction myToUpperCaseFunction = new MyFunction(); // Create a new instance of this class called MyFunction.  I.E. calls the constructer.
}

public MyFunction() { // This is what is called when you call the "constructer" with no arguments. (Nothing inside the parenthesis)  Notice that there is no return type, as you are creating and returning an "instance" of the object MyFunction.
System.out.println("Object initiated");
}

}
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 07, 2011, 06:36:57 pm
That's actually not entirely correct.  You can have many main functions, but only one is defined as THE main function that is called.

true. i've never seen an overloaded main function though, probably because main isn't a very descriptive name for any situation, really.

and scout, you cannot instantiate an object from a method. this is the proper syntax:
Code: [Select]
ClassName objectName = new ClassName(<param list>);
(yes, i know you can do ClassName objectName = new SubClassName(), i'm keeping it simple.)

graphmastur has corrected your code in one way, here's another way you could do it without changing the class name:
Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MainClass myToUpperCaseFunction = new MainClass();
MyFunction();

}

public void MyFunction()
{
System.out.println("Hello");
}
}
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 07, 2011, 06:38:46 pm
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 07, 2011, 06:52:03 pm
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 07, 2011, 06:53:35 pm
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
it doesn't have to have class in it at all.  If he wanted the class to be MyFunction, he should call it MyFunction, not MyClass.  a method is a function, yes.  But in this case it would be a method of the instance variable.  e.g.:
Code: [Select]
myToUpperCaseFunction.MyFunction();
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 07, 2011, 06:56:01 pm
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
it doesn't have to have class in it at all.  If he wanted the class to be MyFunction, he should call it MyFunction, not MyClass.  a method is a function, yes.  But in this case it would be a method of the instance variable.  e.g.:
Code: [Select]
myToUpperCaseFunction.MyFunction();

yes, that's what i was aiming for. i just realized MyFunction isn't static so my code won't compile, but regardless if i saw a class called MyFunction i would be confused.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 07, 2011, 06:57:21 pm
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
it doesn't have to have class in it at all.  If he wanted the class to be MyFunction, he should call it MyFunction, not MyClass.  a method is a function, yes.  But in this case it would be a method of the instance variable.  e.g.:
Code: [Select]
myToUpperCaseFunction.MyFunction();

yes, that's what i was aiming for. i just realized MyFunction isn't static so my code won't compile, but regardless if i saw a class called MyFunction i would be confused.
True, which is why you name it after what it does.  not just MyFunction.  More like MyUberAwesomeReallyLongThisHasNoSpacesAndIsAPainToInitiateClass. ;-)
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 08, 2011, 08:21:18 am
Thanks Much!

Now, can someone explain me what is going on here:

Code: [Select]
import javax.swing.*;       

public class HelloWorldSwing {
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add the ubiquitous "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Not the Swing Part, the way he calls createAndShowGUI() function.


But mainly thanks for:

Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.MyFunction();

}

public void MyFunction()
{
System.out.println("Hello");
}
}

I'm making my class an object and accessing one of its properties, which is MyFunction() right?
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Deep Toaster on March 08, 2011, 09:34:26 am
I'm making my class an object and accessing one of its properties, which is MyFunction() right?

Well, not really. A class is like a definition, creating a new type of object. Then the line MainClass mainClass = new MainClass(); creates a new instance of the class -- an object. That object is a MainClass object, which has a function called MyFunction, so you're calling that with mainClass.MyFunction();.

I think you'll understand it better if we use a concrete example. Say you want to represent buying a car with Java. First, your Car class defines what a car looks like, what you can do with it, etc.

Code: (Java) [Select]
public class Car
{
    public String make;
    public String model;
    public boolean working;    // Set up the variables of the class.
   
    public Car(String arg1, String arg2)    // A constructor; it gets called when a new Car object is created to set up some of the new Car's variables.
    {
        this.make = arg1;
        this.model = arg2;
        this.working = true;
    }
   
    public void dispMakeModel()
    {
        if (this.working)    // First check if it works or not.
        {
            System.out.println("This car seems to be a " + this.make + " " + this.model + ".");
        }
        else
        {
            System.out.println("This car is broken! Fix immediately!");
        }
    }

    public void drive()
    {
        this.working = false;    // Car no longer works.
        System.out.println("CRAAASH!!!11");
    }
}

That's a complete definition for the Car class. If you want to do something, make a main function:

Code: (Java) [Select]
public static void main(String[] args)
{
    Car myPrecious = new Car("Ford", "Fusion");    // Creates ("buys") a new car with make "Ford" and model "Fusion". Notice that there are two arguments, because the Car constructor above takes two arguments.
    myPrecious.dispMakeModel();     // Displays the string "This car seems to be a Ford Fusion."
    myPrecious.drive();     // Take it out for a drive. Oh darn, you crashed.
    myPrecious.dispMakeModel();     // This time it displays "This car is broken! Fix immediately!"
}

That's what's great about Java: you can represent anything you want by defining a class for it :D
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 08, 2011, 09:56:20 am
From what I got, is a class like a recipe that defines how to do something or how something is made or what it is made of?

Also, I can only have one main function per program, how do I define which function runs first in a class if that class is not the class with the main function?

Also, why is the relation between file names and class names?

Another thing, a function in a class and both have the same name doesn't need a return type, why??

EDIT:

I reread your code and found out that functions with the same name of classes are called constructors!

So, the third and fourth questions are now useless.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Deep Toaster on March 08, 2011, 10:40:06 am
From what I got, is a class like a recipe that defines how to do something or how something is made or what it is made of?

Kind of. It's like an encyclopedia entry that defines the variables and functions associated with an object of that class.

Also, I can only have one main function per program, how do I define which function runs first in a class if that class is not the class with the main function?

You don't. In Java, classes do double-duty as programs if and only if they have a main function. Only one of your class files should have a main function; that's the one you run as a program. All the others are "helper" classes, like libraries.

Also, why is the relation between file names and class names?

What do you mean by file names? If you mean the name of the file you store the public class in, it MUST be the same as the name of the class (case sensitive). So for that Car example above, you must save it as Car.java.

If you mean the name of a function, you can name it anything that's a valid Java identifier (letters/numbers/_ only) and that's not a reserved keyword.

Another thing, a function in a class and both have the same name doesn't need a return type, why??

That's a constructor, which is a special type of function. It constructs an object when it's created. In other words, whenever you create a new object of that type, it gets run through the constructor which can set up/initiate the object.

Hope this helps.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 08, 2011, 03:57:07 pm
Another thing, a function in a class and both have the same name doesn't need a return type, why??

That's a constructor, which is a special type of function. It constructs an object when it's created. In other words, whenever you create a new object of that type, it gets run through the constructor which can set up/initiate the object.

This is the one that I still don't get.

So when I make MainClass mainClass = new MainClass(); will it run through the constructor (if it exists?).

I also don't seem to quite understand private classes.

There can only be once public class per file, right? But there can be classes inside it, that are private. Are those classes like public classes?

I answered myself the last question:

Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.MyFunction();
}

public void MyFunction()
{
System.out.println("Hello");
}
public MainClass()
{
System.out.println("How's it going");
}
}

Output is:

Code: [Select]
How's it going
Hello

EDIT:

A constructor is ran when its classed is called as an object??


Code: [Select]
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class MainClass extends JApplet{
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.theGUI();
System.out.println(Math.cos(100));
}

public void theGUI()
{
JFrame myFrame = new JFrame("Calculator");
myFrame.setSize(400,300);
JButton enterButton = new JButton("Enter");
enterButton.addActionListener(new DisplayMessage());
myFrame.getContentPane().add(enterButton);
myFrame.setVisible(true);
}
private class DisplayMessage implements ActionListener {
public void actionPerformed(ActionEvent e) {
            System.out.println("You just pressed a button");
        }

}
public MainClass()
{
System.out.println("This is the constructor class being ran.");
}
}

I made this piece of code to understand inheritance :D
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Deep Toaster on March 08, 2011, 06:18:31 pm
Another thing, a function in a class and both have the same name doesn't need a return type, why??

That's a constructor, which is a special type of function. It constructs an object when it's created. In other words, whenever you create a new object of that type, it gets run through the constructor which can set up/initiate the object.

This is the one that I still don't get.

So when I make MainClass mainClass = new MainClass(); will it run through the constructor (if it exists?).

Correct. Constructors are used to initiate new objects. For example, in that Car class I could have assigned the car a new Motor, a new Wheels[4], etc.

A constructor is ran when its classed is called as an object??

The class itself isn't an object. You create objects of that class.

Code: (Java) [Select]
Car myFirstCar = new Car("Ford", "Fusion");
Car mySecondCar = new Car("Mercury", "Milan");
Car myThirdCar = new Car("Lincoln", "Navigator");

would create three distinct Car objects. Then you can operate on each one individually:

Code: (Axe) [Select]
myFirstCar.drive();
mySecondCar.drive();    // Not going to crash my brand-new Lincoln :P
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 12, 2011, 08:34:02 am
I see Deep Thought!

I have another question, though:

I get this:

Code: [Select]
Exception in thread "main" java.lang.NullPointerException
at java.awt.Component.setLocation(Component.java:1997)
at MainClass.createGUI(MainClass.java:21)
at MainClass.main(MainClass.java:12)

When running this:

Code: [Select]
import javax.swing.*;

import java.awt.*;

public class MainClass extends JApplet {

JFrame mainWindow = new JFrame("Axe Sprite Editor");

    public static void main(String[] args)
    {
    MainClass mainClass = new MainClass();
    mainClass.createGUI();
    }
    public MainClass()
    {
   
    }
    public void createGUI()
    {
    mainWindow.setSize(640,640);
    mainWindow.setLocation(null);
    mainWindow.setResizable(false);
   
    JPanel pixel1 = new JPanel();
    mainWindow.add(pixel1);
   
   
    mainWindow.setVisible(true);
    }
}

I can't really understand why :S
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Deep Toaster on March 12, 2011, 09:38:44 am
Well according to the traceback it's a "NullPointerException" in the line mainWindow.setLocation(null); in public void createGUI(), which means you're using a null where you're not supposed to. Function setLocation doesn't take a null, in other words.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 12, 2011, 10:45:45 am
does this (http://download.oracle.com/javase/6/docs/api/java/awt/Component.html#setLocation(int, int)) help at all? rarely should you call a method using null as the parameter.

you can do:
Code: [Select]
mainWindow.setLocation(x, y);
or
mainWindow.setLocation(new Point(x, y));
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 12, 2011, 12:30:08 pm
But I've seen code centering windows aka frames using setLocation(null).

My goal is to center the window.

Code: [Select]
import javax.swing.*;

import java.awt.*;

public class MainClass extends JApplet {

JFrame mainWindow = new JFrame("Axe Sprite Editor");


    public static void main(String[] args)
    {
    MainClass mainClass = new MainClass();
    mainClass.createGUI();
    }
    public MainClass()
    {
    mainWindow.setSize(640,640);
    mainWindow.setResizable(false);
    JFrame pixel1 = new JFrame();
    mainWindow.add(pixel1);
    }
    public void createGUI()
    {
    mainWindow.setVisible(true);
    }
}

I also have this code but it seems like I can't add the pixel1 panel to mainWindow, so how do I do it?:

Code: [Select]
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:431)
at java.awt.Container.addImpl(Container.java:1039)
at java.awt.Container.add(Container.java:959)
at javax.swing.JApplet.addImpl(JApplet.java:300)
at java.awt.Container.add(Container.java:365)
at MainClass.<init>(MainClass.java:20)
at MainClass.main(MainClass.java:12)

Thanks much and sorry for disturbing you.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 12, 2011, 12:58:23 pm
You can't add a JFrame to another JFrame like that.  In fact, you never really want to do that.  What exactly are you trying to achieve?

As for setting the window at the center, I believe it is setLocationRelativeTo(null).
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 12, 2011, 12:59:16 pm
Oh damn, I just noticed, I made it JFrame, I meant JPanel. Sorry and thanks for the setLocationRelativeTo thing :)
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 12, 2011, 01:00:04 pm
Oh damn, I just noticed, I made it JFrame, I meant JPanel. Sorry and thanks for the setLocationRelativeTo thing :)
no problem.  I've seen workarounds adding JFrames to other JFrames by doing some weird stuff, but it's usually not necessary.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 12, 2011, 01:03:00 pm
Now from now on, I'm going to have problems in the layout of the window.

I wanna make a 640*640 window with 64 panels of 80*80 as in a grid.

It's a 8*8 grid, each square panel is 80pixels*80pixels, althogether makes a 640*640 pixels window.

Any suggestions/ideas/layouts/code on how to do this?
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 12, 2011, 01:04:43 pm
Now from now on, I'm going to have problems in the layout of the window.

I wanna make a 640*640 window with 64 panels of 80*80 as in a grid.

It's a 8*8 grid, each square panel is 80pixels*80pixels, althogether makes a 640*640 pixels window.

Any suggestions/ideas/layouts/code on how to do this?
If you want it that accurate, just override the paint method and do it yourself.  Especially since there will be boundaries for any other object. (e.g. a frame around the box or panel or whatever you use).
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 12, 2011, 01:05:23 pm
The paint method, thanks, I'm gonna check on that.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 12, 2011, 01:58:15 pm
yes, setLocationRelativeTo(null) is one of the few instances you pass null to a method.
and here's a simple demo (http://pastebin.com/Ssy5ifWk) that [maybe] draws the grid you want scout. i say maybe because i haven't tested it.

Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 12, 2011, 02:02:03 pm
@nemo: Does that code make 64 panels or just draw a grid using graphics?
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 12, 2011, 09:23:37 pm
It just draws a grid on a single JPanel.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 13, 2011, 04:56:55 am
It just draws a grid on a single JPanel.

Yes, what I need to do is much harder, I have to draw 64 panels :S
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 13, 2011, 12:32:01 pm
It just draws a grid on a single JPanel.

Yes, what I need to do is much harder, I have to draw 64 panels :S
In which case, I could give you code, but because of the JPanel having a border, it won't be 640x640.  What exactly are you trying to do?
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 13, 2011, 01:15:34 pm
It just draws a grid on a single JPanel.

Yes, what I need to do is much harder, I have to draw 64 panels :S

modified. (http://pastebin.com/a2acmwh5) that code gives each panel a random color too.
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 13, 2011, 02:46:03 pm
nemo, I get the code and it looks awesome, but nothing happens when I run it, did you try it? I tried it:

MainClass.java
Code: [Select]
import java.awt.*;
import javax.swing.*;
import java.util.Random;
 
public class MainClass extends JFrame{
 
        private NPanel[][] panels = new NPanel[8][8];
 
        public MainClass(String s){
                super(s);
                setSize(8 * 64 + 8, 8 * 64 + 34);
                setDefaultCloseOperation(3);
                Random rand = new Random();
                GridLayout layout = new GridLayout(8, 8);
                getContentPane().setLayout(layout);
                for(int row = 0; row < 8; row++)
                        for(int col = 0; col < 8; col++){
                                panels[row][col] = new NPanel(
                        new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
                        getContentPane().add(panels[row][col]);
                        }
               
        }
        public static void main(String[] args){
                new MainClass("Test");
        }
}
class NPanel extends JPanel{
        public NPanel(Color c){
                setBackground(c);
        }
        public void paintComponent(Graphics g){
                super.paintComponent(g);
        }
}
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 13, 2011, 03:38:39 pm
Change it to this and run it:
Code: [Select]
import java.awt.*;
import javax.swing.*;
import java.util.Random;
 
public class MainClass extends JFrame{
 
        private NPanel[][] panels = new NPanel[8][8];
 
        public MainClass(String s){
                super(s);
                setSize(8 * 64 + 8, 8 * 64 + 34);
                setDefaultCloseOperation(3);
                Random rand = new Random();
                GridLayout layout = new GridLayout(8, 8);
                getContentPane().setLayout(layout);
                for(int row = 0; row < 8; row++)
                        for(int col = 0; col < 8; col++){
                                panels[row][col] = new NPanel(
                        new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
                        getContentPane().add(panels[row][col]);
                        }
                this.setVisible(true);
        }
        public static void main(String[] args){
                new MainClass("Test");
        }
}
class NPanel extends JPanel{
        public NPanel(Color c){
                setBackground(c);
        }
        public void paintComponent(Graphics g){
                super.paintComponent(g);
        }
}
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: Munchor on March 13, 2011, 03:49:52 pm
Thanks much both of you.

Now all I have left to do (and sorry for your time) is to add a function to each panel (a mouse click event). No I'm not asking you to do it for me, just to tell me how to make an event for the first panel, and I'll do the same for the others.

Thanks in advance
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: jnesselr on March 13, 2011, 03:53:17 pm
I won't even tell you that.  I will tell you to look at the javadoc for JPanel (http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JPanel.html), which is a subclass of Component, so look at that javadoc here (http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Component.html).  I would also look at the addMouseListener method which takes a MouseListener object.  The javadoc of which can be found here (http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/MouseListener.html)
Title: Re: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects
Post by: nemo on March 13, 2011, 11:22:00 pm
oops. i forgot setVisible(true).

yeah, you'll either want to make NPanel just implement MouseListener and all the methods in that interface, or make a new class which extends MouseAdapter and just overrides mouseClicked(MouseEvent e){/*your code on mouse click*/};
also, a hint, MouseEvent's have a method getX() and getY() to tell where the user clicked the mouse within a component (e.g. JPanel)