// Triptych.java //adapted from Deitel import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Triptych extends JApplet { private JPanel buttonPanel; private CustomPanel[] myPanels; private JButton circleButton, squareButton; private JLabel infoLabel; public void init() { infoLabel = new JLabel( "Triptych Randomis" ); myPanels = new CustomPanel[3]; JPanel myPanelsPanel = new JPanel(); myPanelsPanel.setLayout( new GridLayout(1,3, 4,4) ); for (int i=0; i<3; i++) { myPanels[i] = new CustomPanel(); myPanels[i].setBackground( new Color( (int)(Math.random()*256), (int)(Math.random()*256), (int)(Math.random()*256) )); myPanelsPanel.add( myPanels[i] ); } // set up squareButton squareButton = new JButton( "Square" ); squareButton.addActionListener( new ActionListener() { // anonymous inner class // draw a square public void actionPerformed( ActionEvent event ) { myPanels[(int)(Math.random()*3)].draw( CustomPanel.SQUARE ); } } // end anonymous inner class ); // end call to addActionListener circleButton = new JButton( "Circle" ); circleButton.addActionListener( new ActionListener() { // anonymous inner class // draw a circle public void actionPerformed( ActionEvent event ) { myPanels[(int)(Math.random()*3)].draw( CustomPanel.CIRCLE ); } } // end anonymous inner class ); // end call to addActionListener // set up panel containing buttons buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, 2 ) ); buttonPanel.add( circleButton ); buttonPanel.add( squareButton ); // attach button panel & custom drawing area to content pane Container container = getContentPane(); container.add( infoLabel, BorderLayout.NORTH ); container.add( myPanelsPanel, BorderLayout.CENTER ); container.add( buttonPanel, BorderLayout.SOUTH ); } } class CustomPanel extends JPanel { public final static int CIRCLE = 1, SQUARE = 2; private int shape; // use shape to draw an oval or rectangle public void paintComponent( Graphics g ) { super.paintComponent( g ); int w=getWidth(); int h=getHeight(); for (int i=1; i<100; i++) g.drawLine((int)(Math.random()*w-w/4), (int)(Math.random()*h-h/4), (int)(Math.random()*w+w/4), (int)(Math.random()*h+h/4)); if ( shape == CIRCLE ) g.fillOval( 50, 10, 60, 60 ); else if ( shape == SQUARE ) g.fillRect( 50, 10, 60, 60 ); } // set shape value and repaint CustomPanel public void draw( int shapeToDraw ) { shape = shapeToDraw; repaint(); } } // end class CustomPanel