Results 1 to 16 of 16
Like Tree1Likes
  • 1 Post By KevinWorkman

Thread: using string representation of component to access its methods

  1. #1
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default using string representation of component to access its methods

    Hello everyone

    Everytime i make an application, i always create a database structure to hold all the text in 2 languages. The way i accomplish that is by holding all the component names in one table and another holding the langagues. I then match the IDs in a relation table with the corresponding text.

    However when Java gets involved all i have is a string representation of the component name i'm trying to access. What i need to do is basically iterate through the component list i retrieve and compare such as :

    Java Code:
    if (retrievedComponentString.compareTo("mnuFile"))
    {
        mnuFile.setText(getLanguageText(rertievedComponentString, retrievedComponentLanguage))
    }
    Of course if i have hundreds of components that method becomes enormous and gets me wondering if there is a simpler way to do this.

    So the question is : Is there a way to access a components methods if i only have a String representation of its name?!

  2. #2
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    BTW i googled this for a long time but did not come up with anything. It's hard to think of proper keywords to look for too...

  3. #3
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    Do i have to iterate through all the content pane's component and do something like :
    Java Code:
    if (component.getName().compareTo("retrievedComponentString") == 0)
    {
        ...
    }
    
    or is there a better way?

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,696
    Rep Power
    8

    Default

    Why don't you just add them to a Map?

    Also, you don't have to do that == 0 part. Just use equals() or equalsIgnoreCase().
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    Quote Originally Posted by KevinWorkman View Post
    Why don't you just add them to a Map?

    Also, you don't have to do that == 0 part. Just use equals() or equalsIgnoreCase().
    You mean adding all the Frame's components in a hashmap by iterating through the content pane? In that case i might as well just skip the map and just compare the names no? Or is there a way to send all the components to a map in one shot?

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,696
    Rep Power
    8

    Default

    Quote Originally Posted by d3n1s View Post
    You mean adding all the Frame's components in a hashmap by iterating through the content pane? In that case i might as well just skip the map and just compare the names no? Or is there a way to send all the components to a map in one shot?
    What I meant was, when you initialize the components, add them to the HashMap. Or even if you did iterate through the content pane, at least you'd only have to do it once instead of at the beginning.

    But if you add them to the HashMap at initialization time, that also helps in case you're adding/removing components on the fly- it doesn't sound like you are, but you might want to add that in the future, and your current idea wouldn't support that.
    Fubarable likes this.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,696
    Rep Power
    8

    Default

    Actually, you don't even need them in a Map. Just add them to a List, and when you change the language, iterate over the List, setting the text of each component based on its name. You wouldn't even need any if statements.

    Wait.. you wouldn't need any if statements at all, would you? Why do you use them?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    the reason i needed the conditions was because i didn't think of adding them to a map! Very good idea, that way i can create a map with the component and it's name as the key, iterate through my table and match with the corresponding value in the map!

  9. #9
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default

    a database structure to hold all the text in 2 languages
    Sounds to me like reinventing java.util.ResourceBundle

    db

  10. #10
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default

    are you telling me there's a built in feature to do what i'm trying to do?! Oh well my way is more fun but thx Darryl i'll look it up.

  11. #11
    fxRichard is offline Member
    Join Date
    Dec 2008
    Posts
    64
    Rep Power
    0

    Default Re: using string representation of component to access its methods

    The short answer to your original question:
    "So the question is : Is there a way to access a components methods if i only have a String representation of its name?!"

    Maybe, you need to use reflection, if your gui components are declared class level or globally you can, if they are declared within a method then you have to use a more custom solution. To start if you use reflection you will have to get an instance of the class object that represents your active object, then look up the declared fields on that object, change their access level so you can access them whether or not they are privately declared and then call your methods on these objects. It sounds more complicated than it is.

    If your gui objects are created at the method level then you will have to take an approach of setting the swing components name to the same name as the variable name, then you can recursively traverse the root container's components looking for the object with the given name to find the specific object you need.

    Are either of these solutions ideal...probably not for what you are doing, there is probably a better design that will meet your goals but depending on your situation and circumstances one of the solutions above will work.

  12. #12
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default Re: using string representation of component to access its methods

    Quote Originally Posted by fxRichard View Post
    The short answer to your original question:
    "So the question is : Is there a way to access a components methods if i only have a String representation of its name?!"

    Maybe, you need to use reflection, if your gui components are declared class level or globally you can, if they are declared within a method then you have to use a more custom solution. To start if you use reflection you will have to get an instance of the class object that represents your active object, then look up the declared fields on that object, change their access level so you can access them whether or not they are privately declared and then call your methods on these objects. It sounds more complicated than it is.

    If your gui objects are created at the method level then you will have to take an approach of setting the swing components name to the same name as the variable name, then you can recursively traverse the root container's components looking for the object with the given name to find the specific object you need.

    Are either of these solutions ideal...probably not for what you are doing, there is probably a better design that will meet your goals but depending on your situation and circumstances one of the solutions above will work.
    Hey you've got a point! I was able to list all the fields of the class (including the components!) using :

    Java Code:
    private void listFields()
        {
            Field[] fields = this.getClass().getDeclaredFields();
            for (Field f: fields)
            {
                System.out.println(f.getName());
            }
        }
    How would i then call setText() on any of those components since they are just string representations at this point? I managed to make the concept work by adding the components to a map <String, Component> as previously suggested but your idea seems much more elegant!

    Thanks!

  13. #13
    fxRichard is offline Member
    Join Date
    Dec 2008
    Posts
    64
    Rep Power
    0

    Default Re: using string representation of component to access its methods

    Here is an example of how...

    PHP Code:
    import java.lang.reflect.Field;
    import javax.swing.JTextField;
    
    public class Test
    {
    	private JTextField myTextField = new JTextField("This is some text");
    	
    	/*******************************
    	 * 		STATIC METHODS
    	 *******************************/
    	public static void main(String[] args) throws Exception
    	{
    		//get the field by name
    		Field field = Test.class.getDeclaredField("myTextField");
    		
    		//set accessible so we can modify a private field, this field is private but since we are not
                    //technically changing the field itself we do not have to call it, only if we were changing the
                    //field would we have to call this.
    		//field.setAccessible(true);
    		
    		//create an object in which to modify the field since we don't have
    		//any, in your code you may already have a reference to an instance of the
    		//class that has already been created.
    		Test test = new Test();
    		
    		//display the test objects textfield text
    		test.showText();
    		
    		//change the test objects's myTextField's text
    		((JTextField)field.get(test)).setText("This text has been modified");
    		
    		//display the test object's textfield text now
    		test.showText();
    	}
    	
    	/*******************************
    	 * 		INSTANCE METHODS
    	 *******************************/
    	public void showText()
    	{
    		System.out.println(myTextField.getText());
    	}
    }
    Last edited by fxRichard; 09-18-2011 at 05:38 PM.

  14. #14
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default Re: using string representation of component to access its methods

    WHAT you can typecast a field to a component? Sweet! Can you test them using instanceof to see if they are JLabels, JButtons etc? Reflection is truly awesome!

  15. #15
    fxRichard is offline Member
    Join Date
    Dec 2008
    Posts
    64
    Rep Power
    0

    Default Re: using string representation of component to access its methods

    Yes you can typecast and use instanceof, and I would highly recommend that put in error/exception checking etc. My code above is simply an example of how to do what you are asking :-)

  16. #16
    d3n1s is offline Member
    Join Date
    Apr 2011
    Posts
    69
    Rep Power
    0

    Default Re: using string representation of component to access its methods

    Well it works like a charm, here's my code (using hibernate classes):

    Java Code:
    try
            {
                Field[] fields = this.getClass().getDeclaredFields();
                for (Field f: fields)
                {
                    Object obj = f.get(this);
                    if (obj instanceof JComponent)
                    {
                        Composant comp = Composant.getComposant(f.getName());
                        if (comp != null)
                        {
                            if (obj instanceof JMenu)
                            {
                                ((JMenu)obj).setText(Composant_Langage.getTranslation(comp, langage));
                            }
                            else if (obj instanceof JMenuItem)
                            {
                                ((JMenuItem)obj).setText(Composant_Langage.getTranslation(comp, langage));
                            }
                            else if (obj instanceof JButton)
                            {
                                ((JButton)obj).setText(Composant_Langage.getTranslation(comp, langage));
                            }
                            else if (obj instanceof JLabel)
                            {
                                ((JLabel)obj).setText(Composant_Langage.getTranslation(comp, langage) + " : ");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logs.getFrameLog().log(Level.SEVERE, "Error translating component " + comp + " : ", ex);
            }
    Some of these classes are my own but this basic structure can be applied to anything!

    Thanks again!

Similar Threads

  1. Java Representation
    By lary in forum New To Java
    Replies: 2
    Last Post: 05-08-2011, 07:28 AM
  2. Memory representation of an array?
    By hellolleh in forum Forum Lobby
    Replies: 2
    Last Post: 04-29-2010, 03:05 AM
  3. Ask for help on Java access to protected methods
    By fangzhong in forum Advanced Java
    Replies: 3
    Last Post: 02-17-2009, 01:50 PM
  4. graphical representation of website structure
    By mrpwnt in forum New To Java
    Replies: 0
    Last Post: 12-09-2008, 10:08 PM
  5. Replies: 1
    Last Post: 07-20-2008, 04:42 PM

Posting Permissions

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