Created
December 19, 2013 03:57
-
-
Save jrichardsz/8034191 to your computer and use it in GitHub Desktop.
Efecto seleccion de rectangular con el mouse / Select images by using a rectangular area. NOTA: Si se pone una imagen como fondo en el jpanel + un listener mouseDragged, se podra obtener la seleccion de una porcion de la imagen. Fuente:
http://www.daniweb.com/software-development/java/threads/342036/how-to-select-images-by-using-a-rectangular-area…
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
import java.awt.BorderLayout; | |
import java.awt.Graphics; | |
import java.awt.Graphics2D; | |
import java.awt.Point; | |
import java.awt.Rectangle; | |
import java.awt.event.MouseEvent; | |
import java.awt.event.MouseListener; | |
import java.awt.event.MouseMotionListener; | |
import javax.swing.JPanel; | |
public class SelectionDemo extends javax.swing.JFrame { | |
public SelectionDemo() { | |
initComponents(); | |
add(new DrawingPanel(),BorderLayout.CENTER); | |
setSize(500,500); | |
} | |
class DrawingPanel extends JPanel implements MouseMotionListener, MouseListener{ | |
Rectangle selection; | |
Point anchor; | |
public DrawingPanel(){ | |
addMouseListener(this); | |
addMouseMotionListener(this); | |
} | |
@Override | |
protected void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
if (selection!=null){ | |
Graphics2D g2d = (Graphics2D)g; | |
g2d.draw(selection); | |
} | |
} | |
public void mousePressed(MouseEvent e) { | |
anchor = e.getPoint(); | |
selection = new Rectangle(anchor); | |
} | |
public void mouseDragged(MouseEvent e) { | |
selection.setBounds( (int)Math.min(anchor.x,e.getX()), (int)Math.min(anchor.y,e.getY()), | |
(int)Math.abs(e.getX()-anchor.x), (int)Math.abs(e.getY()-anchor.y)); | |
repaint(); | |
} | |
public void mouseReleased(MouseEvent e) { | |
selection = null; | |
repaint(); | |
} | |
// unused | |
public void mouseMoved(MouseEvent e) {} | |
public void mouseClicked(MouseEvent e) {} | |
public void mouseEntered(MouseEvent e) {} | |
public void mouseExited(MouseEvent e) {} | |
} | |
private void initComponents() { | |
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); | |
pack(); | |
} | |
public static void main(String args[]) { | |
java.awt.EventQueue.invokeLater(new Runnable() { | |
public void run() { | |
new SelectionDemo().setVisible(true); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment