// Scott DeRuiter 4/2/03
// BoxIt.java
// Simple example of a BoxLayout
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BoxIt extends JApplet implements ActionListener
{
private Image [] image;
private boolean click;
private int index, max;
private JButton [] pic;
public BoxIt ( )
{
index = 0;
max = 30;
}
public void init ( )
{
click = false;
getContentPane().setBackground( Color.black );
Box vbox1 = Box.createVerticalBox();
Box vbox2 = Box.createVerticalBox();
image = new Image[max];
pic = new JButton[max];
for ( int i = 0; i < image.length; i++ )
{
pic[i] = new JButton ( );
image[i] = getImage ( getDocumentBase ( ), "pic" + i + ".jpg" );
WaitForImage ( this, image[i] );
if ( i <= 14 )
CreateAButton ( vbox1, pic[i], i+1 );
else
CreateAButton ( vbox2, pic[i], i+1 );
}
getContentPane().add ( BorderLayout.WEST, vbox1 );
getContentPane().add ( BorderLayout.EAST, vbox2 );
}
public void CreateAButton ( Box vbox, JButton pic, int i )
{
String fill = "";
if ( i < 10 )
fill = "0";
pic = new JButton ( "PIC " + fill + i );
pic.addActionListener ( this );
vbox.add ( pic );
}
public void WaitForImage ( JApplet component, Image image )
{
MediaTracker tracker = new MediaTracker ( component );
try
{
tracker.addImage ( image, 0 );
tracker.waitForID ( 0 );
}
catch ( InterruptedException e )
{
e.printStackTrace ( );
}
}
public void paint(Graphics g)
{
boolean b = false;
if ( !click )
super.paint ( g );
else
b = g.drawImage ( image[index], 70, 0, this );
click = false;
}
public void actionPerformed ( ActionEvent evt )
{
String command = evt.getActionCommand();
for ( int i = 0; i < image.length; i++ )
CheckForClick ( command, i+1 );
}
public void CheckForClick ( String command, int i )
{
String fill = "";
if ( i < 10 )
fill = "0";
if ( command.equals ( "PIC " + fill + i ) )
{
click = true;
index = i - 1;
repaint ( );
}
}
}
Back to Lesson 29 Examples
Back to Java Main Page