import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;

public class EggFrame2 extends JFrame {
	public static void main(String args[]) {
		System.out.println("Starting EggFrame...");
		EggFrame2 mainFrame = new EggFrame2();
		mainFrame.setSize(200, 200);
		mainFrame.setTitle("EggFrame");
		mainFrame.show();
	}
	
	public EggFrame2() {
		addWindowListener(new MyWindowListener());		
		getContentPane().add(new Pannello(), "Center");
	}
	
	private class MyWindowListener extends WindowAdapter {
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}
	}
}

class Pannello extends JPanel {
	public Pannello() {
		setLayout(new BorderLayout());
		egg = new Ellipse2D.Double(0, 0, EGG_WIDTH, EGG_HEIGHT);
				
		MyMouseInputListener listener = new MyMouseInputListener();
		addMouseListener(listener);
		addMouseMotionListener(listener);
				
		textField = new JTextField();
		textField.addActionListener(new MyActionListener());
		add(textField, "South");		
	}
	
	public void paintComponent(Graphics g) {	
		super.paintComponent(g);
		Graphics2D g2 = (Graphics2D)g;
		int w = this.getWidth();
		int h = this.getHeight();
		g2.fill(egg);
		textField.setText("");
		textField.setText("x="+egg.x+" y="+egg.y);
	}

	private Ellipse2D.Double egg;
	private static final double EGG_WIDTH = 20, EGG_HEIGHT = 35;
	private JTextField textField;
	
	private class MyMouseInputListener extends MouseAdapter implements MouseMotionListener {
		private double mouseX, mouseY;
		public void mousePressed(MouseEvent event) {
			mouseX = event.getX();
			mouseY = event.getY();
		}
		public void mouseDragged(MouseEvent event) {
			int currMouseX = event.getX();
			int currMouseY = event.getY();
			if(egg.contains(mouseX, mouseY)) { //test su mouseX e mouseY !!!
				egg.x += currMouseX - mouseX;
				egg.y += currMouseY - mouseY;
				mouseX = currMouseX;
				mouseY = currMouseY;
				repaint();
			}
		}
		public void mouseMoved(MouseEvent e) {}
	}
	
	private class MyActionListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			StringTokenizer parser = new StringTokenizer(textField.getText(), " XxYy=");
			textField.setText("");
			try {
				double x = Double.parseDouble(parser.nextToken(" Xx="));
				double y = Double.parseDouble(parser.nextToken(" Yy="));
				if(!parser.hasMoreTokens()) {
					egg.x = x;
					egg.y = y;
					repaint();
				}
			}
			catch(NoSuchElementException e) {
			}
			catch(NumberFormatException e) {
			}			
		}
	}
}


Questa la bacheca di Informatica Grafica, corso di laurea specialistica in Ing. Edile-architettura
by FdA
ultima modifica: 02/02/2005 11.30