LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Java - method names & jTables (https://www.linuxquestions.org/questions/programming-9/java-method-names-and-jtables-583184/)

bingo 09-08-2007 12:45 PM

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!

Mega Man X 09-08-2007 04:26 PM

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!

bingo 09-08-2007 05:32 PM

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!

nadroj 09-08-2007 08:29 PM

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

95se 09-08-2007 09:09 PM

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!

95se 09-08-2007 09:19 PM

Quote:

Originally Posted by nadroj (Post 2886058)
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.

nadroj 09-08-2007 09:34 PM

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.

bingo 09-09-2007 10:18 AM

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!

paulsm4 09-09-2007 12:18 PM

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

95se 09-09-2007 11:39 PM

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.


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