Thursday, February 11, 2010

Bean reader JTable

I have already written about JTable on this blog, a lot can be written about it.
This time I will talk about a custom jtable I developed in order to have the simplest way to show READ ONLY data.

First how I was coding before:


class Person{
String firstName;
String lastName;
/*..*/
}

DefaultTableModel dtm= new DefaultTableModel();
for(Person p: getListPersons()){
Dtm.add(new Object[]{p.getFirstName(),p.getLastName()});
}

Dtm.addColumn(“firstName”);
Dtm.addColumn(“lastName”);

JTable table=new JTable();
table.setModel(dtm);


And to know which Object is currently selected:

Int index=table.getSelectedIndex();
Int modelIndex=table.convertRowIndexToModel(index);
Person selected=getListPersons.get(modelIndex);


After coding this way too many time I wondered:
As we only show only one kind of object in the table, wouldn’t it be easier:
to have a table of T
to be able to add/remove a T
to be able to get the selected T
All this without coding a custom JTable or/and TableModel each time


So the plan is to have an easy way to
-Define the class of objects to show using the JTable
-Define the columns
-Add/remove an object from the table
-Get the selected objects


So now let’s see the implementation I called BeanReaderJTable

First we need a generic parameter

public class BeanReaderJTable<T> extends JTable {/*…*/}


The contructor take the field names and the column names you want as header value.


public BeanReaderJTable(String[] fields, String[] title)


Adding/removing a row or getting the selected objects can’t be easier:

addRow(T)
addRow(T[])
addRow(Collection<T>)
removeRow(T)
getSelectedObject():T
getSelectedObjects():T[]



What is doing the actual job is the GenericTableModel.
The important job is done in getValueAt(int,int). The reflexion API is used to retrieve the value of a given pair field+row


Now let’s see a sample:


// declare the type + fields+column title
String[] fields = new String[] { "size", "size.width", "size.height", "class", "visible", null };
String[] titles = new String[] { "size", "width", "height", "class", "is visible", null };
BeanReaderJTable<Component> table = new BeanReaderJTable<Component>(fields, titles);
//populate the table
table.addRow(getAllComponents(frame));


You may have noticed, I left the last field empty, doing so, an empty column is created that can be used to set for example a button cell editor

And also what you can see, is that you can access nested field like size.width

This time you should actually be able to access the code source repository, my java.net project has been approved:
BeanReaderJTable





Sunday, February 7, 2010

Closing windows in style

This week some fun stuff!

In the post about dialog with drop shadow i mentioned the class WindowFadeInManager to open or close a window with a fadein / fadeout effect, but there is another way to close window in style.

First, don’t make me say what I didn’t, such close transitions should not be used on every windows in your app, if you do it will just annoy the user.
I usually use them to close loading/splash/main frame of an application.



The base class where all the main work is done is
CloseTransition , it’s an abstract class where the only abstract method is

protected abstract void paintImage(Graphics g,float animFraction);


This method is responsible of drawing the closing window for a given animation fraction (from 0 to 1)

The CloseTransition class take care of making a screenshot of the actual window that will get closed. Then it starts the close animation.

So what to do in this paintImage method?
One easy thing is to show that a window is closing via shapes. For example simply by making the window shrink.

This is done by extending the ShapeTransition class.
This class has one abstract method:

public abstract Shape getShape(float animFraction);



This method will get called to set the clip before painting the image of the closing window. There is also an option to automaticly shrink the image of the closing screen.
So to create a close transition, this method will have to return an empty shape when animFraction=1 and a shape that cover totally the original window when animFraction=0

By default in the ShapeTransition the original window is painted with an alpha value of 1-animfraction to make the window disappear smoothly, you can change this behaviour by setting the fadeout property to false.

In the repository you will find the following implementation of close transitions:
ShrinkTransition
CircleTransition
RectanglesTransition (the one I use in my apps)
FadeOutTransition
RotationTransition
PinchTransition, the funniest one, only work well on small window


To start a close transition you can follow this example:

myFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
myFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
RectanglesTransition transition = new RectanglesTransition(myFrame);
transition.startCloseTransition();
}
});

