Last active
April 22, 2019 20:55
-
-
Save ahmednasserpro/11c6e61835bb2e0f72e2405334ccc6b7 to your computer and use it in GitHub Desktop.
13.11 (Plot the square function) Write a program that draws a diagram for the function f(x) = x2 (see Figure 13.29c).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* *13.11 (Plot the square function) Write a program that draws a diagram for the function | |
* f(x) = x2 (see Figure 13.29c). | |
* | |
* Hint: Add points to a polygon p using the following loop: | |
* | |
* double scaleFactor = 0.1; | |
* for (int x = -100; x <= 100; x++) { | |
* p.addPoint(x + 200, 200 - (int)(scaleFactor * x * x)); | |
* } | |
* | |
* Connect the points using g.drawPolyline(p.xpoints, p.ypoints, | |
* p.npoints) for a Graphics object g. p.xpoints returns an array of xcoordinates, | |
* p.ypoints an array of y-coordinates, and p.npoints the number | |
* of points in Polygon object p. | |
*/ | |
import java.awt.*; | |
import javax.swing.*; | |
public class Test extends JFrame { | |
public Test() { | |
setLayout(new BorderLayout()); | |
add(new MyPanel(), BorderLayout.CENTER); | |
} | |
public static void main(String[] args) { | |
JFrame frame = new Test(); | |
frame.setSize(400, 300); | |
frame.setTitle("Exercise13_10"); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.setLocationRelativeTo(null); // Center the frame | |
frame.setVisible(true); | |
} | |
} | |
class MyPanel extends JPanel { | |
@Override | |
protected void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
// Draw lines | |
g.drawLine(10, 240, 380, 240); | |
g.drawLine(200, 10, 200, 300); | |
// Create polygon for adding points | |
Polygon p = new Polygon(); | |
double scaleFactor = 0.1; | |
for (int x = -100; x <= 100; x++) | |
p.addPoint(x + 200, 200 - (int)(scaleFactor * x * x / 10) + 40); | |
g.drawPolyline(p.xpoints, p.ypoints, p.npoints); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment