//RandomLines.java import java.awt.*; import java.awt.event.*; //**ActionListener interface import javax.swing.*; public class RandomLines extends JApplet implements ActionListener { //** JLabel linesLabel, equalLengthLabel, maxLengthLabel; JTextField linesField, equalLengthField, maxLengthField; JButton againButton; public void init() { //sets up the GUI //**represents contents of applet area: Container container = getContentPane(); //**widgets laid out left to right in order added: container.setLayout( new FlowLayout() ); //**create a JLabel object: linesLabel = new JLabel( "Number of lines" ); //**add it to the applet contents: container.add( linesLabel ); //**create a JTextField object: linesField = new JTextField( 4 ); //length in chars container.add( linesField ); equalLengthLabel = new JLabel( "All equal length?" ); container.add( equalLengthLabel ); equalLengthField = new JTextField( "no",4 ); //default value container.add( equalLengthField ); maxLengthLabel = new JLabel( "Max. length" ); container.add( maxLengthLabel ); maxLengthField = new JTextField( 4 ); container.add( maxLengthField ); //create a JButton object: againButton = new JButton( "Again! Again!" ); container.add( againButton ); //**press of button event will be handled by this applet: //**"register" the event handler againButton.addActionListener( this ); } //**required method if implementing ActionListener. //**automatically called upon certain actions (events) that have //been registered by .addActionListener(this) public void actionPerformed( ActionEvent event ) { //**check if source of the event is our JButton: if ( event.getSource() == againButton ) repaint(); //**calls paint //could do other code but this is all that is needed for this program } public void paint( Graphics g ) { int x1, y1, x2, y2; double angle; int lines; int length; int maxLength; boolean equalLengthLines; //** clears applet area. also displays the GUI components. super.paint( g ); //random point (x1,y1) then random point in circle of maxLength radius //around it //**get the string text of a JTextField object length = Integer.parseInt(maxLengthField.getText()); maxLength = Integer.parseInt(maxLengthField.getText()); lines = Integer.parseInt(linesField.getText()); if (equalLengthField.getText().equals("yes")) equalLengthLines = true; else equalLengthLines = false; for (int i=1; i<=lines; i++) { //random point x1 = (int)(Math.random() * getWidth()); y1 = (int)(Math.random() * getHeight()); //random angle angle = Math.random() * 2 * Math.PI; //radians if (!equalLengthLines) //random length length = (int)(Math.random() * maxLength); //other endpoint is angle degrees x2 = (int)(Math.cos(angle) * length + x1); y2 = (int)(Math.sin(angle) * length + y1); g.drawLine(x1,y1,x2,y2); } /* //test if draws to edge or draws nothing //draws to edges! g.drawLine(10,10,-10,-10); g.drawLine(700,100,900,100); */ } }