Sunday, April 3, 2011

Collapsible SWT Text Area Snippet

A little sample code showing how you can have a Java SWT button that can collapse other Controls like a toggle switch. This also will show how to resize the container after "collapsing" your control.

I went this route after not finding the SWT ExpandBar widget suiting this purpose.

Screenshots from Windows 7

Source Code

/*
*
*/
package swt.snippet;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.brianl.timetrack.controller.TimeSession;
import com.brianl.timetrack.view.CollapseButtonListener;

/**
* Simple SWT Shell that contains a Group with some controls. An arrow button is
* used to toggle the Text area widget as collapsed or not.
*
* @author ammianus http://librixxxi.blogspot.com/
*
*/
public class CollapsibleTextBox {

private static final int NUMBER_GRID_COLUMNS = 1;

private Display _display;

private Shell _shell;

CollapsibleTextBox() {
_display = new Display();
_shell = new Shell(_display);
_shell.setSize(300, 250);
// Collapsible Group
_shell.setText("Collapsible Group Example");
// format shell as single column grid layout
_shell.setLayout(new GridLayout(NUMBER_GRID_COLUMNS, true));

// create the group
Group collapseGroup = new Group(_shell, SWT.NONE);
GridData groupGrid = new GridData(SWT.TOP, SWT.LEFT, false, false);
groupGrid.horizontalSpan = 1;
collapseGroup.setLayoutData(groupGrid);
collapseGroup.setText("Control Group");

// create a Label and Button inside the Group
GridData labelGridData = new GridData(GridData.VERTICAL_ALIGN_END);
labelGridData.horizontalSpan = 1;
String labelText = "Pressing button toggles Text. ";
final Label instructionLabel = new Label(collapseGroup, SWT.NONE);
instructionLabel.setText(labelText);
instructionLabel.setLayoutData(labelGridData);
instructionLabel.pack();

final Button collapseButton = new Button(collapseGroup, SWT.ARROW
| SWT.UP);

// multi-row Text area with word-wrap
final Text textArea = new Text(collapseGroup, SWT.MULTI | SWT.LEAD
| SWT.BORDER | SWT.WRAP);

// set height and width of Text area
GC gc = new GC(textArea);
FontMetrics fm = gc.getFontMetrics();
final int textBoxWidth = 50 * fm.getAverageCharWidth();
final int textBoxHeight = 4 * fm.getHeight();
gc.dispose();
textArea.setSize(textArea.computeSize(textBoxWidth, textBoxHeight));
GridData textBoxGrid = new GridData(SWT.TOP, SWT.LEFT, false, false);
textBoxGrid.horizontalSpan = NUMBER_GRID_COLUMNS;
textBoxGrid.heightHint = textBoxHeight;
textBoxGrid.widthHint = textBoxWidth;
textArea.setLayoutData(textBoxGrid);

// set the layout for the items contained by the Group as a two column
// grid
collapseGroup.setLayout(new GridLayout(2, false));
collapseGroup.layout(true);

// create a listener that waits for button press
collapseButton.addListener(SWT.Selection, new CollapseButtonListener(
textArea, textBoxWidth, textBoxHeight, collapseGroup,
textBoxGrid));

// open the shell and run UI loop
_shell.pack();
_shell.open();
while (!_shell.isDisposed()) {
if (!_display.readAndDispatch())
_display.sleep();
}
_display.dispose();
}

/**
* Runs the demo
*
* @param args
*/
public static void main(String[] args) {
new CollapsibleTextBox();
}

/**
* inner class handles button click events for arrow button
*
*/
public class CollapseButtonListener implements Listener {

private Text _timeNotesBox;
private int _textBoxHeight;
private int _textBoxWidth;
private Group _container;
private GridData _textBoxGrid;

/**
* @param timeNotesBox
* @param textBoxHeight
* @param textBoxWidth
* @param container
* @param textBoxGrid
*/
public CollapseButtonListener(Text timeNotesBox, int textBoxWidth,
int textBoxHeight, Group container, GridData textBoxGrid) {
super();
// save references to the various controls to update
this._timeNotesBox = timeNotesBox;
this._textBoxHeight = textBoxHeight;
this._textBoxWidth = textBoxWidth;
this._container = container;
this._textBoxGrid = textBoxGrid;
}

/*
* (non-Javadoc)
*
* @see
* org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets
* .Event)
*/
@Override
public void handleEvent(Event event) {
// toggles the Text Area as visible or not.
// When Text Area is collapsed, resize the parent group
if (_timeNotesBox.getVisible()) {
// collapse the text area
_timeNotesBox.setSize(_timeNotesBox.computeSize(1, 1));
_textBoxGrid.heightHint = 1;
_textBoxGrid.widthHint = 1;
_timeNotesBox.setLayoutData(_textBoxGrid);
_timeNotesBox.setVisible(false);
_timeNotesBox.pack(true);
System.out.println("Hiding textbox");
} else {
// expand text area back to original sizing
_timeNotesBox.setSize(_timeNotesBox.computeSize(_textBoxWidth,
_textBoxHeight));
_textBoxGrid.heightHint = _textBoxHeight;
_textBoxGrid.widthHint = _textBoxWidth;
_timeNotesBox.setLayoutData(_textBoxGrid);
_timeNotesBox.setVisible(true);
_timeNotesBox.pack(true);
System.out.println("Showing textbox");
}

// in this case the container is the Group
_container.pack(true);

// resize the parent shell too
_container.getParent().pack(true);
}

}
}


