Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Java
Could you help on this reflection technique?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Shawn, post: 1938449"] Hi, I have a very simple GUI program: it has a menu and a text area(JTextArea). In the meu, it has several meu items: "save memo 1", "save memo 2", "get memo 1", "get memo 2", "clear", "exit". What the program does is: when the user types something and click "save memo 1", that line will be saved into an internal string memo1; when the user types something else and click "save memo 2", that line will be saved into another internal string memo2; when the user clicks "get memo 1", that line will be shown in the text area, etc. It is very simple. public class MemoGUI extends JFrame implements ActionListener { .... public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Save Memo 1")) memo1 = theText.getText(); else if (actionCommand.equals("Save Memo 2")) memo2 = theText.getText(); else if (actionCommand.equals("Clear")) theText.setText(""); else if (actionCommand.equals("Get Memo 1")) theText.setText(memo1); else if (actionCommand.equals("Get Memo 2")) theText.setText(memo2); else if (actionCommand.equals("Exit")) System.exit(0); else theText.setText("Error in memo interface"); } } // end of class I want to do something fancy here: using reflection. Unfortunately I know very little about it and I cannot make it work: (I have used setActionCommand to save1, save2, get1, get2,etc) public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); /*****Seeking help for the following lines. I am very new to reflection */ Class c = MenuAction.class; Class[] parameterTypes = new Class[] {MenuAction.class}; Method theMethod; try { theMethod = c.getMethod(actionCommand, null); //not very sure ? theMethod.invoke(obj, args) //compiler says error here !!! } catch (NoSuchMethodException err) { System.out.println(err); } catch (IllegalAccessException err) { System.out.println(err); } catch (InvocationTargetException err) { System.out.println(err); } } private class MenuAction { void save1() { memo1 = theText.getText(); } void save2() { memo2 = theText.getText(); } void get1() { theText.setText(memo1); } void get2() { theText.setText(memo2); } void clear() { theText.setText(""); } void exit() { System.exit(0); } } Thank you very much for your help. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Java
Could you help on this reflection technique?
Top