Search code examples
javagraphicsappletawt

How to output a Java Applet using Graphics library?


I am trying to output a math function, but I cannot figure out how to call my class that draws/calculates the function.

In the main class, I've tried the following

public class GraphingProgram {

public static void main(String[] args) 
{

        Applet program = new Applet();
        program.setSize(300, 400);
        program.setName("Graphing Program");

        GraphApplet testFunction = new GraphApplet();
        program.add(testFunction);
        program.setVisible(true);    
}   

Class code

public class GraphApplet extends Applet
{

  double f(double x)
    {
    return (Math.cos(x/5) + Math.sin(x/7) + 2) * getSize().height/ 4;              
    }
  public void paint (Graphics g)
    {
        for(int x = 0; x< getSize().width; x++)
        g.drawLine(x, (int) f(x), x+1, (int) f(x+1));
    }
  public String getAppletInfo()
    {
        return "Draw a function graph";
    }

 }

When executing the program, we should expect to see the graph of the function of the class. For example, I should be able to out put the graph f(x) = cos(x/5) + sin(x/7) + 2 on a given interval as shown bellow

!https://i.sstatic.net/rQX5m.png


Solution

  • In NetBeansIDE 8.2, I had to simply press F6 while in the GraphApplet class to output the graph.