Gradient of Hypotenuse

This is a solution to the triangle class on the events assignment.

It prints a right angle triangle with scrollers to control the height and width. It calculates the gradient of the hypotenuse as the triangle changes.

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class RightTriangle extends Applet implements AdjustmentListener
{

int vertical=50, horizontal=50;
double gradient, dhorizontal, dvertical;
String slope;
Scrollbar height, base;
Label heightLabel, baseLabel;
Image don;
public void init()
{

// Initialize the components. Place these in the window
// ready to use.
heightLabel = new Label("Change height");
add(heightLabel);
height = new Scrollbar(Scrollbar.VERTICAL, 50, 0, 1, 101);
add (height);
height.addAdjustmentListener(this);
baseLabel = new Label("Change base");
add(baseLabel);
base = new Scrollbar(Scrollbar.HORIZONTAL,50, 0, 1, 101);
add (base);
base.addAdjustmentListener(this);
don=getImage(getDocumentBase(), "wall.jpg");

}
public void paint (Graphics g)
{

// Paint method draws the triangle and text on the screen
// including a background image

g.drawImage(don,0,0,this);
g.setColor(Color.white);
g.drawLine(150, 200, (150+horizontal), 200);
g.drawLine((150+horizontal),200,(150+horizontal),(200-vertical));
g.drawLine((150+horizontal),(200-vertical),150,200);
g.drawString("Height = "+(vertical), (160+horizontal), (200-vertical/2));
g.drawString("Base = "+horizontal, 130+horizontal/2, 220);
calcSlope(horizontal,vertical);
g.drawString("Gradient = "+ slope, 20+horizontal, 200-vertical/2);

}
public void adjustmentValueChanged(AdjustmentEvent event)
{

// A method to listen for the changes to the scrollers
// and put these changes into variables.

horizontal=base.getValue();
vertical=height.getValue();
// Repaint the screen each time.
repaint();

}
private void calcSlope(double horizontal,double vertical)
{

// A method to calculate the slope and convert it to
// a suitable string for display. pass horizontal and
// vertical in as doubles to get a double for the slope

gradient = vertical/horizontal;
slope = Double.toString(gradient);
slope = slope.substring(0,3);

}

}

This is the output:

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License