Built with:
swt-3.6.1-win32-win32-x86
Java 1.6.0_17
Eclipse 3.4.1

Built on the model of the snippets from java2s and the SWT snippets site.

I came up with this approach as I am trying to have an optional text box in my "Time Track" program. I really didn't see any other way to have this kind of dynamic visual behavior that is pretty common on websites these days. The only prebuilt widget that seemed similar was the ExpandBar, but what that did was create a large pane with expandable widgets within it. These all had a very non-native look and feel and was bit complex to set up when I had a single text box to expand/collapse.

Saturday, March 19, 2011

Upgrade to Windows 7

I have upgraded my Toshiba laptop to Windows 7. Long story short I have had some difficulties with opening web browsers, after many frustrating hours spent over the past several months, I decided to throw in the towel.

I installed Windows 7 Home Premium SP 1 x64 media. It was a very smooth upgrade, took about 1 hour this morning.

I was pleasantly surprised that it actually backed up my old OS first. All of my files are available under the new directory Windows.old, which contains the following dirs and their content from my old OS.
$Recycle.Bin
Documents and Settings
Program Files
Program Files (x86)
ProgramData
Users
Windows


So I get a clean new OS, and all the files from my old PC.

I sort of prefer the icons and desktop wallpapers from Vista, and they have all different ones bundled with Win 7.

For default desktop wallpapers, you can find them under:
C:\Windows\Web\Wallpaper
You can create sub-directories, which I did for my Vista wallpapers from the same location in Windows.old. Windows 7 displays the sub-directories as sections in the default Desktop Background selection window.

For User Account pictures, I had to get some help from the web:
http://www.winhelponline.com/articles/238/1/Adding-a-custom-picture-to-the-list-of-user-account-pictures.html
The default User Account icons are under
C:\ProgramData\Microsoft\User Account Pictures\Default Pictures
It does not seem that sub-directories are allowed for default User Account change picture selection screen.





Tuesday, March 15, 2011

Basic scientific explanation of Japan Fukushima nuclear plant disaster

On top of the tragedy from tsunami and earthquake, Japan is experiencing another potential catastrophe from a nuclear plant failure.

This article posted on the site of the MIT department of Nuclear Engineering goes into the basic details of the design of the plants at Fukushima and explanation of the events there over the last few days.

http://mitnse.com/2011/03/13/why-i-am-not-worried-about-japans-nuclear-reactors/

The only question I still have after reading this article was how long that they need to keep cooling the shut-down reactor core? Is it several days (so the end is in sight) or will it be weeks? Apparently it has already been 3-4 days at least.

I am also curious about the temperature / pressures involved. Apparently they are battling to stay under 1200°C, and that is with the heat mainly coming from radioactive decay rather than fission (if I understand correctly). If there were no coolant at all how hot could it get just from that?





