Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts

Monday, 4 June 2012

JScrollPane Repainting Problems

I was having some problems with the JScrollPane not repainting my custom component properly when scrolling.  The results were that the area that was now visible because of the scroll was painted unevenly and looked blurred.  This seems to happen when a component is doing some custom rendering inside a JScrollPane and using the clip to find out what area it should paint.  To fix this call the following methods on your JScrollPane:

scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);

In the modern swing implementation there is some 'clever' caching of the content view to improve performance which seems to be the problem.  Setting SIMPLE_SCROLL_MODE will force the scroll pane to repaint it's entire contents while scrolling.  Although this is less performant, it at least shows the correct results with minimum fuss.

Sunday, 26 February 2012

Compatible Images

A couple of weeks ago I was tasked with improving the performance on a legacy java swing application that was really crawling.  It would repaint the whole screen on any event, which it could receive a lot of, and painting the whole screen was really slow.  By using compatible images instead of the default kind of image read by ImageIO, the painting code was sped up by a factor of 70 and the event frequency was a non-issue.  The whole change was about 10 lines of code, much less than that to make the software use the graphics clip.

If you are having an issue with graphics performance make sure you try compatible images before trying anything else since it is so easy to introduce.

Before deploying to site I was worried that the speed up I was seeing was in some way down to my dev machine working well with compatible images so I wrote the tool below to test if the improvement was the same which it was.  Some notes:
  1. The tool requires an image.  When I attempted to create an in-memory image there was no difference in run times.
  2. Results are printed on the command line so remember to use java.exe and not javaw.exe
  3. I went to some effort so that this program was a single class to make it easy for the support guys to run.  I don't usually like to implement Runnable on a class that isn't just a Runnable.

Thursday, 29 April 2010

Miglayout DSL

Here's an embryonic DSL for MigLayout in Java.  Statically imported enums turn out to be a pretty handy alternative to Smalltalk or Erlang atoms.  Unfortunately I can't find the HTML syntax highlighter for Java.


import static MigBuilder.*;

Object mig = mig(size(BUTTON_WIDTH, BUTTON_HEIGHT), gapleft(LEFT_GAP), hidemode(zero), growx, growy);
        
String migconstraint = "w 11!, h 52!, gapleft 3, growx, growy";

enum MigBuilder {
  grow, growx, growy, push, gapleft;
 
  public static Object mig(Object...strings)
  {
    StringBuilder builder = new StringBuilder();
    for (Object object : strings)
    {
      if(object instanceof MigBuilder)
        builder.append(',');
     
      builder.append(String.valueOf(object));
    }
    return builder.toString();     
  }
 
  public static Object size(int width, int height)
  {
    return mig("w ", width, "!,h ", height, '!');
  }
 
  public static Object gapleft(int pixels)
  {
    return mig(gapleft, pixels);
  }
 
  public static Object hidemode(HideMode hidemode)
  {
    return mig("hidemode ", hidemode);
  }
}

Tuesday, 19 January 2010

Implementing Application UI in XML

I just noticed the new release of Pivot on DZone, and the whole idea just leaves me confused.  Why would anyone want to do complex coding in XML?

Java isn't the best for the kind of declarative style that you need when coding components that need a lot of information to be passed in such as colours and fonts.  The rows of sets really become ugly but at least you can have named constants for things like points and rectangles which is really difficult in XML.  Ant is a good example of that, properties soon become complex which doesn't happen in a Java project.

I don't think JavaFx is the answer either, it's just as confusing.  It's a high level language without an advertised purpose.  Yes it can do nice graphics easily but this must account for a single figure percentage (if that) of the total amount of software currently being developed.  If it hasn't been made to scale up to more complex tasks then whats the point of it?  Thats more of an advertising blunder than a language problem since it has all of the features that I would expect of a non-innovative modern language.  Maybe it's just not for me, it's created for designers and I'm not the target market.  Concurrency features are a hard sell to hasn't seen their UI mysteriously lock up.  Overall I'm just not impressed enough to make the switch when I could spend my time learning much more interesting tech.

The Groovy builders are impressive but aren't so much greater than Java to make the massive leap of incorporating a new language into your system. 


Back to Java, what does it really need to catch up in productivity to the main players?
  • Closures,  this would just be really nice to have.  Anonymous classes achieve the same thing but Swing would look so much nicer with closures.
  • String interpolation and multiline string, so simple and so useful.  Over Christmas I read up on Ruby, the language is a good manual on how to make our lives easier for day to day tasks.
  • Clear up the cruddy Swing API, an average custom component has a multitude of inherited methods.  Just think how many different size properties there are, do you know which layout managers rely on which properties?  This can be improved.
  • Inbuilt listener framework, the property change listener framework is really underpowered.  The default framework for property listeners should have weak listeners, annotated methods that can generate handlers and threading strategies as standard.  Think EventBus or something similiar.
  • Configurable style, style should really be configurable and maybe even injectable as in Fuse.  The Swing Application Framework has this as well.
Using frameworks like Guice and MigLayout really improve design and coding as well and should be more standard in Java desktop development.

Thursday, 7 January 2010

UI Code Don'ts

It's important to keep code quality in check constantly in UI classes probably more than others as it typically seems to get out of hand more quickly.  Here are some observations, they hopefully do not fall into the micro-optimisation category but I definitely feel they are bad to have around.

  • Images or other memory hungry objects/resources marked with static.  These objects will never be garbage collected even if they are never used.  A shared object should store these images short term or SoftReferences should be used to store the images for a greater time without the danger of memory leaks.
  • Style information spread out across the whole program.  Especially Font objects, this seems to be the first thing to change and if it is spread out across the whole project then its going to be a mess.
  • Creating new Color objects in setters.  This causes a couple of problems, you're creating new Color objects all over the place which is only a minor problem but still pointless.  The other problem is understandability, it's hard to see what that colour is from the RGB constructor.
  • Magic numbers.  Not much need to explain why this is bad, please name them.  If there are too many then create a separate class to house them, you can even use a static import to keep code readable.
  • Too many anonymous classes.  Anonymous classes are useful buf too many look ugly (I don't like the syntax noise) and can cause memory leaks as the reference isn't explicit.
  • SwingTimer.  Please no!  Even if you know the memory leak pitfall, it's still too easy to fall into it.  Just avoid.

    This is just a short list off the top of my head, I'll update it if I think of anymore.

    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 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);
    }
    }


    Saturday, 21 June 2008

    JPopupMenu and ActionEvent's getSource( ) Method

    When handling an event from a Java Swing component you would most likely implement the ActionListener interface and be able to get the source of the event from the ActionEvent's getSource() property. Not so if the event was triggered by a JPopupMenu. The type of the source of an ActionEvent is actually JPopupMenu$1 which seems to be a private inner class of JPopupMenu. The hack round this is pretty simple but not obvious because JPopupmenu$1 isn't documented anywhere.

    JPopupMenu$1 extends Component and its parent is the JPopupMenu that you wanted in the first place so all you have to do is cast it and call getParent().