Thursday, May 10, 2007

Create a drop-down menu for image selection using java

The following code uses JCombo class for creating a drop down menu that provides the user the ability to choose and see the selected image. Note that the images you want to inlcude in your app should be saved in the main directory of your program (if you use netbeans for example open the project folder and save the images there).

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ComboBoxTest extends JFrame {
private JComboBox images;
private JLabel label;
private String names[] =
{ "cutlass_32.png", "pet-monkey_32.png",
"pirate-captain_32.png", "first-mate_32.png" };
private Icon icons[] =
{ new ImageIcon( names[ 0 ] ),
new ImageIcon( names[ 1 ] ),
new ImageIcon( names[ 2 ] ),
new ImageIcon( names[ 3 ] ) };

public ComboBoxTest()
{
super( "Psy2k-Photo Selection" );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

images = new JComboBox( names );
images.setMaximumRowCount( 3 );

images.addItemListener(
new ItemListener() {
public void itemStateChanged( ItemEvent e )
{
label.setIcon(
icons[ images.getSelectedIndex() ] );
}
}
);

c.add( images );

label = new JLabel( icons[ 0 ] );
c.add( label );

setSize( 350, 100 );
show();
}

public static void main( String args[] )
{
ComboBoxTest app = new ComboBoxTest();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
The icons I used in this app are from Iconbuffet's Amsterdam High Seas collection (pirate icon yeah). Iconbuffet is a free social community for trading small icons with others. If you would like to join the madness feel free. It is very addicting!

1 comment:

Anonymous said...

Nice blog dude!

keep it java ;)