// Purpose. Presentation layer to Towers of Hanoi import java.awt.*; import java.awt.event.*; import java.util.List; public class TowersOfHanoiPresentation implements ActionListener { private Tower[] towers = new Tower[3]; private List instructions; public TowersOfHanoiPresentation( int size, List instr ) { instructions = instr; Frame f = new Frame( "Towers of Hanoi" ); f.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); Panel center = new Panel(); center.setLayout( new GridLayout(1,3) ); for (int i=0; i < 3; i++) center.add( towers[i] = new Tower( i == 0, size ) ); Panel bottom = new Panel(); Button go = new Button( "Next move" ); go.addActionListener( this ); bottom.add( go ); f.add( center, BorderLayout.CENTER ); f.add( bottom, BorderLayout.SOUTH ); f.pack(); f.setVisible( true ); } public void actionPerformed( ActionEvent e ) { if (instructions.size() == 0) return; LeafMove m = (LeafMove) instructions.remove(0); towers[m.from].moveTo( towers[m.to] ); } } class Tower extends Panel { private int top; public Tower( boolean first, int size ) { setLayout( new GridLayout(size,1) ); if ( ! first ) { Button b; Panel p; for (int i=0; i < size; i++) { b = new Button(); b.setBackground( Color.white ); p = new Panel(); p.add( b ); add( p ); } top = size; return; } Button[] a = new Button[7]; a[0] = new Button( "one" ); a[0].setBackground( Color.red ); a[1] = new Button( " two " ); a[1].setBackground( Color.green ); a[2] = new Button( " three " ); a[2].setBackground( Color.yellow ); a[3] = new Button( " four " ); a[3].setBackground( new Color(120,120,255) ); a[4] = new Button( " five " ); a[4].setBackground( Color.magenta ); a[5] = new Button( " six " ); a[5].setBackground( Color.red ); a[6] = new Button( " seven " ); a[6].setBackground( Color.green ); Panel p; for (int i=0; i < size; i++) { p = new Panel(); p.add( a[i] ); add( p ); } top = 0; } public void moveTo( Tower to ) { to.top--; Component disk = getComponent( top ); remove( top ); Component blank = to.getComponent( to.top ); to.remove( to.top ); add( blank, top ); to.add( disk, to.top ); validate(); to.validate(); top++; } }