/* * @(#)Implicitgrapher.java 1.0 02/04/16 * Graphs an implicit relation in a * */ import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; import javax.swing.event.*; public class Implicitgrapher extends Applet implements ActionListener, ChangeListener{ // Button draw; Panel graph; TextField kField; static JSlider s; public static double k; //====================== // Function to graph... //====================== double f(double x, double y){ return x * x + 2000. * Math.cos( k * (x + y) ) + y * y - 5000.; } //========================== //Applet's init function.... //========================== public void init() { setLayout(null); // draw = new Button("Draw It"); // draw.setBounds( 0, 0, 100, 20); // draw.addActionListener(this); // add(draw); graph = new Panel(); graph.setBounds( 20, 50, 200, 200); graph.setBackground(Color.yellow); add(graph); kField=new TextField(); kField.setBounds( 100, 0, 100, 20); kField.addActionListener(this); add(kField); s = new JSlider(5000, 8000, 6280); s.setBounds(20, 250, 200, 20); s.addChangeListener(this); add(s); } public void actionPerformed(ActionEvent e){ //graph.setBackground(Color.white); try { k=Double.parseDouble(kField.getText()); } catch (Exception ex) { k=0; kField.setText(String.valueOf(k)); } Graphit(); } public void Graphit(){ Graphics g = graph.getGraphics(); // erase the graph... g.setColor(Color.yellow); g.fillRect( 0, 0, graph.getWidth(), graph.getHeight()); g.setColor(Color.black); g.translate(100, 100); // draw axes... g.drawLine(-100, 0, 100, 0); g.drawLine( 0, -100, 0, 100); // sketch the graph... double t = 0,v; g.setColor(Color.blue); for(double x = -100;x <= 100;x++) for(double y = -100;y <= 100;y++){ v = f(x,y); if (t * v < 0) g.drawLine((int)x, (int)y, (int)x, (int)y); t = v; } for(double y = -100;y <= 100;y++) for(double x = -100;x <= 100;x++){ v = f(x,y); if (t * v < 0) g.drawLine((int)x, (int)y, (int)x, (int)y); t = v; } }// actionperformed() public void paint(Graphics g) { super.paint(g); g.drawString("x^2 + cos(k*(x - y)) + y^2 = 1", 50, 40 ); g.drawString("k =", 77, 15); } public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); // if (!source.getValueIsAdjusting()) { k= (double) source.getValue()/1000.; kField.setText(String.valueOf(k)); Graphit(); } public static void main(String[] args){ // runs this applet in a window (frame)... Frame window = new Frame("Implicit Grapher"); Implicitgrapher a= new Implicitgrapher(); window.add(a); window.setSize(250,300); // anon. inner class to make exit work... window.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); a.init(); a.start(); window.show();// displays the applet s.requestFocus(); } }