By default the action at the end of the transition is system.exit(0); because those close transitions are meant to be used to close main frame of an application but anyway you can set the end action:

transition.setEndAction(AbstractAction);












Friday, February 5, 2010

Moving to java.dev.net

As kenai is closing i am moving my code repository to https://free-the-pixel.dev.java.net


edit:
here is the mail i got a few hours after migrating to java.net :


In an effort to get information out to the Kenai community quickly, while trying to manage the integration of our two companies, I think we did a poor job at communicating our plans for Kenai.com to you. I would like to remedy that now. Our strategy is simple. We don't believe it makes sense to continue investing in multiple hosted development sites that are basically doing the same thing. Our plan is to shut down kenai.com and focus our efforts on java.net as the hosted development community. We are in the process of migrating java.net to the kenai technology. This means that any project currently hosted on kenai.com will be able to continue as you are on java.net. We are still working out the technical details, but the goal is to make this migration as seamless as possible for the current kenai.com projects. So in the meantime I suggest that you stay put on kenai.com and let us work through the details and get back to you later this month.

Thanks for your feedback and patience.

Ted Farrell
Oracle Corporation


that's great news,
well i did the manual migrating to java.net but i won't complain i didn t have so many stuff as i only started begining on this years.

Thursday, January 28, 2010

Table and actions.

If you have been developing client software you certainly already ran into the following situation:
You have a table full of data, each line corresponding to an object you can interact with. Where and how should I put buttons for this purpose?

I will explore several implementations in order to handle this situation.

Cell editors/renderers


This way is often seen to handle this situation, you have to add one column per action, and then the button will appear on each line thanks to a cell renderer/editor.
I don’t find it really appealing visually, because repeating the same button over and over again on each line seems wrong to me, but at least it’s easy to see that the action on the button will be applied to the selected row.
Adding columns + most likely increasing the row height (to display properly an icon) are a waste of space if you don’t have so much of it at first.

I know by experience that developers that do not understand swing correctly (well, that’s a nice 99% of the people I worked with) tend to fail miserably at writing cell renderer/editor, is why I tried not to advice people to use custom cell editor/renderer.



Buttons outside the table

It’s possible to add buttons somewhere on the screen that will do something related to the selected row in the table, that’s the easiest solution. The main problem of this implementation is that buttons are actually outside the table and hence that the buttons are not yet directly linked to the selected row, it might confuse the user.



Popup menu

Right click on the table to show a popup menu
This one is also an easy solution.
The main drawback of this solution is that at first the user has no idea there is actions available on the selected row via a popup menu



Overlay buttons

So far the main drawbacks of the above solutions are: buttons not directly linked to the selected row, popup not visible at first, repeating the same button again and again.
So why not try to come with a solution that will meet the following requirement:
Only one button per action visible at the same time, linked to the selected row.
Let’s have a look at the outside button way. What was is main problem? The buttons are not linked to the selected row. So how would it be possible to link it?

The solution I came up with is to use a JLayeredPane to position the buttons next to the selected row: here




Mixed approach

What happen now if there are more than 2 actions, so 2+ buttons.
The cell renderer approach will need more even more column, so even more space wasted.
The button overlay approach will also need some space to show the button, and the furthest button will not seems so much connected to the selected row

Only the popup approach is behaving well in this case, but at the same time it’s not user friendly as the possibility to see the popup is not explicit.

(I am not talking about the buttons outside the table way because I consider it not user friendly, because of how unrelated are the buttons with the table)


So why not mixed the popup approach with the 2 others?

Popup + cell renderer/editor / Popup + overlay button
The principle is the same in both approach, that is, to show a button that say “click me to see the popup” and put it either as a cell renderer or as an overlay button.









You can find all the above implementations here

web start demo:


Thursday, January 21, 2010

Validation overlays

What I mean validation is for example to have an error icon in a corner of a text field if the input is wrong.


Like a year ago I read a serie of articles about validation overlays on Kirill Grouchnikov blog at http://www.pushing-pixels.org/?p=69 that I really encourage you to read to have some information/idea how this can be implemented. I came to the conclusion that there were only easy 2 ways of doing this, using glasspane or jxlayer.
The glasspane suffer a performance issue and by the fact that there is only 1 glasspane per window.
JXlayer only drawback is that you can’t put the icon outside of the component.

One day I noticed that jide provide an easy way to add an overlay component to any component.
There is one problem although with jide you have to override the paintComponent Method(and add the required code) of each component you want to have the overlay component.
That’s a constraint I really didn’t want to deal with to have validation overlays, that’s make the code too complicated/unreadable

If you don’t override the paint method, the error icon won’t get repainted after the overlaid component, so the result is that the error icon will be partially/totally hidden by the overlaid component.




So the idea was to have a way to repaint the error icon each time the overlaid component is painted without to have to override the paintcomponent method of each overlaid component.


I came up with the idea to wrap the jide overlayable component inside a JXLayer, and to call the paint component of the overlay component inside the paint layer of the jxlayer, and Voila! Now we have the better of the 2 worlds: the error icon can be outside out the overlaid component and the error icon will be repainted each time the overlaid component does.


The error icon appears/disappear with a smooth animation as I like it.
The icon is a true component so it can have a tooltip, in our case the tooltip will be the error message.
You can change the default error icon for all or for one component:
ValidationPanelIcon.setDefaultIcon(BufferedImage)
ValidationOverlay.setIcon(BufferedImage newicon)


You can change the default location of the icon:
By changing the values of

ValidationPanelIcon.DEFAULT_XOFFSET
ValidationPanelIcon.DEFAULT_YOFFSET
ValidationPanelIcon.DEFAULT_ICON_LOCATION


Or by calling
ValidationIOverlay.setIconLocation(int xoffset, int yoffset, int location)



As there is a JXlayer in use, why not also us it fully and paint something on the layer?

You can specify a ValidationPaint :
ValidationIOverlay.setPaint(ValidationPaint)


ValidationPaint is an abstact class with the following method:


/**
*
* @param g
* @param msg the list of error message
* @param width width of the layer
* @param height height of the layer
* @param animProgress goes from 0 to 1 and then from 1 to 0, the duration of the animation can be set using ValidationOverlay.setAnimationDuration
*/
public abstract void paint(Graphics2D g, List<String> msg, JXLayer<JComponent> layer, float animProgress);



A default implementation is available :
ValidationPaint.getColorValidationPaint(Color)

This default implementation paint a rectangle over the component of the given color with a blink animation

As an example with a custom ValidationPaint it’s possible to write the error messages directly on the layer





ValidationOverlayFactory

To create the validation component use ValidationOverlayFactory:

createBlinking(T, List<Validator<T>>)
createBlinking(T, Validator<T>)
createBlinkingAndIcon(T, Validator<T>)
createBlinkingAndIconComponent(T, List<Validator<T>>)
createErrorOverlayedIcon(T, List<Validator<T>>)
createErrorOverlayedIcon(T, Validator<T>)


Validator is a simple interface

public interface Validator<T extends JComponent> {
String validate(T comp);
}


The validate method should return the error message or null if no error has been detected.

To execute the validator you have to call
ValidationOverlayFactory.validate(JComponent)

The jcomponent given to this method is your original component on wich you add the overlay


TextValidationOverlayFactory is a facility class to create validation overlaid component for text component, it installs automatically a listener to call ValidationOverlayFactory.check on a text changed.





validation overlays source code here

Saturday, January 16, 2010

Animated cell renderer

This article will take as example list cell renderer but the same way can be applied to animate tree/table renderer.

Let’s start from where the last article end: the renderer is bigger when the cell is selected, why not animate the fact that the renderer size increase over time, to let the user know it’s actually the one that he selected that get bigger.

First we need a way to store the animation value for each cell:


Map<Integer, Float> mapAnimation = new HashMap<Integer, Float>();


The renderer will look up for the animation value:

public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, final boolean cellHasFocus) {

JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index,isSelected, cellHasFocus);

