Aspects are great way to to remove redundant code. I started tinkering with another aspect over the holiday because I was getting very tired of having manually style multiple JLabels with the same code over an over again. So instead of having to do something like this:
Font customFont = new Font("verdana",Font.BOLD,10); Color mediumGray = new Color(172,172,172); JLabel name1 = new JLabel("Name 1"); JLabel name2 = new JLabel("Name 2"); name1.setFont(font); name1.setForeground(meduimGray); name2.setFont(font); name2.setForeground(meduimGray);
You could do something like this:
@Style(name="mediumGray") JLabel name1 = new JLabel("Name 1"); @Style(name="mediumGray") JLabel name2 = new JLabel("Name 2");
This ensures that the lables get styled with the same style when the lable values are set. This also ensures consistency accorss multiple forms too. While not the best example in ther world, I think it does get the point accros. There’s stil a lot more thought that needs to go into it such as:
- What type of format do you externalize the Styles? I’m not convinced CSS will work well with Swing.
- Loading and configuration of the externalized style definitions needs to be figured out
- Expand this far beyond JLabels
- The aspect depends on the JComonents to be a field of another class, they can’t be local variables
- See if AspectJ is better than JBoss AOP🙂
I’ll be tweaking the code a bit more over the winter holidays and it will all become available in new Open Source project on Java.net. If you have any suggestions on the Style Aspect, please leave a comment or two!