Facciamo così: tempo fa scrissi un programma che mi permetteva di disegnare le funzioni su un piano cartesiano. Per farlo avevo accorpato in un unico file .java StdDraw, StdAudio (per far "suonare" le funzionitrigonometriche) e quanto avevo scritto io, sfruttando i metodi delle due librerie (non si chiamano così?) citate. Di seguito l'intero codice che ero solito salvare come "Funzioni.java" per farlo poi elaborare automaticamente a Executable Jar Maker per ottenere Funzioni.Jar ed ottenere a video lo studio della funzione scritta nel codice. Come posso fare per farlo eseguire?
import javax.sound.sampled.*;
import java.net.*;
import java.applet.*;
import java.io.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.util.LinkedList;
public final class Funzioni implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
public static final int SAMPLE_RATE = 44100;
private static final int BYTES_PER_SAMPLE = 2; // 16-bit audio
private static final int BITS_PER_SAMPLE = 16; // 16-bit audio
private static final double MAX_16_BIT = Short.MAX_VALUE; // 32,767
private static final int SAMPLE_BUFFER_SIZE = 4096;
private static SourceDataLine line; // to play the sound
private static byte[] buffer; // our internal buffer
private static int i = 0; // number of samples currently in internal buffer
// pre-defined colors
public static final Color BLACK = Color.BLACK;
public static final Color BLUE = Color.BLUE;
public static final Color CYAN = Color.CYAN;
public static final Color DARK_GRAY = Color.DARK_GRAY;
public static final Color GRAY = Color.GRAY;
public static final Color GREEN = Color.GREEN;
public static final Color LIGHT_GRAY = Color.LIGHT_GRAY;
public static final Color MAGENTA = Color.MAGENTA;
public static final Color ORANGE = Color.ORANGE;
public static final Color PINK = Color.PINK;
public static final Color RED = Color.RED;
public static final Color WHITE = Color.WHITE;
public static final Color YELLOW = Color.YELLOW;
// default colors
private static final Color DEFAULT_PEN_COLOR = BLACK;
private static final Color DEFAULT_CLEAR_COLOR = WHITE;
// current pen color
private static Color penColor;
// default canvas size is SIZE-by-SIZE
private static final int DEFAULT_SIZE = 512;
private static int width = DEFAULT_SIZE;
private static int height = DEFAULT_SIZE;
// default pen radius
private static final double DEFAULT_PEN_RADIUS = 0.002;
// current pen radius
private static double penRadius;
// show we draw immediately or wait until next show?
private static boolean defer = false;
// boundary of drawing canvas, 5% border
private static final double BORDER = 0.05;
private static final double DEFAULT_XMIN = 0.0;
private static final double DEFAULT_XMAX = 1.0;
private static final double DEFAULT_YMIN = 0.0;
private static final double DEFAULT_YMAX = 1.0;
private static double xmin, ymin, xmax, ymax;
// for synchronization
private static Object mouseLock = new Object();
private static Object keyLock = new Object();
// default font
private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 16);
// current font
private static Font font;
// double buffered graphics
private static BufferedImage offscreenImage, onscreenImage;
private static Graphics2D offscreen, onscreen;
// singleton for callbacks: avoids generation of extra .class files
private static Funzioni std = new Funzioni();
// the frame for drawing to the screen
private static JFrame frame;
// mouse state
private static boolean mousePressed = false;
private static double mouseX = 0;
private static double mouseY = 0;
// keyboard state
private static LinkedList<Character> keysTyped = new LinkedList<Character>();
// not instantiable
private Funzioni() { }
// static initializer
static { init(); }
/**
* Set the window size to w-by-h pixels
*
* @param w the width as a number of pixels
* @param h the height as a number of pixels
* @throws a RunTimeException if the width or height is 0 or negative.
*/
public static void setCanvasSize(int w, int h) {
if (w < 1 || h < 1) throw new RuntimeException("width and height must be positive");
width = w;
height = h;
init();
}
// init
private static void init() {
try {
// 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false);
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE);
// the internal buffer is a fraction of the actual buffer size, this choice is arbitrary
// it gets diveded because we can't expect the buffered data to line up exactly with when
// the sound card decides to push out its samples.
buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3];
} catch (Exception e) {
System.out.println(e.getMessage());
System.exit(1);
}
line.start();
if (frame != null) frame.setVisible(false);
frame = new JFrame();
offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
offscreen = offscreenImage.createGraphics();
onscreen = onscreenImage.createGraphics();
setXscale();
setYscale();
offscreen.setColor(DEFAULT_CLEAR_COLOR);
offscreen.fillRect(0, 0, width, height);
setPenColor();
setPenRadius();
setFont();
clear();
// add antialiasing
RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
offscreen.addRenderingHints(hints);
// frame stuff
ImageIcon icon = new ImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(std);
draw.addMouseMotionListener(std);
frame.setContentPane(draw);
frame.addKeyListener(std); // JLabel cannot get keyboard focus
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes all windows
//frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // closes only current window
frame.setTitle("Funzioni");
frame.pack();
frame.requestFocusInWindow();
frame.setVisible(true);
}
// create the menu bar (changed to private)
private static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem1 = new JMenuItem(" Salva con nome");
menuItem1.addActionListener(std);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuItem1);
return menuBar;
}
public static final void close() {
line.drain();
line.stop();
}
public static final void play(double in) {
// clip if outside [-1, +1]
if (in < -1.0) in = -1.0;
if (in > +1.0) in = +1.0;
// convert to bytes
short s = (short) (MAX_16_BIT * in);
buffer[i++] = (byte) s;
buffer[i++] = (byte) (s >> 8); // little Endian
// send to sound card if buffer is full
if (i >= buffer.length) {
line.write(buffer, 0, buffer.length);
i = 0;
}
}
/**
* Write an array of samples (between -1.0 and +1.0) to standard audio. If a sample
* is outside the range, it will be clipped.
*/
public static void play(double[] input) {
for (int i = 0; i < input.length; i++) {
play(input[i]);
}
}
/**
* Read audio samples from a file (in .wav or .au format) and return them as a double array
* with values between -1.0 and +1.0.
*/
public static double[] read(String filename) {
byte[] data = readByte(filename);
int N = data.length;
double[] d = new double[N/2];
for (int i = 0; i < N/2; i++) {
d[i] = ((short) (((data[2*i+1] & 0xFF) << 8) + (data[2*i] & 0xFF))) / ((double) MAX_16_BIT);
}
return d;
}
/**
* Play a sound file (in .wav or .au format) in a background thread.
*/
public static void play(String filename) {
URL url = null;
try {
File fil = new File(filename);
if (fil.canRead()) url = fil.toURI().toURL();
}
catch (MalformedURLException e) { e.printStackTrace(); }
// URL url = Funzioni.class.getResource(filename);
if (url == null) throw new RuntimeException("audio " + filename + " not found");
AudioClip clip = Applet.newAudioClip(url);
clip.play();
}
// return data as a byte array
private static byte[] readByte(String filename) {
byte[] data = null;
AudioInputStream ais = null;
try {
URL url = Funzioni.class.getResource(filename);
ais = AudioSystem.getAudioInputStream(url);
data = new byte[ais.available()];
ais.read(data);
}
catch (Exception e) {
System.out.println(e.getMessage());
throw new RuntimeException("Could not read " + filename);
}
return data;
}
/**
* Save the double array as a sound file (using .wav or .au format).
*/
public static void save(String filename, double[] input) {
// assumes 44,100 samples per second
// use 16-bit audio, mono, signed PCM, little Endian
AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false);
byte[] data = new byte[2 * input.length];
for (int i = 0; i < input.length; i++) {
int temp = (short) (input[i] * MAX_16_BIT);
data[2*i + 0] = (byte) temp;
data[2*i + 1] = (byte) (temp >> 8);
}
// now save the file
try {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
AudioInputStream ais = new AudioInputStream(bais, format, input.length);
if (filename.endsWith(".wav") || filename.endsWith(".WAV")) {
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename));
}
else if (filename.endsWith(".au") || filename.endsWith(".AU")) {
AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename));
}
else {
throw new RuntimeException("File format not supported: " + filename);
}
}
catch (Exception e) {
System.out.println(e);
System.exit(1);
}
}
/***********************************************************************
* sample test client
***********************************************************************/
// create a note (sine wave) of the given frequency (Hz), for the given
// duration (seconds) scaled to the given volume (amplitude)
private static double[] note(double hz, double duration, double amplitude) {
int N = (int) Math.round(SAMPLE_RATE * duration);
double[] tone = new double[N+1];
for (int i = 0; i <= N; i++)
tone[i] = amplitude * Math.sin(2 * Math.PI * i * hz / SAMPLE_RATE);
return tone;
}
/**
* Test client - play an A major scale to standard audio.
// create the menu bar (changed to private)
private static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuItem1 = new JMenuItem(" Salva con nome");
menuItem1.addActionListener(std);
menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuItem1);
return menuBar;
}
/*************************************************************************
* User and screen coordinate systems
*************************************************************************/
/**
* Set the X scale to be the default
*/
public static void setXscale() { setXscale(DEFAULT_XMIN, DEFAULT_XMAX); }
/**
* Set the Y scale to be the default
*/
public static void setYscale() { setYscale(DEFAULT_YMIN, DEFAULT_YMAX); }
/**
* Set the X scale (a border is added to the values)
* @param min the minimum value of the X scale
* @param max the maximum value of the X scale
*/
public static void setXscale(double min, double max) {
double size = max - min;
xmin = min - BORDER * size;
xmax = max + BORDER * size;
}
/**
* Set the Y scale (a border is added to the values)
* @param min the minimum value of the Y scale
* @param max the maximum value of the Y scale
*/
public static void setYscale(double min, double max) {
double size = max - min;
ymin = min - BORDER * size;
ymax = max + BORDER * size;
}
// helper functions that scale from user coordinates to screen coordinates and back
private static double scaleX(double x) { return width * (x - xmin) / (xmax - xmin); }
private static double scaleY(double y) { return height * (ymax - y) / (ymax - ymin); }
private static double factorX(double w) { return w * width / Math.abs(xmax - xmin); }
private static double factorY(double h) { return h * height / Math.abs(ymax - ymin); }
private static double userX(double x) { return xmin + x * (xmax - xmin) / width; }
private static double userY(double y) { return ymax - y * (ymax - ymin) / height; }
/**
* Clear the screen with the default color, white
*/
public static void clear() { clear(DEFAULT_CLEAR_COLOR); }
/**
* Clear the screen with the given color.
* @param color the Color to make the background
*/
public static void clear(Color color) {
offscreen.setColor(color);
offscreen.fillRect(0, 0, width, height);
offscreen.setColor(penColor);
show();
}
/**
* Set the pen size to the default
*/
public static void setPenRadius() { setPenRadius(DEFAULT_PEN_RADIUS); }
/**
* Set the pen size to the given size
* @param r the radius of the pen
* @throws RuntimeException if r is negative
*/
public static void setPenRadius(double r) {
if (r < 0) throw new RuntimeException("pen radius must be positive");
penRadius = r * DEFAULT_SIZE;
// BasicStroke stroke = new BasicStroke((float) penRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
BasicStroke stroke = new BasicStroke((float) penRadius);
offscreen.setStroke(stroke);
}
/**
* Set the pen color to the default which is BLACK.
*/
public static void setPenColor() { setPenColor(DEFAULT_PEN_COLOR); }
/**
* Set the pen color to the given color. The available pen colors are
BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA,
ORANGE, PINK, RED, WHITE, and YELLOW.
* @param color the Color to make the pen
*/
public static void setPenColor(Color color) {
penColor = color;
offscreen.setColor(penColor);
}
/**
* Set the font to be the default for all string writing
*/
public static void setFont() { setFont(DEFAULT_FONT); }
/**
* Set the font as given for all string writing
* @param f the font to make text
*/
public static void setFont(Font f) { font = f; }
/*************************************************************************
* Drawing geometric shapes.
*************************************************************************/
/**
* Draw a line from (x0, y0) to (x1, y1)
* @param x0 the x-coordinate of the starting point
* @param y0 the y-coordinate of the starting point
* @param x1 the x-coordinate of the destination point
* @param y1 the y-coordinate of the destination point
*/
public static void line(double x0, double y0, double x1, double y1) {
offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1)));
show();
}
/**
* Draw one pixel at (x, y)
* @param x the x-coordinate of the pixel
* @param y the y-coordinate of the pixel
*/
public static void pixel(double x, double y) {
offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1);
}
/**
* Draw a point at (x, y)
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
*/
public static void point(double x, double y) {
double xs = scaleX(x);
double ys = scaleY(y);
double r = penRadius;
// double ws = factorX(2*r);
// double hs = factorY(2*r);
// if (ws <= 1 && hs <= 1) pixel(x, y);
if (r <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - r/2, ys - r/2, r, r));
show();
}
/**
* Draw circle of radius r, centered on (x, y); degenerate to pixel if small
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws RuntimeException if the radius of the circle is negative
*/
public static void circle(double x, double y, double r) {
if (r < 0) throw new RuntimeException("circle radius can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
show();
}
/**
* Draw filled circle of radius r, centered on (x, y); degenerate to pixel if small
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @throws RuntimeException if the radius of the circle is negative
*/
public static void filledCircle(double x, double y, double r) {
if (r < 0) throw new RuntimeException("circle radius can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs));
show();
}
/**
* Draw an arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees).
* @param x the x-coordinate of the center of the circle
* @param y the y-coordinate of the center of the circle
* @param r the radius of the circle
* @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock.
* @param angle2 the angle at the end of the arc. For example, if
* you want a 90 degree arc, then angle2 should be angle1 + 90.
* @throws RuntimeException if the radius of the circle is negative
*/
public static void arc(double x, double y, double r, double angle1, double angle2) {
if (r < 0) throw new RuntimeException("arc radius can't be negative");
while (angle2 < angle1) angle2 += 360;
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN));
show();
}
/**
* Draw squared of side length 2r, centered on (x, y); degenerate to pixel if small
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws RuntimeException if r is negative
*/
public static void square(double x, double y, double r) {
if (r < 0) throw new RuntimeException("square side length can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
show();
}
/**
* Draw a filled square of side length 2r, centered on (x, y); degenerate to pixel if small
* @param x the x-coordinate of the center of the square
* @param y the y-coordinate of the center of the square
* @param r radius is half the length of any side of the square
* @throws RuntimeException if r is negative
*/
public static void filledSquare(double x, double y, double r) {
if (r < 0) throw new RuntimeException("square side length can't be negative");
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(2*r);
double hs = factorY(2*r);
if (ws <= 1 && hs <= 1) pixel(x, y);
else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs));
show();
}
/**
* Draw a polygon with the given (x[i], y[i]) coordinates
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void polygon(double[] x, double[] y) {
int N = x.length;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < N; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.draw(path);
show();
}
/**
* Draw a filled polygon with the given (x[i], y[i]) coordinates
* @param x an array of all the x-coordindates of the polygon
* @param y an array of all the y-coordindates of the polygon
*/
public static void filledPolygon(double[] x, double[] y) {
int N = x.length;
GeneralPath path = new GeneralPath();
path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0]));
for (int i = 0; i < N; i++)
path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i]));
path.closePath();
offscreen.fill(path);
show();
}
/*************************************************************************
* Drawing images.
*************************************************************************/
// get an image from the given filename
private static Image getImage(String filename) {
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
} catch (Exception e) { /* not a url */ }
}
// in case file is inside a .jar
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = Funzioni.class.getResource(filename);
if (url == null) throw new RuntimeException("image " + filename + " not found");
icon = new ImageIcon(url);
}
return icon.getImage();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y).
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @throws RuntimeException if the image's width or height are negative
*/
public static void picture(double x, double y, String s) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
int ws = image.getWidth(null);
int hs = image.getHeight(null);
if (ws < 0 || hs < 0) throw new RuntimeException("image " + s + " is corrupt");
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
show();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y),
* rotated given number of degrees
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @param degrees is the number of degrees to rotate counterclockwise
* @throws RuntimeException if the image's width or height are negative
*/
public static void picture(double x, double y, String s, double degrees) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
int ws = image.getWidth(null);
int hs = image.getHeight(null);
if (ws < 0 || hs < 0) throw new RuntimeException("image " + s + " is corrupt");
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
show();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y).
* Rescaled to w-by-h.
* @param x the center x coordinate of the image
* @param y the center y coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @param w the width of the image
* @param h the height of the image
*/
public static void picture(double x, double y, String s, double w, double h) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(w);
double hs = factorY(h);
if (ws < 0 || hs < 0) throw new RuntimeException("image " + s + " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
else {
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
}
show();
}
/**
* Draw picture (gif, jpg, or png) centered on (x, y),
* rotated given number of degrees, rescaled to w-by-h.
* @param x the center x-coordinate of the image
* @param y the center y-coordinate of the image
* @param s the name of the image/picture, e.g., "ball.gif"
* @param w the width of the image
* @param h the height of the image
* @param degrees is the number of degrees to rotate counterclockwise
* @throws RuntimeException if the image's width or height are negative
*/
public static void picture(double x, double y, String s, double w, double h, double degrees) {
Image image = getImage(s);
double xs = scaleX(x);
double ys = scaleY(y);
double ws = factorX(w);
double hs = factorY(h);
if (ws < 0 || hs < 0) throw new RuntimeException("image " + s + " is corrupt");
if (ws <= 1 && hs <= 1) pixel(x, y);
offscreen.rotate(Math.toRadians(-degrees), xs, ys);
offscreen.drawImage(image, (int) Math.round(xs - ws/2.0),
(int) Math.round(ys - hs/2.0),
(int) Math.round(ws),
(int) Math.round(hs), null);
offscreen.rotate(Math.toRadians(+degrees), xs, ys);
show();
}
/*************************************************************************
* Drawing text.
*************************************************************************/
/**
* Write the given text string in the current font, center on (x, y).
* @param x the center x coordinate of the text
* @param y the center y coordinate of the text
* @param s the text
*/
public static void text(double x, double y, String s) {
offscreen.setFont(font);
FontMetrics metrics = offscreen.getFontMetrics();
double xs = scaleX(x);
double ys = scaleY(y);
int ws = metrics.stringWidth(s);
int hs = metrics.getDescent();
offscreen.drawString(s, (float) (xs - ws/2.0), (float) (ys + hs));
show();
}
/**
* Display on screen and pause for t milliseconds.
* Calling this method means that the screen will NOT be redrawn
* after each line(), circle(), or square(). This is useful when there
* are many methods to call to draw a complete picture.
* @param t number of milliseconds
*/
public static void show(int t) {
defer = true;
onscreen.drawImage(offscreenImage, 0, 0, null);
frame.repaint();
try { Thread.currentThread().sleep(t); }
catch (InterruptedException e) { System.out.println("Error sleeping"); }
}
/**
* Display on-screen;
* calling this method means that the screen WILL be redrawn
* after each line(), circle(), or square(). This is the default.
*/
public static void show() {
if (!defer) onscreen.drawImage(offscreenImage, 0, 0, null);
if (!defer) frame.repaint();
}
/*************************************************************************
* Save drawing to a file.
*************************************************************************/
/**
* Save to file - suffix must be png, jpg, or gif.
* @param filename the name of the file with one of the required suffixes
*/
public static void save(String filename) {
File file = new File(filename);
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
// png files
if (suffix.toLowerCase().equals("png")) {
try { ImageIO.write(offscreenImage, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
// need to change from ARGB to RGB for jpeg
// reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
else if (suffix.toLowerCase().equals("jpg")) {
WritableRaster raster = offscreenImage.getRaster();
WritableRaster newRaster;
newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
DirectColorModel cm = (DirectColorModel) offscreenImage.getColorModel();
DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(),
cm.getRedMask(),
cm.getGreenMask(),
cm.getBlueMask());
BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
try { ImageIO.write(rgbBuffer, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
else {
System.out.println("Invalid image file type: " + suffix);
}
}
/**
* Open a save dialog when the user selects "Save As" from the menu
*/
public void actionPerformed(ActionEvent e) {
FileDialog chooser = new FileDialog(Funzioni.frame, "Use a .png or .jpg extension", FileDialog.SAVE);
chooser.setVisible(true);
String filename = chooser.getFile();
if (filename != null) {
Funzioni.save(chooser.getDirectory() + File.separator + chooser.getFile());
}
}
/*************************************************************************
* Mouse interactions.
*************************************************************************/
/**
* Is the mouse being pressed?
* @return true or false
*/
public static boolean mousePressed() {
synchronized (mouseLock) {
return mousePressed;
}
}
/**
* Where is the mouse?
* @return the value of the x-coordinate of the mouse
*/
public static double mouseX() {
synchronized (mouseLock) {
return mouseX;
}
}
/**
* Where is the mouse?
* @return the value of the y-coordinate of the mouse
*/
public static double mouseY() {
synchronized (mouseLock) {
return mouseY;
}
}
public void mouseClicked(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
synchronized (mouseLock) {
mouseX = Funzioni.userX(e.getX());
mouseY = Funzioni.userY(e.getY());
mousePressed = true;
}
}
public void mouseReleased(MouseEvent e) {
synchronized (mouseLock) {
mousePressed = false;
}
}
public void mouseDragged(MouseEvent e) {
synchronized (mouseLock) {
mouseX = Funzioni.userX(e.getX());
mouseY = Funzioni.userY(e.getY());
}
}
public void mouseMoved(MouseEvent e) {
synchronized (mouseLock) {
mouseX = Funzioni.userX(e.getX());
mouseY = Funzioni.userY(e.getY());
}
}
/*************************************************************************
* Keyboard interactions.
*************************************************************************/
/**
* Has the user typed a key?
* @return true if the user has typed a key, false otherwise
*/
public static boolean hasNextKeyTyped() {
synchronized (keyLock) {
return !keysTyped.isEmpty();
}
}
/**
* What is the next key that was typed by the user?
* @return the next key typed
*/
public static char nextKeyTyped() {
synchronized (keyLock) {
return keysTyped.removeLast();
}
}
public void keyTyped(KeyEvent e) {
synchronized (keyLock) {
keysTyped.addFirst(e.getKeyChar());
}
}
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public static void istruzioni(){
Funzioni.setPenColor(Funzioni.BLACK);
Funzioni.text(15,90,"sin x = Math.sin(x)");
Funzioni.text(15,80,"cos x = Math.cos(x)");
Funzioni.text(15,70,"tg x = Math.tan(x)");
Funzioni.text(15,60,"|x| = Math.abs(x)");
Funzioni.text(15,50,"ln x = Math.log(x)");
Funzioni.text(15,40,"radice x = Math.sqrt(x)");
Funzioni.text(15,30,"e^x = Math.pow(e,x)");
Funzioni.text(15,20,"p greco = Math.PI");
Funzioni.setPenColor(Funzioni.GRAY);Funzioni.filledSquare(50,50,8);
Funzioni.setPenColor(Funzioni.LIGHT_GRAY);Funzioni.filledSquare(50,50,7);
Funzioni.setPenColor(Funzioni.BLACK);
Funzioni.text(50,50,"BACK");
}
public static void spec(){
Funzioni.setPenColor(Funzioni.YELLOW);
Funzioni.filledCircle(100*Math.random(),100*Math.random(),10*Math.random());
Funzioni.filledCircle(-100*Math.random(),100*Math.random(),10*Math.random());
Funzioni.filledCircle(100*Math.random(),-100*Math.random(),10*Math.random());
Funzioni.filledCircle(-100*Math.random(),-100*Math.random(),10*Math.random());
}
public static void piano( double tav){
Funzioni.setXscale(-tav,tav);
Funzioni.setYscale(-tav,tav);
}
public static void tasti(){
double x=-9.5;
double cont=13;
while(cont>0){
Funzioni.setPenColor(Funzioni.GRAY);
Funzioni.filledSquare(x,-10.5,0.5);
Funzioni.setPenColor(Funzioni.LIGHT_GRAY);
Funzioni.filledSquare(x,-10.5,0.4);
x=x+1.1;cont=cont-1;
Funzioni.show(1);}
Funzioni.setPenColor(Funzioni.BLACK);
Funzioni.text(-9.5,-10.5,"<>");
Funzioni.text(-8.4,-10.5,"f");
Funzioni.text(-7.3,-10.5,"rad");
Funzioni.text(-6.2,-10.5,"dec");
Funzioni.text(-5.1,-10.5,"| f |");
Funzioni.text(-4.0,-10.5,"1/f");
Funzioni.text(-2.9,-10.5,"-f");
Funzioni.text(-1.8,-10.5,"N");
Funzioni.text(-0.7,-10.5,"aud");
Funzioni.text(0.4,-10.5,"int");
Funzioni.text(1.5,-10.5,"lnf");
Funzioni.text(2.6,-10.5,"leg");
Funzioni.text(3.7,-10.5,"e^f");
Funzioni.show(1); }
public static void grigliarad(){
Funzioni.setPenRadius(0.0005);
Funzioni.setPenColor(Funzioni.BLACK);
int cont1=21;
int cont2=21;
double x=-3*Math.PI;
int y=-10;
while(cont1>0){
Funzioni.line(x,-10,x,10);
x=x+Math.PI/2;
cont1=cont1-1;}
while(cont2>0){
Funzioni.line(-10,y,10,y);
y=y+1;
cont2=cont2-1;}
Funzioni.setPenRadius(0.001);
Funzioni.line(0,-10,0,10);
Funzioni.line(0,10,0.15,9.5);
Funzioni.line(0,10,-0.15,9.5);
Funzioni.text(0.5,10,"Y");
Funzioni.line(-10,0,10,0);
Funzioni.line(10,0,9.5,0.15);
Funzioni.line(10,0,9.5,-0.15);
Funzioni.text(10,-0.5,"X");
Funzioni.show(1);
}
public static void grigliadec(){
Funzioni.setPenRadius(0.0005);
Funzioni.setPenColor(Funzioni.BLACK);
int cont1=21;
int cont2=21;
int x=-10;
int y=-10;
while(cont1>0){
Funzioni.line(x,-10,x,10);
x=x+1;
cont1=cont1-1;
}
while(cont2>0){
Funzioni.line(-10,y,10,y);
y=y+1;
cont2=cont2-1;
}
Funzioni.setPenRadius(0.001);
Funzioni.line(0,-10,0,10);
Funzioni.line(0,10,0.15,9.5);
Funzioni.line(0,10,-0.15,9.5);
Funzioni.text(0.5,10,"Y");
Funzioni.line(-10,0,10,0);
Funzioni.line(10,0,9.5,0.15);
Funzioni.line(10,0,9.5,-0.15);
Funzioni.text(10,-0.5,"X");
Funzioni.show(1);
}
public static void funzione (double man){
double e=2.718281828;
Funzioni.setPenColor(Funzioni.RED);
//intervallo
//default a=-11 b=11
double a=-11;
double b=11;
double count=a;
double n=0.001;
double point=0.03;
double x=a;
double y=-100000;
double y2=-100000;
while(count<b){
if(man==4){n=1;point=0.1;}
Funzioni.filledCircle(0+x,0+y,point);
Funzioni.filledCircle(0+x,0+y2,point);
x=x+n;
//funzione
y=x*x+2*x+1;
//funzione2
if(man==13){Funzioni.setPenColor(Funzioni.MAGENTA);y=Math.pow(e,y);}
if(man==12){Funzioni.setPenColor(Funzioni.ORANGE);y=Math.log(y)/Math.log(e);}
if(man==7){Funzioni.setPenColor(Funzioni.ORANGE);y=y*Math.random();}
if(man==1){Funzioni.setPenColor(Funzioni.BLUE);y=Math.abs(y);}
if(man==6){Funzioni.play(y);}
if(man==2){Funzioni.setPenColor(Funzioni.BLACK);y=1/y;}
if(man==3){Funzioni.setPenColor(Funzioni.GREEN);y=-y;}
count=count+0.001;
} Funzioni.show(1);
Funzioni.setPenColor(Funzioni.BLACK);
}
public static void main(String args[]){
double X; double Y;
Funzioni.piano(10); Funzioni.grigliadec();
Funzioni.funzione(0);
Funzioni.tasti();
while(true){
if(Funzioni.mousePressed()){
X=Funzioni.mouseX();
Y=Funzioni.mouseY();
Funzioni.setPenColor(Funzioni.BLACK);
Funzioni.filledCircle(X,Y,0.1);
if(X>-10 && X<-9 && Y>-11 && Y<-10){
Funzioni.setPenColor(Funzioni.WHITE);
Funzioni.filledSquare(0,0,1000);
Funzioni.piano(100); Funzioni.grigliadec();
Funzioni.funzione(0);}
Funzioni.setPenColor(Funzioni.GRAY);
Funzioni.filledSquare(-95,-105,5);
Funzioni.setPenColor(Funzioni.LIGHT_GRAY);
Funzioni.filledSquare(-95,-105,4);
Funzioni.setPenColor(Funzioni.BLACK);
Funzioni.text(-95,-105,"><");
if(X>-100 && X<-90 && Y>-110 && Y<-100){
Funzioni.setPenColor(Funzioni.WHITE);
Funzioni.filledSquare(0,0,1000);
Funzioni.piano(10); Funzioni.grigliadec();
Funzioni.funzione(0); Funzioni.tasti();}
if(X>-8 && X<-7 && Y>-11 && Y<-10){
Funzioni.setPenColor(Funzioni.WHITE);
Funzioni.filledSquare(0,0,1000);
Funzioni.piano(10); Funzioni.grigliarad();
Funzioni.tasti();}
if(X>-6.5 && X<-5.5 && Y>-11 && Y<-10){
Funzioni.setPenColor(Funzioni.WHITE);
Funzioni.filledSquare(0,0,1000);
Funzioni.piano(10);Funzioni.grigliadec();
Funzioni.tasti();
}
if(X>42 && X<58 && Y>42 && Y<58){Funzioni.piano(10); Funzioni.setPenColor(Funzioni.WHITE);
Funzioni.filledSquare(0,0,1000);Funzioni.grigliadec(); Funzioni.tasti();Funzioni.funzione(0);}
if(X>2.2 && X<3.1 && Y>-11 && Y<-10){ Funzioni.setXscale(0,100);
Funzioni.setYscale(0,100); Funzioni.setPenColor(Funzioni.WHITE);
Funzioni.filledSquare(0,0,1000);Funzioni.istruzioni();}
if(X>1.1 && X<2.1 && Y>-11 && Y<-10){ Funzioni.tasti();Funzioni.funzione(12);}
if(X>0 && X<1 && Y>-11 && Y<-10){ Funzioni.tasti();Funzioni.funzione(7);}
if(X>-9 && X<-8 && Y>-11 && Y<-10){ Funzioni.tasti();Funzioni.funzione(0);}
if(X>-5.3 && X<-4.3 && Y>-11 && Y<-10){ Funzioni.tasti();Funzioni.funzione(1);}
if(X>-4.2 && X<-3.2 && Y>-11 && Y<-10){ Funzioni.tasti();Funzioni.funzione(2);}
if(X>3.3 && X<4.3 && Y>-11 && Y<-10){Funzioni.tasti();Funzioni.funzione(13);}
if(X>-3.2 && X<-2.2 && Y>-11 && Y<-10){ Funzioni.tasti();Funzioni.funzione(3);}
if(X>-2.1 && X<-1.1 && Y>-11 && Y<-10){
Funzioni.tasti();Funzioni.funzione(4);}
if(X>-1.1 && X<-0.1 && Y>-11 && Y<-10){
Funzioni.tasti();Funzioni.funzione(6);
}
if(X>109 && X<110 && Y>109 && Y<110){
Funzioni.spec();
}
Funzioni.show(1);}}}
}