LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-08-2007, 12:45 PM   #1
bingo
Member
 
Registered: Apr 2006
Distribution: Slackware
Posts: 57

Rep: Reputation: 15
Java - method names & jTables


I'm writing my first Java app, and have 2 things I'm stuck on...

- I have a class that contains a bunch of methods. I want to be able to reference these methods based on the value of a String variable. So... my class is named "OrderLine", and my variable is String "item". I want to be able to reference the various methods by calling "OrderLine.item()". Is this possible? If not, what is the best way to accomplish this?

- I would like to use a jTable on my GUI, but I'm not finding the info I need. All I really need to do is define the values of specific cells, and do a little math on some. How do I assign a value, based on a variable, to a jTable cell?

Thanks in advance for the help!
 
Old 09-08-2007, 04:26 PM   #2
Mega Man X
LQ Guru
 
Registered: Apr 2003
Location: ~
Distribution: Ubuntu, FreeBSD, Solaris, DSL
Posts: 5,339

Rep: Reputation: 65
For the first question, use "set" and "get" methods (called getters and setters). For example:

Code:
public class OrderLine {

    private String item;

    public String getItem(){
        return item;
    }

    public void setItem(String item){
        this.item = item;
    }
}
So now, let's say you have another class, like "Main", where you wish to retrieve and/or set items. Do something like this:

Code:
public class Main{

    public static void main(String[] args) {

        public OrderLine order = new OrderLine();
        order.setItem("Nintendo Wii");

        System.out.println("Your order is: " + order.getItem());

}
For the second, take a look here to learn how to use tables:

http://java.sun.com/docs/books/tutor...nts/table.html

Regards!

Last edited by Mega Man X; 09-08-2007 at 04:28 PM.
 
Old 09-08-2007, 05:32 PM   #3
bingo
Member
 
Registered: Apr 2006
Distribution: Slackware
Posts: 57

Original Poster
Rep: Reputation: 15
Thanks for the reply! The getters and setters make sense, but I don't think that I described my problem well. Hopefully this will help...

In my "OrderLine" class, let's say I have methods "a", "b", and "c". In my main class, there is a String variable "item", that I want to determine which method to call. So, if the value of "item" is "a", I want to reference OrderLine.a, and if "item" is "b", I want to reference OrderLine.b. Right now I'm doing this with a bunch of if-then statements in a method of my main class, but this will soon be very lengthy. Is there a better solution?

I will spend some time on the jTable link, thanks!
 
Old 09-08-2007, 08:29 PM   #4
nadroj
Senior Member
 
Registered: Jan 2005
Location: Canada
Distribution: ubuntu
Posts: 2,539

Rep: Reputation: 60
i dont think its possible. well, at least from my experience with java (or any language) i havent seen (or required) a 'feature' like this. often when your trying to do something with programming and you find it cant be done it may be an identifier of poor program design.

how different is each method (a vs b vs c, etc), _really_? is it possible for you to just make one method to do the common statements, and have the method take in a string parameter, then have just a few if statements to handle the individual cases? could you show us two different methods you have written/require (ie a() and b() or whatever their names).
 
Old 09-08-2007, 09:09 PM   #5
95se
Member
 
Registered: Apr 2002
Location: Windsor, ON, CA
Distribution: Ubuntu
Posts: 740

Rep: Reputation: 32
This can be done with Java reflection. Here is an example:

A simple class, ABC:
Code:
public class ABC {
    public void a(String msg) {
	System.out.println("a: " + msg);
    }

    public void b(String msg) {
	System.out.println("b: " + msg);
    }

