26 June 2009
Resize a dialog with a multi line text field that has fixed width
stackoverflow.com is a great forum to ask questions. Sometimes an answer to a question you ask there will trigger yourself to think in new ways so you can answer you own question. This happened to me in the problem with the dialog with the multi line text field with fixed width: http://stackoverflow.com/questions/1048224/get-height-of-multi-line-text-with-fixed-width-to-make-dialog-resize-properly
Base class for ChangeEvent/ChangeListener mangament
If you have written a data model you often want to be able to notify others about the change in the model by using some kind of listener. The Java swing ChangeListener interface is one choice of listener to choose. But the management of a listener list (adding, removing and notification of listeners) is a bit of a hazel to write code for each time you have a model. I searched the Java API but could not find any base class of helper class to solve this. The closest I got was the EventListenerList class. By using this class I've written my own base/helper class:
An example of how to use this class:
import javax.swing.event.*;
/**
* Convenience class to notify others of changes
* Can be used as a base class or as an aggregate/helper
*/
public class ChangeEventDispatcher {
protected EventListenerList listenerList = new EventListenerList();
protected ChangeEvent changeEvent = null;
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void removeFooListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
/**
* Called by by child/wrapper class to dispatch a Change event
*
* Code is copied from EventListenerList documentation and adapted to ChangeEvent
*/
public void fireChangeEvent() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
}
An example of how to use this class:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
@SuppressWarnings("serial")
public class ChangeTester extends JFrame {
private JButton increaseButton = new JButton("Increase");
private JLabel valueLabel = new JLabel();
private ValueModel model = new ValueModel();
public ChangeTester() {
setLayout(new FlowLayout());
add(increaseButton);
add(valueLabel);
//Change the model when pressing the button
increaseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.increaseValue();
}
});
//The label should be updated when the model is changed
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateLabelValue();
}
});
updateLabelValue();
pack();
}
private void updateLabelValue() {
valueLabel.setText(Integer.toString(model.getValue()));
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new ChangeTester();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
/**
* Simple model that extends the ChangeEventDispatcher
* to get listener list handling
*/
public static class ValueModel extends ChangeEventDispatcher {
private int value;
public void increaseValue() {
this.value++;
fireChangeEvent(); //Notify listeners
}
public int getValue() {
return value;
}
}
}
Quick close a dialog by escape key
I Windows there is a convention that a dialog is closed (and canceled) if the user pressed the Esc key. There is also a convention that pressing Enter closes (and confirms) the dialog. In Java there is no default implementation of this.
So we need to implement this ourself. A naive approach would be to add a KeyListener to the dialog. This will not work if the keyboard focus is in a nested component (for example a text field). So how about to add a key listener to both the dialog and all its subcomponents? Well this would work, and I have successfully implemented this using a ContainerListener in the dialog so any components added in the dialog also gets a key listener. But there is a simpler way: the key bindings way!
With a key binding you don't have to care where the keyboard focus is.
Update: My solution is probably not thread safe, this alternative solution is: http://stackoverflow.com/questions/642925/swing-how-do-i-close-a-dialog-when-the-esc-key-is-pressed
So we need to implement this ourself. A naive approach would be to add a KeyListener to the dialog. This will not work if the keyboard focus is in a nested component (for example a text field). So how about to add a key listener to both the dialog and all its subcomponents? Well this would work, and I have successfully implemented this using a ContainerListener in the dialog so any components added in the dialog also gets a key listener. But there is a simpler way: the key bindings way!
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
@SuppressWarnings("serial")
public class QuickCloseDialog extends JDialog {
public QuickCloseDialog() {
initCloseListener();
add(new JTextField("A text field"));
pack();
}
private void initCloseListener() {
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE , 0), "close");
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "close");
getRootPane().getActionMap().put("close", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JDialog dialog = new QuickCloseDialog();
dialog.setVisible(true);
}
});
}
}
With a key binding you don't have to care where the keyboard focus is.
Update: My solution is probably not thread safe, this alternative solution is: http://stackoverflow.com/questions/642925/swing-how-do-i-close-a-dialog-when-the-esc-key-is-pressed
25 June 2009
Static import and GroupLayout tip for Eclipse
I you like GroupLayout and use Eclipse this might be a good tip:
Eclipse is not that good with static imports but it is possible to make the content assist suggest and automatically add static imports. Go to Preferences -> Java -> Editor -> Content Assist -> Favorites and add the types

It is now possible to use the Content Assist (Ctrl + Space) to get help when writing the GroupLayout properties:
Eclipse is not that good with static imports but it is possible to make the content assist suggest and automatically add static imports. Go to Preferences -> Java -> Editor -> Content Assist -> Favorites and add the types
javax.swing.GroupLayout.*, javax.swing.GroupLayout.Alignment.* and javax.swing.LayoutStyle.ComponentPlacement.*:
It is now possible to use the Content Assist (Ctrl + Space) to get help when writing the GroupLayout properties:
Eclipse 3.5 Galileo - a first impression

I installed Eclipse 3.5 (or Galileo as it is called) today.
My first impression is that it is similar to 3.4. One thing that i noticed is that cancellation of building a Java project is working better in 3.5. The Java editor is updated and writing code is a bit different. For instance I got a bit annoyed by how parenthesis are inserted. But I guess that I'll quickly get used to it.
The "editor" for Team Synchronizing compare view is updated so it now is more like a Java editor. I'm note sure I will edit code in a compare view just now. I still miss the Ctrl + Shift + T shortcut in Team Synchronizing.
24 June 2009
Key bindings is sometimes to prefer over KeyListener
In Java (Swing) there are KeyListener:s and key bindins. KeyListerner is the classical way of catching events from the keyboard. But inn some situations the key bindings feature is preferred:
For example if you are developing a tetris game this code can be used to get the Left arrow key:
To catch the control key use
More information at http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
- If you want to catch (only) the CTRL key
- If you want to catch keys regardles of where the user has focus
For example if you are developing a tetris game this code can be used to get the Left arrow key:
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
getActionMap().put("left", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
engine.moveBrickLeft();
}
});
To catch the control key use
KeyStroke.getKeyStroke("ctrl pressed CONTROL") and KeyStroke.getKeyStroke("released CONTROL")More information at http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
04 June 2009
Hint: Set a good comment on your ssh key
Using a ssh key to login into a ssh account is really good. You don't have to know the passwords of the accounts you are logging into, only the password on the ssh key (if any). If you use a password on the key the password can be cached (for example using Pageant).
When creating a ssh key I really recommend that you set a good comment. For example using puttygen enter a "Key comment":

This should be included in the key:
This way it will be so much easier when someone should clean up the keys from
When creating a ssh key I really recommend that you set a good comment. For example using puttygen enter a "Key comment":

This should be included in the key:
- The identity of you (for example your e-mail)
- The computer you used to create it on (for example your Windows computer name)
- The date you created the key
This way it will be so much easier when someone should clean up the keys from
.ssh/authorized_keys. The identity is good if there are many users for the same ssh account (common in some corporations). The computer name and date is useful when you know that you have lost the key (for example because of hard drive crash), of when a security exploit has been published and the key is considered unsafe.
Subscribe to:
Posts (Atom)