Recently I have been working on a project that as normal uses Swing but decided to use Guice to avoid some of the problems that I’ve encountered in previous projects.
The problem is that if you have components that rely on service type interfaces that are nested several layers deep (not that unlikely in a complex UI) then to pass the service to the component all the other components above it need to have methods/constructors that pass the service down the hierarchy. This culminates in a simple change to a component that needs a reference to a new service requiring changes to 4/5 classes that also now have references to something they didn’t need to know about. This means extra coupling and more pain when you’re trying to refactor.
So now there are panels which have references to components that are themselves injected, which have injected services and everything works. It just works. In fact I barely think about it anymore, components with dependencies are just injected and there are no problems, no extra dependencies and no extra work. If the injected components also need service dependant components then they are injected as well and have no impact up the hierarchy.
Many classes in the project now have no code depending on the way they are created, which is a real joy. I haven’t heard this benefit touted by IoC propaganda but it really should be. If you ever wondered if adding dependency injection was overkill for you project, note down what you would inject. If there is more than two (my own measurement) injectable classes then the gains will be more than the cost of complexity in setting up the IoC infrastructure with modules and injectors etc.
Wednesday, 21 October 2009
Friday, 22 May 2009
DMA
I've had a frustrating day wrestling with my sound recording setup. The Mircotrack 2 that I'm using seems to have toasted one of my compact flash cards, now it crashes Windows Explorer!
The problem was fixed by turning off DMA on the Microtrack recorder and now it's recording properly again. DMA is a mechanism for circumventing the CPU, while writing to memory on a different device.
Thanks to Mr Sandiford for figuring this out :)
Wednesday, 4 March 2009
Referencing Enclosing Instance of an Inner Class
When using an inner class how do you reference the enclosing class? The answer is
Object.this where Object is the class type of the enclosing class. Sweet :)
Sunday, 11 January 2009
Setting a custom cursor which doesn't get resized
When setting a custom cursor in Swing you shouldn't really rely on the
To me this seems pretty crap because the image is going to get resized at some point depending on the platform your app is being run on which will most likely make the cursor image look terrible, perhaps to the user, unusable. IMO the behaviour should be to create a new image of the dimensions of
Implementation is below...
createCustomCursor method to use your images in any respectful way. The behaviour of this method is to resize the image into the dimensions returned by the getBestCursorSize method, which on Windows XP always seems to return 32x32 pixels.To me this seems pretty crap because the image is going to get resized at some point depending on the platform your app is being run on which will most likely make the cursor image look terrible, perhaps to the user, unusable. IMO the behaviour should be to create a new image of the dimensions of
getBestCursorSize and draw the supplied image at point 0,0. This does cause a problem if your image is larger than the dimension but your would be screwed the default way anyway.Implementation is below...
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
public class SizedCursor
{
public static Image getPreferredSizedCursor(
Image image)
{
Dimension bestDimension = Toolkit
.getDefaultToolkit()
.getBestCursorSize(
image
.getWidth(null),
image
.getHeight(null));
if (bestDimensionsEqualsImageSize(
image,
bestDimension))
{
return image;
}
else
{
BufferedImage resizedImage = new BufferedImage(
bestDimension.width,
bestDimension.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) resizedImage
.getGraphics();
g.drawImage(
image, 0,
0, null);
return resizedImage;
}
}
private static boolean bestDimensionsEqualsImageSize(
Image image,
Dimension bestDimension)
{
return bestDimension
.getWidth() == image
.getWidth(null)
&& bestDimension
.getHeight() == image
.getHeight(null);
}
}
Tuesday, 16 December 2008
Java Garbage Collection for String literals
Tonight I had a ponder about Javas garbage collection mechanism and what would make an object held by a WeakReference be garbage collected. The answer was quite simple, create a instance of a variable, create a WeakReference for it, null the instance and call System.gc(). I'm guessing that the instance would be garbage collected on the next natural sweep but because I was using a unit test I needed it to be done straight away.
However, garbage collection on string literals is far more interesting. See the unit tests.
All of these tests pass. Notice the last test, even after the string instance has been nulled the WeakReference still has a not null value. After a bit of googling I found that string literals are referenced from Javas 'String Literal Pool' which is a cache for string literals so is not eligible for garbage collection!
However, garbage collection on string literals is far more interesting. See the unit tests.
import static org.junit.Assert.*;
import java.lang.ref.WeakReference;
import org.junit.Test;
public class ReferenceTest
{
@Test
public void testWeakReference()
{
Object reference = new Object();
WeakReference<Object> weakRef =
new WeakReference<Object>(reference);
assertNotNull(reference);
reference = null;
// reference will not be null
// without garbage collection here
System.gc();
assertNull(weakRef.get());
}
@Test
public void testWeakStringReference()
{
String reference = new String();
WeakReference<String> weakRef =
new WeakReference<String>(reference);
assertNotNull(reference);
reference = null;
// reference will not be null
// without garbage collection here
System.gc();
assertNull(weakRef.get());
}
@Test
public void testWeakStringLiteralReference()
{
String reference = "my reference";
WeakReference<String> weakRef =
new WeakReference<String>(reference);
assertNotNull(reference);
reference = null;
// does not matter if garbage collection
// is here or not but lets do it anyway
System.gc();
// !!!
assertNotNull(weakRef.get());
}
}
All of these tests pass. Notice the last test, even after the string instance has been nulled the WeakReference still has a not null value. After a bit of googling I found that string literals are referenced from Javas 'String Literal Pool' which is a cache for string literals so is not eligible for garbage collection!
Saturday, 11 October 2008
Turn off no serialVersionUID warnings in eclipse
A bit of madness that I've always asscoiated with eclipse is that it shows a warning if a Java class does not have a serialisable UID, for example, something like the following...
If I see this then I know its been written using eclipse, to turn it off go to the project's properties. In the tree follow Java Compiler->Errors/Warnings. To configure this for all projects click on Configure Workspace Settings... In the list of categories choose Potential Programming Problems and the setting for serial UIDs is top of the list, here you can it to ignore.
public class MyTreeModel extends DefaultTreeModel
{
    private static final long serialVersionUID = 7522249943744455803L;
}
If I see this then I know its been written using eclipse, to turn it off go to the project's properties. In the tree follow Java Compiler->Errors/Warnings. To configure this for all projects click on Configure Workspace Settings... In the list of categories choose Potential Programming Problems and the setting for serial UIDs is top of the list, here you can it to ignore.
Tuesday, 23 September 2008
Decorating a Swing Action
I've got into the decorator pattern since reading Swing Hacks as a way to add some functionality to a class or even an interface (see the JTable sorting hack!) without changing it. I recently needed a way of adding functionality to Swing Actions that was specific to where they were used, this time disposing a JFrame but only when its used in that JFrame. The solution is to create a wrapper for the action that delegates all method calls to the wrapped action but has method hooks that that are called before and after the wrapped action's actionPerformed method is called which are overridable.
And an example usage is below...
Here myJFrame is an instantiated JFrame and action is your original action implementation, myJFrame will now be disposed once the action is triggered.
public class AbstractWrapperAction extends AbstractAction {
Action wrappedAction;
public AbstractWrapperAction(Action wrappedAction) {
this.wrappedAction = wrappedAction;
}
public void actionPerformed(ActionEvent e) {
preWrappedAction(e);
if(wrappedAction != null)
{
wrappedAction.actionPerformed(e);
}
postWrappedAction(e);
}
public void preWrappedAction(ActionEvent e) { }
public void postWrappedAction(ActionEvent e) { }
@Override
public void setEnabled(boolean b) {
wrappedAction.setEnabled(b);
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
wrappedAction.removePropertyChangeListener(listener);
}
@Override
public void putValue(String key, Object value) {
wrappedAction.putValue(key, value);
}
@Override
public boolean isEnabled() {
return wrappedAction.isEnabled();
}
@Override
public Object getValue(String key) {
return wrappedAction.getValue(key);
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
wrappedAction.addPropertyChangeListener(listener);
}
}
And an example usage is below...
Action wrapperAction = new AbstractWrapperAction(action) {
@Override public void postWrappedAction(ActionEvent e) {
((Window)getValue(FRAME_KEY)).dispose();
}
};
wrapperAction.putValue(FRAME_KEY, myJFrame);
Here myJFrame is an instantiated JFrame and action is your original action implementation, myJFrame will now be disposed once the action is triggered.
Subscribe to:
Posts (Atom)