    public void c(String msg) {
	System.out.println("c: " + msg);
    }
}
Then some code that reflects ABC:
Code:
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

import java.util.Arrays;

public class ReflectionEx {
    public static void main(String[] args) {
	Class klass = null;			// Class to be reflected
	Object abcInstance = null;		// An instance of klass
	String arg1 = "Hello";			// The argument to its methods
	Class[] paramTypes = { String.class };	// The parameter types the 
						// method to invoke takes

	try {
	    // Create an instance of class ABC

	    klass = Class.forName("ABC");
	    abcInstance = klass.newInstance();

	} catch (InstantiationException ex) {
	    // indicates the class is not instantiable, ex. abstract class,
	    // interface, primitive, etc.
	    System.out.println("Couldn't create instance of class " 
			       + klass.getName());
	    return;

	} catch (IllegalAccessException ex) {
	    System.out.println("Class constructor or class is not accessible");
	    return;

	} catch (ClassNotFoundException ex) {
	    System.out.println("Can't find class ABC");
	    return;
	}

	// Get all methods of class ABC
	
	Method[] methods = klass.getMethods();

	// Invoke all methods with paramters matching paramTypes (ie. take 1
	// String), with the argument arg1

	for (int i = 0; i < methods.length; i++) {
	    if (Arrays.equals(methods[i].getParameterTypes(), paramTypes)) {
		try {
		  methods[i].invoke(abcInstance, arg1);

		} catch (IllegalAccessException ex) {
		    // Method may be private, protected, etc.
		    System.out.println("Illegal access to method " 
				       + methods[i].getName() + " w/ modifiers "
				       + Modifier.toString(
						methods[i].getModifiers()));

		} catch (InvocationTargetException ex) {
		    // Something wrong w/ the target object passed in
		    System.out.println("Couldn't invoke method "
				       + methods[i].getName() + " on " 
				       + abcInstance.toString());
		}
	    }
	}
    }
}
Check out the Java reflection API for more details.
http://java.sun.com/j2se/1.5.0/docs/...e-summary.html
http://java.sun.com/j2se/1.5.0/docs/...ang/Class.html
http://java.sun.com/docs/books/tutor...ect/index.html

Make sure that you NEED to use reflection to do what you want to do and that you can't do it using normal OO techniques.

EDIT:
In reference to the very last thing I said. Reflection is very useful for dynamic loading of classes (plugins and whatnot) and for automated testing and the like. It should not take the place of proper OO design! Nadroj is very correct about not needing it.

If you were making a spread sheet program, for instance, and you wanted users to be able to enter function names. Then you would take that function name and execute some corresponding Java function. You could do this using reflection. Doing, basically, a 1:1 correspondance of function names entered by the user to java function names of some class. But this would be better done by creating an interface, for example, that has a few methods... say:
Code:
public interface Function {
    public int getParameterCount();
    public String execute(String[] args);
}
Then, for each function, create a implementation of this class. In your code create an instance, and put it in a hashmap, where the keys are the function names et voila!

Last edited by 95se; 09-08-2007 at 09:39 PM.
 
Old 09-08-2007, 09:19 PM   #6
95se
Member
 
Registered: Apr 2002
Location: Windsor, ON, CA
Distribution: Ubuntu
Posts: 740

Rep: Reputation: 32
Quote:
Originally Posted by nadroj View Post
i dont think its possible. well, at least from my experience with java (or any language) i havent seen (or required) a 'feature' like this. often when your trying to do something with programming and you find it cant be done it may be an identifier of poor program design.

how different is each method (a vs b vs c, etc), _really_? is it possible for you to just make one method to do the common statements, and have the method take in a string parameter, then have just a few if statements to handle the individual cases? could you show us two different methods you have written/require (ie a() and b() or whatever their names).
See my post above. Java reflection is really cool. There are many languages that provide support (on some level) for reflection; Java, C# (.NET in general really), Python, Perl, Ruby. I even seen reflection for C++, though it was fairly invasive.
 
Old 09-08-2007, 09:34 PM   #7
nadroj
Senior Member
 
Registered: Jan 2005
Location: Canada
Distribution: ubuntu
Posts: 2,539

Rep: Reputation: 60
ya ive never heard of it before, now i know. good trick they got there!

and i agree with your 'NB/warning' comment in your previous post.
 
Old 09-09-2007, 10:18 AM   #8
bingo
Member
 
Registered: Apr 2006
Distribution: Slackware
Posts: 57

Original Poster
Rep: Reputation: 15
I'm always amazed at the level of knowledge and the willingness to help around here, thanks again!

The project I'm working on is a restaurant self-service ordering program, to be run on a touch-screen for a customer. I'm not a developer (obviously!), this is just a side-project that could be a really cool addition.

The comments about the design of my program are probably right-on. As I'm learning more, I keep shifting my approach. I'll give a brief overview of my current design...

I have 2 classes right now, a main GUI class, and an "OrderLine" class. The GUI has a main JFrame, to select things like a drink, or a sandwich. There is a JDialog that allows a customer to select the details of each item (drink=flavor, small, medium, large; sandwich=toppings, etc.). The OrderLine class takes the boolean values of the details such as small, medium, and large, and constructs the order, as well as calculates the price. Since each item type can have vastly different options, I wanted to have a method for each type (drink, sandwich, ice cream, etc.), in the OrderLine class. At one time, I had a class for each type, but shifted to this approach. I'm using a single JDialog to toggle the options for every item, making the appropriate JToggleButtons visible as needed for the given item. The values get passed to OrderLine when the "Done" button is pressed on the JDialog. Since I'm using the same JDialog for every item, I'm trying to call the different methods in OrderLine based on if the user selected a hamburger vs. a drink to get to the JDialog. Currently, I have a method in the main class with a bunch of if-then statements to determine which method to call. Does that make any sense?

How would you design a program such as this? Thanks!
 
Old 09-09-2007, 12:18 PM   #9
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Strong suggestion: please take a look here
<= Definitely good advice!

And the corresponding code here
<= Note how straightforward it is: basically just adding a bunch of buttons to a panel...
.. and letting the panel's "GridLayout" manager do all the heavy lifting
 
Old 09-09-2007, 11:39 PM   #10
95se
Member
 
Registered: Apr 2002
Location: Windsor, ON, CA
Distribution: Ubuntu
Posts: 740

Rep: Reputation: 32
I wouldn't suggest creating separate class for each. But I would not use methods either. Since you are dealing with products, you should be able to add and remove them easily. Perhaps in a database or a text file or the like. You should make a general product class that is functional enough that it can deal with a wide variety of options and product types. You can also subclass it if you want to add functionality that is more specific (like a "Beverage" subclass for all beverages). Each instance of the class should represent one product, and this should be able to handle stuff like options (small, medium, large, hot, cold, flavour, etc.). It shouldn't be hard coded, but you could use a database backend to keep these options in and make the product class somehow use this. Another really cool thing you could do, but is more advanced, is use the Java scripting framework to allow logic to be added with Groovy or something if needed.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
java newbie question method headers and if statements dflan98783 Programming 6 02-21-2007 11:18 PM
Rewriting small method (Java) megabot Programming 11 02-13-2007 11:51 PM
Method readLine() in Java...help KissDaFeetOfSean Programming 1 09-09-2005 12:41 AM
[java] Method signature precision pycoucou Programming 6 06-20-2004 11:31 AM
how do you reload the 'main' method in Java? ludeKing Programming 1 05-29-2004 10:22 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:04 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration