JPanel which uses reflection to create a simple property editor

Hi everyone,
Here's what I'd like: a custom JPanel, let's call it DesiredJPanel, which can be passed an object as an argument, and which then detects all the public getters and setters on that object, and then creates a simple property editor, with default behavior for numbers, booleans, Strings, etc. It might be used like this:
JDialog dialog = new JDialog(new DesiredJPanel(someObjectWithSettersAndGetters)));
dialog.setVisible(true);
Then we'd get a dialog populated with the current values of all relevant properties. The panel could have a button bar, with an ok button. When you press it, all the properties of someObjectWithSettersAndGetters are set according to what the user has entered in the fields of the panel.
This seems like a pervasive, standard use case. It also seems like javabeans is intended for this. E.g. quoting wikipedia: "JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool." Moreover, there is the java.beans.PropertyEditor interface.
And yet I can't find anything that seems to do this, so I end up writing the same boilerplate style code over and over. I found some commercial thing (this is for an open source project), and netbeans does what I'm after but it's netbeans. I want something that can be used in any swing app.
Apologies if I've overlooked something obvious or posted this to the wrong forum (if either, please let me know!).
All best and happy new year!
- Jeff

Not exactly what you asked for, but reasonably close. You can use my [Bean Table Model|http://www.camick.com/java/blog.html?name=bean-table-model] to create a JTable which will display all the properties in a single row of a table. The appropriate renderer/editor is used for each property.
Play with the commented out code in JButtonTableModel class to see what you get for your particular bean.

Similar Messages

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

  • Using LabVIEW to create a simple datalogger.

    Hello,
    Can someone show me how to create a simple data logger.
    Here's an example, Using a for loop can I keep track of the loop number in an array?
    In the first loop ,first array would have 1, in the second loop,second array would have 1,2. And in the last loop array N, would have 1,2,3...N.
    First loop =>      1
    Second loop => 1 2
    Third Loop =>    1 2 3
    N loop =>           1 2  3 4 . . . N.
    Thanks

    Building arrays are pretty simple. If you want the array outside the for loop, you just have to wire iteration terminal to the edge of the the for loop. The auto-indexing feature of a for loop will automatically create the array. If you need the array inside the for loop, you can use the build array function and a shift register.
    Attachments:
    Build Array.JPG ‏7 KB

  • Using reflection to create a JTree representing an object

    I�m trying to implement a Java component which represents an Object tree.
    the idea is to receive a generic Object and then to create a JTree with all attributes of this object... If an attribute is a list or other complex object, than my component include subnodes into the tree with the contents of this collections, etc.
    my current first steps:
    private DefaultMutableTreeNode setAttributesTree(Object obj) {
         DefaultMutableTreeNode root = new DefaultMutableTreeNode(obj.toString());
         Class userObjectClass =obj.getClass();
         Field[] fields = userObjectClass.getDeclaredFields();
         for(int i=0; i<fields.length; i++) {
              try {
                   fields.setAccessible(true);
                   root.add(new DefaultMutableTreeNode(fields[i].getName() + " = " + fields[i].get(obj)));
              } catch (Exception e) {
                   System.out.println("some bug");

    interesting approach.. I wiil try that... bellow is my current code, which runs well to the first level of attributes.. When I tryied to load the deeper levels, it caused a StackOverflow... I will try the cited approach...
    /** 2003 � www.atlantico.com.br */
    package com.atlantico.sigweb.util;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.lang.reflect.Field;
    import java.util.Collection;
    import java.util.Iterator;
    * Esta classe re�ne funcionalidades que n�o est�o vinculadas
    * a um processo espec�fico.
    * @author Felipe Ga�cho
    * @version 15/09/2003
    public abstract class Util {
         * M�todo que recebe um objeto qualquer e retorna a ra�z
         * da �rvore de atributos deste objeto. Este m�todo usa
         * reflection para inspecionar o objeto recebido.
         * @param object O objeto a partir do qual a �rvore de
         * atributos ser� constru�da.
         * @return A �rvore de atributos.
         * @throws IllegalArgumentException
         * @throws IllegalAccessException
        public static DefaultMutableTreeNode inspect(Object object)
            throws IllegalArgumentException, IllegalAccessException {
            if (object == null) {
                return null;
            DefaultMutableTreeNode root =
                new DefaultMutableTreeNode(object.toString());
            Class userObjectClass = object.getClass();
            Field[] fields = userObjectClass.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                fields.setAccessible(true);
    Object field = fields[i].get(object);
    DefaultMutableTreeNode child =
    new DefaultMutableTreeNode(fields[i].getName());
    inspect(child, fields[i]);
    ((DefaultMutableTreeNode) root).add(child);
    return root;
    public static void inspect(DefaultMutableTreeNode root, Object object)
    throws IllegalArgumentException, IllegalAccessException {
    if (object instanceof Collection) {
    for (
    Iterator children = ((Collection) object).iterator();
    children.hasNext();
    Object next = children.next();
    DefaultMutableTreeNode nextNode =
    new DefaultMutableTreeNode(next);
    inspect(nextNode, next);
    root.add(nextNode);
    } else {
    Class objectClass = object.getClass();
    Field[] fields = objectClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
    fields[i].setAccessible(true);
    Object field = fields[i].get(object);
    root.add(
    new DefaultMutableTreeNode(
    fields[i].getName() + " = " + fields[i].get(object)
    private static DefaultMutableTreeNode inspectR(Object object)
    throws IllegalArgumentException, IllegalAccessException {
    DefaultMutableTreeNode node =
    new DefaultMutableTreeNode(object.toString());
    Class objectClass = object.getClass();
    Field[] fields = objectClass.getDeclaredFields();
    if (fields.length > 0) {
    for (int i = 0; i < fields.length; i++) {
    fields[i].setAccessible(true);
    Object field = fields[i].get(object);
    node.add(inspectR(field));
    return node;

  • Problem during dynamic casting (using reflection)

    Hi Guys,
    Need you help
    Situation is like this �.I have a function which accept the Sting parameter
    Which is actually a full name of class �.using reflection I created the class and object
    Now I want to cast this newly created object to their original class type
    Code is somehow like this
    Public void checkThis (String name) throws Exception{
    Class c = Class.forName(name.trim());
    Object o = c.newInstance();     
    System.out.println(" class name = " + c.getName());
    throw ()o; //// here I want to cast this object to their orginal class type
    I tried throw (c.getName())o;
    But it is not working
    }

    You can't cast to an unknown type like that. You're trying to throw the object, which makes me believe you're loading and instantiating some Exception or other, right? Just cast the result to something generic, like Exception, or RuntimeException, or maybe Throwable. As long as the class you load actually is a subclass of whichever you choose, you'll be fine. And if it isn't, you've got problems anyway because you can't throw anything that isn't Throwable

  • Working around unchecked conversions when using reflection

    I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
    Suppose I've got a method that uses reflection to compare an arbitrary property in
    an arbitrary pair of beans (of the same class).
    public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
         Method m = bean0.getClass().getMethod(
                   "get" + prop.substring(0,1).toUpperCase() +
                   prop.substring(1));
         Object o0 = m.invoke(bean0);
         Object o1 = m.invoke(bean1);
         if (o0 instanceof Comparable &&
             o1 instanceof Comparable &&
             (o1.getClass().isAssignableFrom(o0.getClass()) ||
              o0.getClass().isAssignableFrom(o1.getClass()))) {
              return ((Comparable)o0).compareTo(o1); // compiler warning
         } else {
              return o0.toString().compareTo(o1.toString());
    }There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?

    Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
    Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
    Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API)

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

  • Create the simple browser which is based on JEditorPane

    hi all!
    please help me!
    I want create the simple browser which is based on JEditorPane, but when i insert hyperlink into "my.jar", in my html page, and when i click on it, i get text only. How can i rewrite HyperLinkListener to run my program after clicking on the link?
    thanks!

    it's not that simple :)
    If you're just given a jar and no class to run, you need to save the jar in a known location and use Runtime.exec() to do java -jar "myjar.jar"
    otherwise, if you have a main class defined, you can use URLClassLoader to load the jar. Once you've done that you can run the applet / exe

  • Any tutorials on creating a simple Login using Mysql and sessions?

    Hey guys. I cannot seem to find any information(online) or books that cover sessions in JSF and how to do a simple log in. I can get the application to query a mysql table and check the credentials and go to the next page, but I'm not sure how to make that page locked from non authorized access. I am very familiar with PHP and using it to create database driven applications. It's very straightforward, making safe logins using mysql, and creating sessions once the user has logged in(making pages locked unless the user is logged in, etc).. I have the core java server faces book but it's a joke. I feel like its an incomplete book. It merely skims a topic, and when you think it's going to get interesting it moves on to something else. It teaches basic stuff but nothing of what I want to do(or need to do). The older Javaserver faces book that came out in 2004 from O'Reilly doesn't seem to help either. I'm just wondering where people learn JSF at. I know Java, I would say pretty well as far as desktop applications go. I really like the way JSF is layed out and would really like to use it in my next project. At the level I know it now it's perfect for static web pages with no dynamic information.(but I could use plain html for that). Thanks for all your help.

    dothedru22 wrote:
    but I'm not sure how to make that page locked from non authorized access.You can use a Filter for that. Map the filter on the desired url-pattern and write doFilter() logic which checks if the user is logged in (basically: if there is an User object in the HttpSession) and handle accordingly (chain.doFilter() on success or response.sendRedirect on fail).
    and creating sessions once the user has logged in(making pages locked unless the user is logged in, etc).. The HttpSession is backed by a cookie (as is PHP's $_SESSION, did you know that?), you don't need to do any low-level stuff with cookies. Maybe at highest if you ever want a "remember me on this computer" option.
    booksThe mentioned books learns you the JSF basics. They doesn't really learn the best practices / practical use cases. There you have other resources for (or just practical experiences). Besides, I recommend you to go get a book which covers JSF 1.2 or newer. The mentioned ones are outdated, as is everything else older dan two years in the programming world.

  • I can't open my imovie '9 projects on my new lap top which uses imovie 11'.. previous lap top was mac book osx 10.5.8.. new one is mac book pro 10.6.6.. any help out there! i'm pretty useless at this stuff, might be really simple???

    which uses imovie 11'.. previous lap top was mac book osx 10.5.8.. new one is mac book pro 10.6.6.. any help out there! i'm pretty useless at this stuff, might be really simple???

    Thanks for nothing, as usual, Apple.
    I had to redo the whole project from scratch on Windows Movie Maker.
    Now I know which brand to trust on my next purchase.

  • I am trying to create a simple animated gif in Photoshop. I've set up my frames and want to use the tween to make the transitions less jerky. When I tween between frame 1 and frame 2 the object in frame two goes out of position, appearing in a different p

    I am trying to create a simple animated gif in Photoshop. I've set up my frames and want to use the tween to make the transitions less jerky. When I tween between frame 1 and frame 2 the object in frame two goes out of position, appearing in a different place than where it is on frame 2. Confused!

    Hi Melissa - thanks for your interest. Here's the first frame, the second frame and the tween frame. I don't understand why the tween is changing the position of the object in frame 2, was expecting it to just fade from one frame to the next.

  • How do I use the same Icloud address on my Ipad and Iphone ? I went to put my icloud address on my Iphone, but ttells me it is already being used and to create another one, which I dont want to do

    I have just bought an Iphone 4s to compliment my Ipad Air, I want to use my Icloud address on both machines but cant get my iphone to accept my icloud address, it tells me it is already in use and to create a new one, which is not what I want.. How do I get the same email on both devices?

    it tells me it is already in use
    You will need to contact the previous owner of the iPhone in order to change the Apple ID.

  • How can I re-arrange the pages in a Pages document now?? I used to be able to click on the thumbnails and shift their position which is important in creating documents.  Any ideas?

    How can I re-arrange the pages in a Pages document now?? I used to be able to click on the thumbnails and shift their position which is important in creating documents.  Any ideas?

    This feature has been removed from Pages 5 along with over 90 others:
    http://www.freeforum101.com/iworktipsntrick/viewforum.php?f=22&mforum=iworktipsn trick
    Pages '09 is still in your Applications/iWork folder.
    Trash/archive Pages 5 and rate/review it in the App Store.
    Peter

  • How to create a simple app using the MVC approach?

    Hello gurus i'm trying to learn the SAPUI5 and i'm trying to create a simple app using the MVC i created the app and trying to add a lable to the view but there is nothing appear when i run it the code for the HTML page
    <!DOCTYPE HTML>
    <html>
      <head>
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
      <script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
      id="sap-ui-bootstrap"
      data-sap-ui-libs="sap.m"
      data-sap-ui-theme="sap_bluecrystal">
      </script>
      <!-- only load the mobile lib "sap.m" and the "sap_mvi" theme -->
      <script>
      sap.ui.localResources("mytestapp");
      var view = sap.ui.view({id:"idshell1", viewName:"mytestapp.shell", type:sap.ui.core.mvc.ViewType.JS});
      view.placeAt("content");
      </script>
      </head>
      <body class="sapUiBody" role="application">
      <div id="content"></div>
      </body>
    </html>
    the code for the view
    sap.ui.jsview("mytestapp.shell", {
      /** Specifies the Controller belonging to this View.
      * In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
      * @memberOf mytestapp.shell
      getControllerName : function() {
      return "mytestapp.shell";
      /** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.
      * Since the Controller is given to this method, its event handlers can be attached right away.
      * @memberOf mytestapp.shell
      createContent : function(oController) {
      var oLabel = new sap.ui.commons.Label("l1");
      oLabel.setText("Test label");
      oLabel.placeAt("content");
    i dont know what is wrong or if i should use a container to display my controls
    any help will be appreciated
    thanks in advance

    Hi,
    Instead of   oLabel.placeAt("content"); use return oLabel;
    so it will as below,
    createContent : function(oController) {
      var oLabel = new sap.ui.commons.Label("l1");
      oLabel.setText("Test label");
      return oLable;
    Regards,
    Chandra

  • Problem Creating Project (Flash Builder 4) which uses LiveCycle DS

    I have a web app which uses LiveCycle DS 2.6.1, however, when I try to create a new flex project I am getting this error:
    Only LiveCycle Data Services 2.6 and higher are supported.
    Here are the steps in Flash Builder 4
    1. File -> New -> Flex Project
    2. Set project name
    3. Point folder to existing source code
    4. Change "Application server type" to "J2EE"
    5. Check the "Use remote object acces service"
    6. Select "LiveCycle Data Services ES" radio button
    7. Click next
    8. Un-check "Use default location for local LiveCycle Data Services server
    9. Set "Root Folder" to "C:\tomcat\webapps\myapp"
       -- in myapp, I have WEB-INF\flex of course
    10. Set root URL and context root
    11. Click "Validate Configuration"
    This gives me the error: "Only LiveCycle Data Services 2.6 and higher are supported."
    Any ideas?  How is Flash Builder determining the version of LiveCycle?

    Hi Jeremy,
    I tried the steps you mentioned and cannot reproduce the problem. You mentioned you are pointing your project location to existing source code. Was there a previous FB project at that location? Was that project using an older version of LCDS before? If you create a new project and point it to a new emoty project location folder (or use default workspace location), do you still see the problem? Any more information you can give me to help reproduce the problem would help.
    thanks!
    -george

Maybe you are looking for

  • IPod Touch newbie questions - pt. III

    Last questions: 1) I downloaded a few apps from the Apps Store and noticed that a few would not load. They kept cycling and cycling and never completed. I then realized that I had to connect to a Wi FI network, which I am lucky enough to have at home

  • To transfer data from one db table to anotherdb's table

    I have to transfer data from one db table A to another db table B. Both the tables have data which is common. I want to transfer data from table A to table B. Data transfer needed is only the excess data in table A

  • Can i import photos from my wifi enabled camera to iphoto over wifi?

    I am looking to buy a new digital camera and want to get want with wifi if I can upload the photos to iPhoto without cables.

  • Phone won't show contact name in recents list

    Phone won't show contact name while somebody call me, the same is in recent list under number is unknown. I already reset my phone and try to make new contact when somebody called me and it isn't work. 

  • Hyperion EPM 9.x

    Can anyone give me details regarding the feasilibilty issues and performance of migrating from a 7.x system to a 9.x system Thanks