Results 1 to 7 of 7
- 09-12-2011, 10:01 AM #1
Member
- Join Date
- Jun 2011
- Posts
- 11
- Rep Power
- 0
Need help creating new instances dynamically. Compilable code inside.
I'm sorry for the long code, I've made effort to make it as concise as possible without losing it's illustrative purpose. Should compile without errors.
My goal is to add new Function-objects dynamically to the usedFunctionsListModel when I click a function in the functionList. Currently this is done by checking the name of the function using an if-condition per function and then instantiating the corresponding function. I would prefer if a new instance of any of the functions clicked could be added with the same code to the usedFunctionsListModel. Any thoughts? I have been thinking about using reflection myself, making the functions displayed in the functionList Function-objects instead of Strings, and then using newInstance() to add them to usedFunctionListModel, but I'm not sure how to make that work.
Also I wonder if the way I create a unique card number for adding new JPanels to the cardlayout is a bit awkward. I don't see any other way of doing it, since I'm apparently required to pass a String along with the JPanel object.
Any help would be appreciated, and comments on structure,coding practise etc. in general are also very welcome. Also let me know if anything is unclear.
Java Code:import java.awt.CardLayout; import java.awt.GridLayout; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; public class Example extends JFrame { JList functionList; JList usedFunctionsList; DefaultListModel functionListModel; DefaultListModel usedFunctionsListModel; JButton removeButton, createCodeButton; ExampleHelperClass exampleHelperInstance; JPanel functionListPanel; JPanel usedFunctionListPanel; //Et panel for  holde brukte kommandoer og Create Code-knappen JPanel cards; JPanel defaultGUI; //Constructor public Example(){ exampleHelperInstance = new ExampleHelperClass(); functionListModel = new DefaultListModel(); usedFunctionsListModel = new DefaultListModel(); //Specific functions are added to the functionListModel functionListModel.addElement("Function1"); functionListModel.addElement("Function2"); functionListModel.addElement("Function3"); //Creates the functionList and a panel for it functionListPanel = new JPanel(); functionList = new JList(functionListModel); functionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //Kun en kan velges om gangen functionList.addMouseListener(new FunctionListMouseListener()); JScrollPane listScrollPane = new JScrollPane(functionList); //Creates a list intended to show and select used commands usedFunctionListPanel = new JPanel(); usedFunctionsList = new JList(usedFunctionsListModel); usedFunctionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); usedFunctionsList.addListSelectionListener(new UsedFunctionsListSelectionListener()); JScrollPane usedListScrollPane = new JScrollPane(usedFunctionsList); //Creates a panel with a CardLayout to display the parameter values of a selected function CardLayout cl = new CardLayout(); cards = new JPanel(cl); defaultGUI = exampleHelperInstance.new DefaultGUI(); cards.add(defaultGUI, ExampleHelperClass.DEFAULTGUI); cl.show(cards, ExampleHelperClass.DEFAULTGUI); getContentPane().setLayout(new GridLayout(1,3)); getContentPane().add(listScrollPane); getContentPane().add(cards); getContentPane().add(usedListScrollPane); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args){ Example example = new Example(); example.pack(); example.setLocationRelativeTo(null); //Centers window example.setVisible(true); example.setTitle("Example"); } //Adds elements that are clicked in functionList to usedFunctionsList class FunctionListMouseListener implements MouseListener{ public void mouseClicked(MouseEvent arg0) {} public void mouseEntered(MouseEvent arg0) {} public void mouseExited(MouseEvent arg0) {} public void mousePressed(MouseEvent arg0) {} public void mouseReleased(MouseEvent arg0) { CardLayout cl = (CardLayout)(cards.getLayout()); String element = (String)functionListModel.getElementAt(functionList.getSelectedIndex()); String name = null; if(element.equals("Function1")){ //Adds a new Function to the usedFunctionsListModel and cards ExampleHelperClass.Function1 function1 = exampleHelperInstance.new Function1(1, 1, 1); usedFunctionsListModel.addElement(function1); name = function1.getName(); cards.add(function1,name); }else if(element.equals("Function2")){ ExampleHelperClass.Function2 function2 = exampleHelperInstance.new Function2(1); usedFunctionsListModel.addElement(function2); name = function2.getName(); cards.add(function2,name); } else if(element.equals("Function3")){ ExampleHelperClass.Function3 function3 = exampleHelperInstance.new Function3(1,1); usedFunctionsListModel.addElement(function3); name = function3.getName(); cards.add(function3,name); } System.out.println(name); cl.show(cards, name); usedFunctionsList.setSelectedIndex(usedFunctionsListModel.size()-1); } } //Listens for selection changes in UsedFunctionsList class UsedFunctionsListSelectionListener implements ListSelectionListener{ public void valueChanged(ListSelectionEvent e){ displayParameters(); } } //Displays the marked used function public void displayParameters(){ if(usedFunctionsList.getSelectedIndex() == -1){ //No selection, do nothing }else{ Object element = usedFunctionsListModel.getElementAt(usedFunctionsList.getSelectedIndex()); System.out.println(element); CardLayout cl = (CardLayout)(cards.getLayout()); if(element instanceof ExampleHelperClass.Function1){ cl.show(cards,((ExampleHelperClass.Function1)element).getName()); }else if(element instanceof ExampleHelperClass.Function2){ cl.show(cards,((ExampleHelperClass.Function2)element).getName()); } else if(element instanceof ExampleHelperClass.Function3){ cl.show(cards,((ExampleHelperClass.Function3)element).getName()); } } } }//End ExampleJava Code:import javax.swing.*; import java.awt.*; public class ExampleHelperClass { private static int UniqueCardNumber = 0; final static String DEFAULTGUI = "DefaultGUI"; //Constructor public ExampleHelperClass() { } private void incrementUniqueCardNumber(){ UniqueCardNumber +=1; System.out.println(UniqueCardNumber); } public int getUniqueCardNumber(){ return UniqueCardNumber; } /* * Function1 * */ public class Function1 extends JPanel implements Function{ int value1, value2, value3; JTextField value1TextField,value2TextField,value3TextField; private String name; public Function1(int value1, int value2, int value3){ this.value1 = value1; this.value2 = value2; this.value3 = value3; setLayout(new GridLayout(3,2)); JLabel value1Label = new JLabel("Value1"); JLabel value2Label = new JLabel("Value2"); JLabel value3Label = new JLabel("Value3"); value1TextField = new JTextField(Integer.toString(value1)); value2TextField = new JTextField(Integer.toString(value2)); value3TextField = new JTextField(Integer.toString(value3)); add(value1Label); add(value1TextField); add(value2Label); add(value2TextField); add(value3Label); add(value3TextField); name = String.valueOf(getUniqueCardNumber()); incrementUniqueCardNumber(); } public int getValue1() { return value1; } public void setValue1(int value1) { this.value1 = value1; } public int getValue2() { return value2; } public void setValue2(int value2) { this.value2 = value2; } public int getValue3() { return value2; } public void setValue3(int value3) { this.value3 = value3; } public void setAll(){ setValue1(Integer.parseInt(value1TextField.getText())); setValue2(Integer.parseInt(value2TextField.getText())); setValue3(Integer.parseInt(value3TextField.getText())); } public String getFunction(){ return "Function1("+value1+","+value2+","+value3+")"; } public String getName(){ return name; } public String toString(){ return "Function1"; } } //Function 1 /* * Function 2 */ public class Function2 extends JPanel implements Function{ int value1; JTextField value1TextField; private String name; public Function2(int value1) { this.value1 = value1; setLayout(new GridLayout(3,2)); JLabel value1Label = new JLabel("Value1"); value1TextField = new JTextField(Integer.toString(value1)); add(value1Label); add(value1TextField); name = String.valueOf(getUniqueCardNumber()); incrementUniqueCardNumber(); } public int getValue1() { return value1; } public void setValue1(int value1) { this.value1 = value1; } public void setAll(){ setValue1(Integer.parseInt(value1TextField.getText())); } public String getFunction(){ return "Function2("+value1+")"; } public String getName(){ return name; } public String toString(){ return "Function2"; } } //End Function 2 /* * Function 3 */ public class Function3 extends JPanel implements Function{ int value1, value2; JTextField value1TextField, value2TextField; private String name; public Function3(int value1, int value2){ this.value1 = value1; this.value2 = value2; setLayout(new GridLayout(3,2)); JLabel value1Label = new JLabel("Value1"); JLabel value2Label = new JLabel("Value2"); value1TextField = new JTextField(Integer.toString(value1)); value2TextField = new JTextField(Integer.toString(value2)); add(value1Label); add(value1TextField); add(value2Label); add(value2TextField); name = String.valueOf(getUniqueCardNumber()); incrementUniqueCardNumber(); } public int getValue1() { return value1; } public void setValue1(int value1) { this.value1 = value1; } public int getValue2() { return value2; } public void setValue2(int value2) { this.value2 = value2; } public void setAll(){ setValue1(Integer.parseInt(value1TextField.getText())); setValue2(Integer.parseInt(value2TextField.getText())); } public String getFunction(){ return "Function3("+value1+", "+value2+")"; } public String getName(){ return name; } public String toString(){ return "Function3"; } }//End Function3 public class DefaultGUI extends JPanel{ public DefaultGUI() { JLabel label = new JLabel("Default interface"); add(label); } public String toString(){ return "DefaultGUI"; } } //End DefaultGUI }//End class interface Function{ public String getFunction(); public void setAll(); public String getName(); }
- 09-12-2011, 11:01 AM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,460
- Rep Power
- 16
Re: Need help creating new instances dynamically. Compilable code inside.
Using code tags is a bit pointless if your code isn't formatted to begin with...
- 09-12-2011, 11:17 AM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,399
- Blog Entries
- 7
- Rep Power
- 17
Re: Need help creating new instances dynamically. Compilable code inside.
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 09-12-2011, 12:06 PM #4
Member
- Join Date
- Jun 2011
- Posts
- 11
- Rep Power
- 0
- 09-12-2011, 12:51 PM #5
Member
- Join Date
- Jun 2011
- Posts
- 11
- Rep Power
- 0
Re: Need help creating new instances dynamically. Compilable code inside.
Thanks for the response. Well, the lack of separation between 'view' and 'controller' (I'm assuming you're referring to the MVC-pattern) can be blamed on my inexperience with Java in general, and the lack of practise with separating code in a logical well functioning structure. I'm basically throwing things together at this point, as I'm sure you notice. I must admit that I haven't really gotten to grips with the MVC way of doing things.
If there are any specific places you could point out that needs restructuring, that would be helpful, although I know it's quite a bit of (terrible) code.
I'll try to produce a small example text-wise. If this is not sufficient let me know, and I'll make further effort to refine the code to show the essential problem.
The GUI has three panels: functionList, cards and usedFunctionList.
What I would like the program to do, is to add and display the function clicked in the functionList to the usedFunctionList. Also the parameters of the function should be editable in the central cards JPanel when clicked in the usedFunctionList.
My main problem is that my current implementation requires me to compare if the strings with function-names (Function1, Function2 etc) are equal to "Function1" and "Function2" in the mouseReleased() method. This is cumbersome.
Also I'm required to check the class of the object that's returned by usedFunctionsListModel.getElementAt(usedFunctionsL ist.getSelectedIndex()) (the one that's currently selected in usedFunctionsList) to be able to display the parameter card for each function. This is also cumbersome.
What I think I would like, is to add Function-objects directly to the functionList, and that when one of them is clicked, I could just use the same piece of code to add any of them to the usedFunctionList. The problem is, that even if there were objects (not just strings, like now) that were clicked in functionList, functionListModel.getElementAt(functionList.getSel ectedIndex()), which is used to get the element that was selected, just returns Object, so I would still have to do individual comparing. Is there any way to remedy this?
I know that an Object can use reflection to find out what its class is, so ideally I could then just write usedFunctionsListModel.addElement(element.newInsta nce()), and every function in functionList would be added to the usedFunctioList by the same piece of code. I haven't succeeded in making this work, nor do I know if it's a preferred solution.
The problem also goes for displaying the parameter-card when the selection in usedFunctionList is changed.
I hope this gave you some idea about what I want to do. I can easily understand the the code is not optimal in any sence. I'm just stumbling my way forward, learning as I go I guess. Let me know if you need any more information, I can understand if I haven't made myself quite clear as well.
- 09-12-2011, 01:09 PM #6
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,399
- Blog Entries
- 7
- Rep Power
- 17
Re: Need help creating new instances dynamically. Compilable code inside.
A JList doesn't care what type of objects you store in it, so why not store your own type of objects in it? Its toString() method should produce something sensible but for the rest you're free to do what you want. So why not define a 'FunctionHolder'? Something like this:
Wrap your Function objects in FunctionHolder objects and store those FunctionHolder objects in your JList. When you fetch an Object from the JList you know that it actually is a FunctionHolder so you can cast it to such a type and fetch its Function from it.Java Code:public class FunctionHolder { private Function function; // the Function this object holds // ctor public FunctionHolder(Function function) { this.function= function; } public Function getFunction() { return function; } // whatever the String form of a Function is: public String toString() { return function.toString(); } }
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 09-12-2011, 02:27 PM #7
Member
- Join Date
- Jun 2011
- Posts
- 11
- Rep Power
- 0
Re: Need help creating new instances dynamically. Compilable code inside.
Thanks for the advise. This sounds like the way I would like to go. But wouldn't I have to further cast the object into its original class to get access to all its methods and such?
Is it a better solution to skip extending JPanel, and rather extend a generic Function class, where I keep all common methods in one place, and where I could use your approach of casting to this known superclass? (Still not sure why I wouldn't have to explicitly cast it to its specific class). Not sure how I could lay it out then though, but I definitely agree that the GUI-part and functionality part are too entangled...
Similar Threads
-
creating an object inside jsp using el/jstl
By niteangell21 in forum JavaServer Pages (JSP) and JSTLReplies: 1Last Post: 11-30-2010, 05:26 PM -
Creating Jbuttons, etc. dynamically
By JohnST in forum New To JavaReplies: 2Last Post: 01-30-2010, 04:08 PM -
Creating new instances of a Match over and over again
By Che_Is_Alive in forum Advanced JavaReplies: 2Last Post: 11-19-2009, 06:05 PM -
Creating File inside a Directory
By viswanadh7 in forum AWT / SwingReplies: 1Last Post: 03-17-2009, 02:22 AM -
Object Reflection: Creating new instances
By Java Tip in forum java.langReplies: 0Last Post: 04-23-2008, 08:13 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks