21 April 2009

GroupLayout vs JFrame - the content pane problem

I really like the "new" GroupLayout that was introduced in JDK 1.6. It originates from Netbeans GUI editor. It is a layout that groups components in logical groups. For a tutorial of GroupLayout see http://java.sun.com/docs/books/tutorial/uiswing/layout/group.html.

The JFrame is a sneaky Swing implementation. It has a content pane where the main things of your application should be in. But is has convenience methods (for example add() and setLauout()) that actually invokes call in the content pane. This might make you believe you can use is just as a normal container when using GroupLayout. The naive approach is to do this:
public class MyFrame extends JFrame {
GroupLayout layout = new GroupLayout(this);
...

This will unfortunately not work. The GroupLayout is fooled to control the JFrame, but in fact it should control the content pane inside the JFrame. The solution is instead to to this:

import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class GroupLayoutJFrameExample extends JFrame {

private GroupLayout layout = new GroupLayout(this.getContentPane());

public GroupLayoutJFrameExample() {
initLayout();
pack();
}

private void initLayout() {
this.getContentPane().removeAll();
this.getContentPane().setLayout(layout);

JLabel helloLabel = new JLabel("Hello!");

layout.setVerticalGroup(layout.createSequentialGroup()
.addComponent(helloLabel)
);

layout.setHorizontalGroup(layout.createParallelGroup()
.addComponent(helloLabel)
);
}

public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new GroupLayoutJFrameExample();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

16 April 2009

How to merge-copy a Java bean

Problem: you have one template object and one target object. They are of the same class and is a standard Java bean. You would like to copy and merge all of the properties from the template object to the target object, but only for attributes that is null in the target.

Solution:
  public <M> void merge(M target, M destination) throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(target.getClass());

// Iterate over all the attributes
for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {

// Only copy writable attributes
if (descriptor.getWriteMethod() != null) {
Object originalValue = descriptor.getReadMethod()
.invoke(target);

// Only copy values values where the destination values is null
if (originalValue == null) {
Object defaultValue = descriptor.getReadMethod().invoke(
destination);
descriptor.getWriteMethod().invoke(target, defaultValue);
}

}
}
}


Test code:
  @Test
public void testMerge() throws Exception {
Person templatePerson = new Person("Template", 20);
Person targetPerson = new Person("Johan", null);
merge(targetPerson, templatePerson);

assertEquals("Johan", targetPerson.getName());
assertEquals(20, targetPerson.getAge());
}

private static class Person {
private String name;
private Integer age;

public Person(String name, Integer age) {
this.name = name;
this.age = age;
}

public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
}

09 April 2009

Tetris in Java (J2ME) MIDP 1.0

I found my old Tetris game i developed in 2004. At that time I had a Ericsson 610i phone. It supported MIDP 1.0. Nowdays the specification for J2ME have evloved quite some much. I tried to play the game on my 3 years old SonyEricsson W810. It still works! Well sort of, I noticed that there is bug so that exiting is a bit harder than it used to...


If you want to play my Tetris direct your phone to this URL: http://lesc.se/tetris/Tetris.jad.

05 April 2009

A simple under clock experiment

I have one computer in a closet. It is a server that is always on. I did a little experiment to see how under clocking the CPU would affect temperature and power consumption.

The CPU is a AMD Atholon 3500+ that clocks in a 2,2 GHz. During the test I had 2 Gb of memory and one Samsung 80 Gb, 2 platter 2,5 inch hard drive (a notebook hard drive).







SpeedPower consumptionTemperature (high fan speed)Temperature (low fan speed)
2,2 GHzLoad36 W5260
Idle26 W3940
1,8 GHzLoad35 W4653
Idle25 W3739
1,0 GHzLoad30 W4244
Idle25 W3739

I did not modify the VCore anything during these tests, I let the motherboard decide that. My guess is that with more tuning of the VCore I would have gotten better numbers.

31 March 2009

BeanTableModel as a TableModel for Swing

I've written lots of models for JTable's in Swing. Often I have to re-learn how Swing TableModel work each time. There is also often the case that one row in the table represents a Java object with bean getters and setters. Inspired by the Spring bean configuration I wrote TableModel that uses a bean class as a base.

It makes it easy to create a table and sets up the default CellEditors automatically and can get and set data from the cell in the GUI to the Java object.


BeanTableModel:
package se.lesc.beantablemodel;

import java.beans.*;
import java.util.*;

import javax.swing.table.AbstractTableModel;

/**
* A table model where each row represents one instance of a Java bean.
* When the user edits a cell the model is updated.
*
* @author Lennart Schedin
*
* @param <M> The type of model
*/
@SuppressWarnings("serial")
public class BeanTableModel<M> extends AbstractTableModel {
private List<M> rows = new ArrayList<M>();
private List<BeanColumn> columns = new ArrayList<BeanColumn>();
private Class<?> beanClass;

public BeanTableModel(Class<?> beanClass) {
this.beanClass = beanClass;
}

public void addColumn(String columnGUIName, String beanAttribute,
EditMode editable) {
try {
PropertyDescriptor descriptor = new PropertyDescriptor(beanAttribute,
beanClass);
columns.add(new BeanColumn(columnGUIName, editable, descriptor));
} catch (Exception e) {
e.printStackTrace();
}
}

public void addColumn(String columnGUIName, String beanAttribute) {
addColumn(columnGUIName, beanAttribute, EditMode.NON_EDITABLE);
}

public void addRow(M row) {
rows.add(row);
}

public void addRows(List<M> rows) {
for (M row : rows) {
addRow(row);
}
}

public int getColumnCount() {
return columns.size();
}

public int getRowCount() {
return rows.size();
}

public Object getValueAt(int rowIndex, int columnIndex) {
BeanColumn column = columns.get(columnIndex);
M row = rows.get(rowIndex);

Object result = null;
try {
result = column.descriptor.getReadMethod().invoke(row);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

public void setValueAt(Object value, int rowIndex, int columnIndex) {
M row = rows.get(rowIndex);
BeanColumn column = columns.get(columnIndex);

try {
column.descriptor.getWriteMethod().invoke(row, value);
} catch (Exception e) {
e.printStackTrace();
}
}

public Class<?> getColumnClass(int columnIndex) {
BeanColumn column = columns.get(columnIndex);
Class<?> returnType = column.descriptor.getReadMethod().getReturnType();
return returnType;
}

public String getColumnName(int column) {
return columns.get(column).columnGUIName;
}


public boolean isCellEditable(int rowIndex, int columnIndex) {
return columns.get(columnIndex).editable == EditMode.EDITABLE;
}

public List<M> getRows() {
return rows;
}

public enum EditMode {
NON_EDITABLE,
EDITABLE;
}

/** One column in the table */
private static class BeanColumn {
private String columnGUIName;
private EditMode editable;
private PropertyDescriptor descriptor;

public BeanColumn(String columnGUIName, EditMode editable,
PropertyDescriptor descriptor) {
this.columnGUIName = columnGUIName;
this.editable = editable;
this.descriptor = descriptor;
}
}
}

A test class:
package se.lesc.beantablemodel;

import javax.swing.*;

import se.lesc.beantablemodel.BeanTableModel.EditMode;

@SuppressWarnings("serial")
public class TableTester extends JTable {

public TableTester() {
BeanTableModel<Person> model = new BeanTableModel<Person>(Person.class);
model.addColumn("Social Security Number", "socialSecurityNumber");
model.addColumn("Name", "name", EditMode.EDITABLE);
model.addColumn("Age", "age", EditMode.EDITABLE);
model.addColumn("Heigt (in cm)", "height", EditMode.EDITABLE);
model.addColumn("Has empoyment", "employed", EditMode.EDITABLE);

model.addRow(new Person("1", "David", 20, 170.5, true));
model.addRow(new Person("2", "Susan", 26, 162.0, false));
model.addRow(new Person("3", "Mark", 42, 180.5, false));
model.addRow(new Person("4", "Anna", 54, 168.0, true));
model.addRow(new Person("5", "Johan", 5, 120.5, false));

setModel(model);
}

public static class Person {
private String socialSecurityNumber;
private String name;
private Integer age;
private Double height;
private Boolean employed;
private String hiddenField;

public Person(String socialSecurityNumber, String name, Integer age,
Double height, Boolean isMale) {
this.socialSecurityNumber = socialSecurityNumber;
this.name = name;
this.age = age;
this.height = height;
this.employed = isMale;
}

public String getSocialSecurityNumber() {
return socialSecurityNumber;
}
public void setSocialSecurityNumber(String socialSecurityNumber) {
this.socialSecurityNumber = socialSecurityNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getHeight() {
return height;
}
public void setHeight(Double height) {
this.height = height;
}
public Boolean isEmployed() {
return employed;
}
public void setEmployed(Boolean employed) {
this.employed = employed;
}

public String getHiddenField() {
return hiddenField;
}
public void setHiddenField(String hiddenField) {
this.hiddenField = hiddenField;
}
}

public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

TableTester table = new TableTester();
JScrollPane scollPane = new JScrollPane(table);
frame.setContentPane(scollPane);

frame.pack();
frame.setVisible(true);

}
}

11 March 2009

Where are the numerical-less keyboards?

I want more keyboards that are full size without a numerical keyboard. Why? It is a purely physical requirement! A person that uses the mouse in the right hand does not have to use as wide angle of the arm if the keyboard is narrower. Even a slight change in angle of the arm increases the risk of mouse arm syndrome. A human person arms are its most comfortable when angling into the direction of the body. A user of the classical finger position on the keaboard (“asdf jklö” on my keyboard) has a long way to the mouse on the right side, probably risking to angle the arm outside the body.


The only keyboard that I have found is the Logitech Dinovo cordless desktop for notebooks (it is no difference between the “for notesbooks” and “laser” except the mouse). It now looks like Logitech is going to stop producing this keyboard (it can only be found in the support section on www.logitech.com).

Use Launchy to start applications

A nice program to start applications is Launchy. It is almost like the start field in Vista, except this is a standalone program. I recommend the Putty plugin to Launchy. With this, it has never been easier to start a new ssh session. Just press Alt-Space to start Launcy and then enter "ssh" to enable the putty plugin. After that enter a saved Putty session or a IP-number or host to connect to a new ssh server.



This is how it looks like. Launch can start almost all your programs (and with parameters)!