You are currently browsing the Philipp Meier's weblog blog archives for February, 2008

contact


This must be shared: /^1?$|^(11+?)\1+$/ to check for prime numbers

That’s all and checks if a string does not consist of a prime number of “1“, e.g. “111” is prime whereas “1111” is not:

[source:ruby]
/^1?$|^(11+?)\1+$/
[/source]

Although this seems cryptic its rather straight forward: match on either “” or “1” (first part until “|“) or match on a substring of 2 or more “1” with repeatedly fits the whole. For the string “111111” the substring “11” fits in 3 times.

Over all its a very high level description of a primality test. I never considered regular expressions as a mathematical domain language.

More details on Avinash Meetoo’s Blog.

advertise

Don’t subclass DefautListCellRenderer for Swing’s Nimbus LAF

If you follow the common practice to subclass JLabel to add some formatting to your combobox you will be surprised that this will break the rendering of JComboBoxes in the Nimbus Look Ant Feel.

Examples of bad JLabel-based CellRenderer

Basically the nice glass like look of the combobox will disappear and the old flat look will be restored. This comes due to Nimbus using a custom CellRenderer:

javax.swing.plaf.synth.SynthComboBoxUI$SynthComboBoxRenderer

Fortunately this renderer is based on JLabel, too. This is why you can simply wrap the renderer and add some blinkenlights when needed:

Good example of renderer wrapping the original renderer

The implementation is straight forward:

[source:java]
public class InstanceWithIconCellRendererWrapper implements ListCellRenderer {
private final ListCellRenderer wrapped;
public InstanceWithIconCellRendererWrapper(ListCellRenderer listCellRenderer) {
this.wrapped = listCellRenderer;
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String displayName = String.valueOf(value); // customize here
Component renderer = wrapped.getListCellRendererComponent(list, displayName, index, isSelected, cellHasFocus);
if (renderer instanceof JLabel) {
Icon icon = new ImageIcon(); // customize here
((JLabel) renderer).setIcon(icon);
}
return renderer;
}
}
[/source]

Use it as follows:


jComboBox.setRenderer(new InstanceWithIconCellRendererWrapper(jComboBox.getRenderer()));

store
support
partner
Bear