LA CLASE PRINCIPAL
Código:
package ejercicio210;
import javax.swing.JFrame;
public class Ejercicio210 {
public static void main(String[] args) {
JFrame ventana = new JFrame("Panel de dibujo");
Panel panel = new Panel();
ventana.add(panel);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ventana.setSize(300,300);
ventana.setResizable(false);
ventana.setVisible(true);
}
}
LA CLASE PANEL(LA PIZARRA)
Código:
package ejercicio210;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Graphics;
public class Panel extends JPanel {
private JLabel etiquetaInferior;
private JPanel panelInferior;
private Linea linea;
private Linea lineasDibujadas[] = new Linea[100];
private int contadorLineas = 0;
public Panel(){
setLayout(new BorderLayout());
setBackground(Color.WHITE);
panelInferior = new JPanel();
etiquetaInferior = new JLabel("Puntero fuera del panel");
panelInferior.setLayout(new BorderLayout());
panelInferior.add(etiquetaInferior,BorderLayout.WEST);
add(panelInferior,BorderLayout.SOUTH);
addMouseListener(new EventoMouse());
addMouseMotionListener(new EventoMouse());
}
private class EventoMouse extends MouseAdapter implements MouseMotionListener {
public void mousePressed(MouseEvent evento){
linea = new Linea(evento.getX(),evento.getY(),evento.getX(),evento.getY());
repaint();
}
public void mouseDragged(MouseEvent evento){
linea.setFinalX(evento.getX());
linea.setFinalY(evento.getY());
etiquetaInferior.setText(String.format("%d,%d",evento.getX(),evento.getY()));
repaint();
}
public void mouseReleased(MouseEvent evento){
lineasDibujadas[contadorLineas] = linea;
contadorLineas++;
repaint();
}
public void mouseMoved(MouseEvent evento){
etiquetaInferior.setText(String.format("%d,%d",evento.getX(),evento.getY()));
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i=0; i<contadorLineas; i++){
lineasDibujadas[i].dibujar(g);
}
}
}
LA CLASE LINEA
Código:
package ejercicio210;
import java.awt.Graphics;
public class Linea {
private int origenX;
private int origenY;
private int finalX;
private int finalY;
public Linea(int origenX, int origenY, int finalX, int finalY){
this.origenX = origenX;
this.origenY = origenY;
this.finalX = finalX;
this.finalY = finalY;
}
public void setFinalX(int finalX){
this.finalX = finalX;
}
public void setFinalY(int finalY){
this.finalY = finalY;
}
public void dibujar(Graphics g){
g.drawLine(origenX,origenY,finalX,finalY);
}
}