1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CurveExemple implements ActionListener {
private JPanel p;
private final int width = 400;
private final int height = 400;
private final int echelle = 2;
public static void main(final String[] args) {
new CurveExemple();
}
public CurveExemple() {
JFrame f = new JFrame();
p = new JPanel();
JButton b = new JButton("draw");
b.addActionListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(p, BorderLayout.CENTER);
f.getContentPane().add(b, BorderLayout.SOUTH);
p.setPreferredSize(new Dimension(width, height));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private double getPoint(final double x) {
double y = x * x;
return y;
}
private Map<Double, Double> getCurve(final double begin, final double end, final double step) {
Map<Double, Double> map = new LinkedHashMap<Double, Double>();
for (double x = begin; x <= end; x = x + step) {
double y = getPoint(x);
map.put(x, y);
}
return map;
}
private void drawCurve(final Map<Double, Double> map, final Graphics g) {
int ox = width / 2;
int oy = height / 2;
g.translate(ox, oy);
g.setColor(Color.BLACK);
g.drawLine(-ox, 0, ox, 0);
g.drawLine(0, -oy, 0, oy);
g.setColor(Color.BLUE);
Set<Double> keys = map.keySet();
Double lastX = null;
Double lastY = null;
for (Double key : keys) {
Double value = map.get(key);
if (lastX != null && lastY != null) {
g.drawLine(lastX.intValue() * echelle, lastY.intValue() * -1 * echelle,
key.intValue() * echelle, value.intValue() * -1 * echelle);
}
lastX = key;
lastY = value;
}
}
private final void showPoints(final Map<Double, Double> map) {
Set<Double> keys = map.keySet();
for (Double key : keys) {
Double value = map.get(key);
System.out.println("x=" + key + ", y=" + value);
}
}
@Override
public void actionPerformed(final ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
public void run() {
Graphics g = p.getGraphics();
Map<Double, Double> map = getCurve(-8, 8, 1);
showPoints(map);
drawCurve(map, g);
}
});
}
} |
Partager