Monday, February 21, 2011

Firefox 4 to the future

I just installed Firefox 4.0 beta this weekend. More than any new features, I was impressed by the first run artwork that they are using to market the FF 4 beta. All the illustrations are retro-futuristic, highly detailed, scenes of future technology, space colony landscapes and jet packs. Although the actual browser is just a browser, no self-aware robots or jet packs involved I still liked the concept. Here is an example (from http://www.mozilla.com/en-US/firefox/3.6.13/whatsnew/)


After a bit of digging, the artwork is by artist: Steven Olds.


The marketing blog for Mozilla attributes some of the inspiration for this campaign to "20th century futurist" Klaus Bürgle.

This also reminds me of the amazing paintings I used to read about in space books as a kid, often borrowing images from the 1975 "Stanford Torus" NASA Ames/Stanford study on building a colony in space for 10,000 people. One of the artists for that project was Dan Davis and others such as Rick Guidice who contributed artwork to Gerard O'neill's book the High Frontier

Will using Firefox help me live there? Can someone at least make a persona of this stuff?

Saturday, February 12, 2011

Listing files in a folder to a text file on Windows

One endless source of annoyance in my work is copying and a list of file names from some folder to paste in another document.

In the Windows UI, your only option is really right-clicking on individual file names, clicking Rename and then selecting the name to copy. This must be done for each file.

The fastest way I have found to achieve this uses a DOS Command Prompt and flags for the dir command.

To open a Command Prompt window, in pretty much all versions of Windows. Go to Start > Run > type "cmd" (without quotes).

To get a list of files and directories into a text file use the "dir" command with "/B" option

C:\java>dir /B
Apache Software Foundation
apache-ant-1.8.2-bin
apache-ant-1.8.2-bin.zip
apache-ant-1.8.2-manual
apache-ant-1.8.2-manual.zip
chrome.dmp
databene-benerator-0.6.3-dist
databene-benerator-0.6.3-dist.zip
eclipse-jee-ganymede-SR1-win32
eclipse-SDK-3.6.1-win32
eclipse-SDK-3.6.1-win32.zip
javadb-10_5_3_0
javadb-10_5_3_0.zip
MiniConnectionPoolManager.zip
opencsv-2.2
opencsv-2.2-src-with-libs.tar.gz
swt-3.6.1-cocoa-macosx
swt-3.6.1-cocoa-macosx.zip
swt-3.6.1-gtk-linux-x86
swt-3.6.1-gtk-linux-x86.zip
swt-3.6.1-gtk-linux-x86_64
swt-3.6.1-gtk-linux-x86_64.zip
swt-3.6.1-win32-win32-x86
swt-3.6.1-win32-win32-x86.zip
TimeTrack_win32


To have the output of this command piped to a file "C:\output.txt" use the ">" symbol:
dir /B > C:\output.txt

To only show files, no directories you can use the /A:-D flag ("/A:" is for attribute matching filters, "D" is directories, "-" is for not):
dir /A:-D/B > C:\output.txt

Results in the file contents being:

apache-ant-1.8.2-bin.zip
apache-ant-1.8.2-manual.zip
chrome.dmp
databene-benerator-0.6.3-dist.zip
eclipse-SDK-3.6.1-win32.zip
javadb-10_5_3_0.zip
MiniConnectionPoolManager.zip
opencsv-2.2-src-with-libs.tar.gz
output.txt
swt-3.6.1-cocoa-macosx.zip
swt-3.6.1-gtk-linux-x86.zip
swt-3.6.1-gtk-linux-x86_64.zip
swt-3.6.1-win32-win32-x86.zip


Note: on some versions of Windows you can't save a file to C:\ without running the cmd.exe as an Administrator.

For more information on the other flags for more control over your output:
C:\java>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
[/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

[drive:][path][filename]
Specifies drive, directory, and/or files to list.

/A Displays files with specified attributes.
attributes D Directories R Read-only files
H Hidden files A Files ready for archiving
S System files I Not content indexed files
L Reparse Points - Prefix meaning not
/B Uses bare format (no heading information or summary).
/C Display the thousand separator in file sizes. This is the
default. Use /-C to disable display of separator.
/D Same as wide but files are list sorted by column.
/L Uses lowercase.
/N New long list format where filenames are on the far right.
/O List by files in sorted order.
sortorder N By name (alphabetic) S By size (smallest first)
E By extension (alphabetic) D By date/time (oldest first)
G Group directories first - Prefix to reverse order
/P Pauses after each screenful of information.
/Q Display the owner of the file.
/R Display alternate data streams of the file.
/S Displays files in specified directory and all subdirectories.
/T Controls which time field displayed or used for sorting
timefield C Creation
A Last Access
W Last Written
/W Uses wide list format.
/X This displays the short names generated for non-8dot3 file
names. The format is that of /N with the short name inserted
before the long name. If no short name is present, blanks are
displayed in its place.
/4 Displays four-digit years

Switches may be preset in the DIRCMD environment variable. Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

Sunday, February 6, 2011

Introducing the Time Track Project

The Time Track application is a small side-project I have been developing since late November 2010. It is a simple application that lets a user keep track of time spent on work, projects, tasks etc.


Time Track main window, Windows Vista x64

The main requirements for the Time Track application were

  • Be a software version of a time punch clock, for any purpose

  • Keep track of time in a persistant format that can be saved

  • Cross-platform support (at least Windows, Mac OS X)

  • Needs a GUI

  • Lightweight, simple to use and set up

I developed this in Java as a standalone desktop program with a GUI using all OpenSource components. I am nearly complete with an initial version that meets all this functionality and I intend to release it as a free-ware app for now, maybe it can be made released as open source by itself in the future.


Implementation


I had really two paths I could have taken with this, one would be to build a dynamic webapp with a RDBMS backend. The second approach was to develop a standalone self-contained application that could be somewhat portable itself. I was hesitant to take on a project that required any sort of server set up and hosting, I am just not set up to do that now, so although the webapp was pretty easily cross-platform being browser based, I didn't like the idea of the dependency on the remote server.


I went with the standalone app approach, in order to be cross-platform and easy for me to develop I went with Java as the source language. I didn't want the program looking like a Java Swing application so I opted for the SWT api which is the basis for the Eclipse IDE and platform, it tends to look more "solid" in my opinion as one of its main features is native look and feel for UI components on every OS. I think so far it is coming along nicely. You can see a side-by-side comparison of the interface in Windows Vista, and on Linux (Ubuntu 10.04, 64-bit)




I have probably spent around 5 weekends and the occasional hour on a weeknight in total since I started building this application. Probably overall time spent has been under 80 hours. It was enjoyable to more or less go through the full development life-cycle for a new project. I got to do design, open-source research, coding and integration, source-control, and complete build scripts in Ant. Even though I may never release a line of code from this, I am building like I could.

In terms of the OpenSource projects that I used a variety of different components in my stack.

For my build environment, I am using Java JDK 1.6.0_17, Eclipse Ganymede IDE, Junit 3 (for the few automated unit tests that were really helpful with Derby), SVN for source control and builds are done with ANT. Testing was done on Windows Vista SP2 x64 and Ubuntu Linux 64-bit GTK.


RoadMap
On my to do list I still have a number of items I'd like to close out before really wrapping up this release.
  • The main table needs to update when changes occur. Currently it is loaded at start up.
  • Need to think about an import data function.
  • Testing on a Mac
  • Implement a more solid connection pool mechanism
  • Release strategy. Post on this site? or create an OpenSource project page?

Friday, December 24, 2010

Christmas Redwoods

Our redwoods needed to show some Christmas spirit.

Unfortunately the only horizontal branches strong enough to really hold ornaments are near the base of the trees, about an inch or two from the soil in their pots. We managed to hang a few ornaments around the trunk. It didn't help that the ornament kit we got had no hooks for hanging.







As you can see the seedlings are doing just fine so far this winter. Generally they have been near the window for the short amount of direct sunlight we have in the apartment, the cold temperatures from outside haven't seemed to affect them too much.