Float progress = mapAnimation.get(index);
if (progress == null) {
progress = 0f;
}
label.setFont(label.getFont().deriveFont(10 + 20 * progress));
label.setPreferredSize(new Dimension(50, (int) (15 + 35 * progress)));
return label;
}




A selection listener to start the animation:
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
return;
}
final Timeline timeline = new Timeline();
timeline.setDuration(200);
timeline.addCallback(new TimelineCallback() {
/*…see below…*/
});
timeline.play();
}
});



The TimelineCallBack allow us to define what to do on each timeline pulse, it’s where the animation map will get populated.

new TimelineCallback() {
@Override
public void onTimelinePulse(float durationFraction,float TimelinePosition) {
// set the progress for the selected index
mapAnimation.put(list.getSelectedIndex(), durationFraction);
//set the progress for the last selected index
if (oldSelected[0] != -1) {
mapAnimation.put(oldSelected[0], 1 - durationFraction);
}
//compute the size for each cell with the new animation values
SwingUtilities.invokeLater(new Runnable(){
Override
public void run(){
JlistUtils.computeListSize(list);
}
});
}




And that’s it! You now have an animated renderer.




A bit more complex examples:













as always you can find the source code in the source code repository here

Dynamic size cell list renderer

What I mean by dynamic size is that the renderer can changed size for a given index.

Let’s take what can be seen at first as a very easy example:
For example when you select an item, you would like to increase the font size of the label.

It seems easy, let’s just create a custom renderer and change the font size based on the isSelected parameter.


public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (isSelected) {
label.setFont(label.getFont().deriveFont(35f));
} else {
label.setFont(label.getFont().deriveFont(10f));
}
return label;
}




The font size is bigger but the size of the label is not increased, hence the label is partly hidden .

So let’s try to change the size of the label:


public Component getListCellRendererComponent(JList list, Object value,int index, boolean isSelected, boolean cellHasFocus) {

JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (isSelected) {
label.setFont(label.getFont().deriveFont(35f));
label.setPreferredSize(new Dimension(50, 50));
} else {
label.setFont(label.getFont().deriveFont(10f));
label.setPreferredSize(new Dimension(50, 15));
}
return label;
}



To our surprise it doesn’t work. Why?

The answer is in the BasicListUI class, the height of each cell is cached, it doesn’t get computed each time the getListCellRendererComponent method get called. That’s where our problem lies.

By looking a bit more closely at BasicListUI, one can see that the cache is populated in the updateLayoutState method and that’s only getting called after a change in the model.

We have to call this method in order to compute the new size of each cell, but this method is protected,so we won’t be able to call this method directly so we will use reflection.


public static void computeListSize(final JList list) {
if (list.getUI() instanceof BasicListUI) {
BasicListUI ui = (BasicListUI) list.getUI();

try {
Method method = BasicListUI.class.getDeclaredMethod("updateLayoutState");
method.setAccessible(true);
method.invoke(ui);
list.revalidate();
list.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
}




In our case we need to compute the cell size when a cell gets selected:

list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
JlistUtils.computeListSize(list);
}
});



But as you can see if you run this webstart demo , it doesn’t work, so why ?
The answer is in the updateLayoutState method.:
protected void updateLayoutState(){
//…
Component c = renderer.getListCellRendererComponent(list, value, index, false, false);
//…
}



The 2 last parameters are isSelected and cellHasFocus, which means we can’t use isSelected+cellHasFocus to determine the size of the renderer.

So the last version of our renderer is:


public Component getListCellRendererComponent(JList list,Object value, int index, boolean isSelected, boolean cellHasFocus) {

JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (list.getSelectedIndex() == index) {
label.setFont(label.getFont().deriveFont(35f));
label.setPreferredSize(new Dimension(50, 50));
} else{
label.setFont(label.getFont().deriveFont(10f));
label.setPreferredSize(new Dimension(50, 15));
}
return label;
}



This time we actually have what we expected: the cell selected is bigger.






You can find the source of those demo in the following package in the source code repository here


all the jars files has been signed to run via webstart; that was needed because of the use of Method.setAccessible to be able to call a protected method