I have post this question before also but this time I have added only required and necessary code only although the code is somewhat lengthy.
I want to load image in Jlabel and then after change image when user clicks next button. And when user want to move or scale image he can just easily do it by selecting image edges but it's not working.
All problem are solved except the scaling and moving image.
my code :
public class CopyOfPictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
JPanel panel = new JPanel();
public CopyOfPictureEditor()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
e.printStackTrace();
}
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu(" File ");
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
JButton NEXT = new JButton("");
NEXT.setToolTipText("Next Image");
Image imgn = null;
try
{
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}catch (IOException e) {
e.printStackTrace();
}
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
setJMenuBar(menubar);
menubar.add(toolsmenu);
panel.add(label,BorderLayout.CENTER);
add(panel);
setTitle("Aero Picture Editor");
setVisible(true);
setPreferredSize(getPreferredSize());
setLocation(0,0);
label.addMouseListenet(new MouseHandler());
label.addMouseMotionListenet(new MouseHandler());
}
public Stack<File> getFilesInFolder(String startPath){
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
for (File file : startFolder.listFiles()) {
extension = "";
dotindex = file.getName().lastIndexOf('.');
if (dotindex > 0) {
extension = file.getName().substring(dotindex + 1);
for (String filetype : validpicturetypes){
if (extension.equals(filetype)) {
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage() {
String p;
File f;
try{
f= pictures.pop().getAbsoluteFile();
a=ImageIO.read(f);
p = f.getPath();
System.out.println(p);
} catch (IOException e1) {
e1.printStackTrace();
}
ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
protected void paintComponent(Graphics g)
{
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g.create();
int x = (getWidth() - a.getWidth()) / 2;
int y = (getHeight() - a.getHeight()) / 2;
AffineTransform at = new AffineTransform();
at.translate(x, y);
g2d.setTransform(at);
g2d.drawImage(a, 0, 0, this);
g2d.dispose();
}
public enum MouseAction {
Move(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)),
ResizeSouth(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)),
ResizeNorth(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)),
ResizeEast(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)),
ResizeWest(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)),
ResizeNorthEast(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR)),
ResizeNorthWest(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR)),
ResizeSouthEast(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)),
ResizeSouthWest(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
private Cursor cursor;
private MouseAction(Cursor cursor) {
this.cursor = cursor;
}
public Cursor getCursor() {
return cursor;
}
}
public class MouseHandler extends MouseAdapter
{
private MouseAction action;
private Point clickPoint;
private boolean ignoreMoves;
protected void updateAction(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int width = getWidth();
int height = getHeight();
if (x < 10 && y < 10) {
action = MouseAction.ResizeNorthWest;
} else if (x > width - 10 && y < 10) {
action = MouseAction.ResizeNorthWest;
} else if (y < 10) {
action = MouseAction.ResizeNorth;
} else if (x < 10 && y > height - 10) {
action = MouseAction.ResizeSouthWest;
} else if (x > width - 10 && y > height - 10) {
action = MouseAction.ResizeSouthEast;
} else if (y > height - 10) {
action = MouseAction.ResizeSouth;
} else if (x < 10) {
action = MouseAction.ResizeWest;
} else if (x > width - 10) {
action = MouseAction.ResizeEast;
} else {
action = MouseAction.Move;
} setCursor(action.getCursor());
}
#Override
public void mouseMoved(MouseEvent e) {
if (!ignoreMoves)
{
updateAction(e);
}
}
#Override
public void mousePressed(MouseEvent e) {
updateAction(e);
ignoreMoves = true;
clickPoint = e.getPoint();
repaint();
System.out.println(e.getX());
System.out.println(e.getY());*/
}
#Override
public void mouseReleased(MouseEvent e) {
clickPoint = null;
ignoreMoves = false;
}
#Override
public void mouseDragged(MouseEvent e) {
switch (action) {
case Move: {
Point p = e.getPoint();
p.x -= clickPoint.x;
p=SwingUtilities.convertPoint(label, p, null);
setLocation(p);
}
break;
case ResizeWest: {
Point p = e.getPoint();
int xDelta = p.x - clickPoint.x;
int width = getWidth() - xDelta;
int x = getX() + xDelta;
setSize(width, getHeight());
setLocation(x, getY());
revalidate();
}
break;
case ResizeEast: {
Point p = e.getPoint();
int xDelta = p.x - clickPoint.x;
int width = getWidth() + xDelta;
setSize(width, getHeight());
revalidate();
clickPoint = p;
}
break;
case ResizeNorth: {
Point p = e.getPoint();
int yDelta = p.y - clickPoint.y;
int height = getHeight() - yDelta;
int y = getY() + yDelta;
setSize(getWidth(), height);
setLocation(getX(), y);
revalidate();
}
break;
case ResizeSouth: {
Point p = e.getPoint();
int yDelta = p.y - clickPoint.y;
int height = getHeight() + yDelta;
setSize(getWidth(), height);
revalidate();
clickPoint = p;
}
break;
}
}
#Override
public void mouseExited(MouseEvent e)
{
}
}
}
Found this one:
label.addMouseListener(new MouseHandler());
label.addMouseMotionListener(new MouseHandler());
Since you set your clickPoint in mousePressed and want to have it in mouseDragged, it should be the same object. You should actually get some nullpointers in mouseDragged?
Hard to see without complete code, but for one, you're calling setSize and setLocation on the Window itself in your MouseDragged method. If you want to get the object the user clicked on you need to get it from e.getSource(), like:
public void mouseDragged(MouseEvent e){
JLabel l = (JLabel)e.getSource();
switch(action){
case ResizeWest:
Point p = e.getPoint();
int xDelta = p.x - clickPoint.x;
int width = getWidth() - xDelta;
int x = getX() + xDelta;
l.setSize(width, getHeight()); // call setSize on JLabel l
l.setLocation(x, getY());
l.revalidate();
break;
}
Incidentally, why are you using a JLabel for this? I would use a Java object that draws itself onto the JFrame using the JFrame's graphics context.
Related
The program is supposed to make a grid where all rectangles start black and if clicked or dragged they turn white. So far my program is able to make the rectangle you click or drag white, but it doesn't memorize or remember which one I clicked to make them stay white until you click them again. Maybe I would call the change using the mouse listener or maybe by creating an LinkedList , I just can't figure out the easiest solution.
public class Clicky extends JFrame {
private static class Board extends JPanel {
private double BRICK_WIDTH = 20;
private double BRICK_HEIGHT = 20;
public Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public double width = screenSize.getWidth();
public double height = screenSize.getHeight();
private int COLS = (int)(width/BRICK_WIDTH);
private int ROWS =(int)(height/BRICK_HEIGHT);
private Color CO = Color.BLACK;
public Board() {
System.out.println("WIdth:" + COLS + "Height:" + ROWS);
setBackground(Color.BLACK);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
System.out.printf("X: %d Y: %d ", mx, my);
repaint();
}
});
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
mx = e.getX();
my = e.getY();
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBricks(g);
}
private double x;
private double y;
private void drawBricks(Graphics g) {
Graphics2D brick = (Graphics2D) g.create();
x = 0;
y = 0;
for (int j = 0; j <= ROWS; j++)
{
for (int a = 0; a <= COLS; a++) {
brick.setColor(Color.BLACK);
Rectangle2D.Double rect = new Rectangle2D.Double(x, y, BRICK_WIDTH, BRICK_HEIGHT);
brick.fill(rect);
if (mx > x && mx < x + BRICK_WIDTH && my > y && my < y + BRICK_HEIGHT) {
if (brick.getColor() == Color.BLACK) {
CO = Color.white;
brick.setColor(CO);
brick.fill(rect);
repaint();
}
else {
CO = Color.BLACK;
brick.setColor(CO);
brick.fill(rect);
repaint();
}
}
brick.setColor(Color.gray);
brick.draw(rect);
x += BRICK_WIDTH;
}
repaint();
x = 0;
y += BRICK_HEIGHT;
}
}
public int mx = -100;
public int my = -100;
}
public Clicky() {
setDefaultCloseOperation(EXIT_ON_CLOSE); //mai bine cu exit on close
setSize(800, 820);
add(new Board());
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Clicky().setVisible(true);
}
});
}
An easy solution is to use an 2-dimensional boolean array that represents the status of rectangles. When the color changes, change the value of the array-element and set the color depending on it:
public class Clicky extends JFrame {
private static class Board extends JPanel {
private double BRICK_WIDTH = 20;
private double BRICK_HEIGHT = 20;
public Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public double width = screenSize.getWidth();
public double height = screenSize.getHeight();
private int COLS = (int) (width / BRICK_WIDTH);
private int ROWS = (int) (height / BRICK_HEIGHT);
private Color CO = Color.BLACK;
private boolean[][] isWhite = new boolean[COLS + 1][ROWS + 1];
public Board() {
System.out.println("WIdth:" + COLS + "Height:" + ROWS);
setBackground(Color.BLACK);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
System.out.printf("X: %d Y: %d ", mx, my);
isWhite[(int) (mx / BRICK_WIDTH)][(int) (my
/ BRICK_HEIGHT)] = !isWhite[(int) (mx / BRICK_WIDTH)][(int) (my / BRICK_HEIGHT)];
repaint();
}
});
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
mx = e.getX();
my = e.getY();
isWhite[(int) (mx / BRICK_WIDTH)][(int) (my
/ BRICK_HEIGHT)] = !isWhite[(int) (mx / BRICK_WIDTH)][(int) (my / BRICK_HEIGHT)];
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBricks(g);
}
private double x;
private double y;
private void drawBricks(Graphics g) {
Graphics2D brick = (Graphics2D) g.create();
x = 0;
y = 0;
for (int j = 0; j <= ROWS; j++) {
for (int a = 0; a <= COLS; a++) {
if (isWhite[a][j]) {
brick.setColor(Color.WHITE);
} else {
brick.setColor(Color.BLACK);
}
Rectangle2D.Double rect = new Rectangle2D.Double(x, y, BRICK_WIDTH, BRICK_HEIGHT);
brick.fill(rect);
brick.setColor(Color.gray);
brick.draw(rect);
x += BRICK_WIDTH;
}
repaint();
x = 0;
y += BRICK_HEIGHT;
}
}
public int mx = -100;
public int my = -100;
}
public Clicky() {
setDefaultCloseOperation(EXIT_ON_CLOSE); // mai bine cu exit on close
setSize(800, 820);
add(new Board());
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Clicky().setVisible(true);
}
});
}
}
Why does caret becomes invisible (after key pressed, or left-arrow) under java8 (oracle and openjdk) and higher ? (it works under java7). I am on ubuntu. It works fine on mac-os jdk1.8.0_51 and windows jdk1.8.0_65.
Seems to be linked to this bug. It is spécific to JTextField (does not occur on JTextArea).
from OverwritableTextField
public class OverWriteCaret extends DefaultCaret {
protected static final int MIN_WIDTH = 8;
private static final Logger logger = Logger.getLogger(OverWriteCaret.class.getName());
public static void main(String[] args) {
JFrame f = new JFrame("Big caret");
JTextField tf = new JTextField(20);
tf.setCaret(new OverWriteCaret());
f.getContentPane().add(tf, "North");
f.pack();
f.setVisible(true);
}
#Override
protected synchronized void damage(Rectangle r) {
if (r == null)
return;
try {
JTextComponent comp = getComponent();
TextUI mapper = comp.getUI();
Rectangle r2 = mapper.modelToView(comp, getDot() + 1);
int largeur = r2.x - r.x;
if (largeur == 0)
largeur = MIN_WIDTH;
comp.repaint(r.x, r.y, largeur, r.height);
this.x = r.x;
this.y = r.y;
this.width = largeur;
this.height = r.height;
} catch (Exception e) {
logger.info(e);
}
}
#Override
public void paint(Graphics g) {
if (isVisible())
try {
JTextComponent comp = getComponent();
TextUI mapper = comp.getUI();
Rectangle r1 = mapper.modelToView(comp, getDot());
Rectangle r2 = mapper.modelToView(comp, getDot() + 1);
g = g.create();
g.setColor(comp.getForeground());
g.setXORMode(comp.getBackground());
int largeur = r2.x - r1.x;
if (largeur == 0)
largeur = MIN_WIDTH;
g.fillRect(r1.x, r1.y, largeur, r1.height);
g.dispose();
} catch (Exception e) {
logger.info(e);
}
}
}
found another caret, ok with it
public class FancyCaret extends DefaultCaret {
private static final Logger logger = Logger.getLogger(FancyCaret.class.getName());
protected synchronized void damage(Rectangle r) {
if (r == null)
return;
x = r.x;
y = r.y;
height = r.height;
if (width <= 0)
width = getComponent().getWidth();
repaint(); // calls getComponent().repaint(x, y, width, height)
}
#Override
public void paint(Graphics g) {
JTextComponent comp = getComponent();
if (comp == null)
return;
int dot = getDot();
Rectangle r;
char dotChar;
try {
r = comp.modelToView(dot);
if (r == null)
return;
dotChar = comp.getText(dot, 1).charAt(0);
} catch (Exception e) {
logger.info(e);
return;
}
if ((x != r.x) || (y != r.y)) {
repaint(); // erase previous location of caret
x = r.x; // Update dimensions (width gets set later in this method)
y = r.y;
height = r.height;
}
if (dotChar == '\n') {
width = r.height / 2;
if (isVisible())
g.fillRect(r.x, r.y, width, r.height);
return;
}
g.setColor(comp.getCaretColor());
g.setXORMode(comp.getBackground()); // do this to draw in XOR mode
width = g.getFontMetrics().charWidth(dotChar);
if (isVisible())
g.fillRect(r.x, r.y, width, r.height);
}
}
I'm trying to make a java class that contains one layeredpane with 2 JPanel and a scroller.
There are 2 drawings so that I'll be able to draw different things with different threads on each panel, however, nothing happens when I use this class, and, I've checked if I delete the layeredPane and drawingPane0, creating the scroller with drawingPane1, it works correctly...
Does anyone know whats wrong?
Thank you all!
Here it's my code:
public class ScrollPanel extends JPanel implements MouseListener{
private Dimension area; //indicates area taken up by graphics
private Vector<Rectangle> circles; //coordinates used to draw graphics
private JPanel drawingPane0;
private JPanel drawingPane1;
private JLayeredPane layeredPane;
private final Color colors[] = {
Color.red, Color.blue, Color.green, Color.orange,
Color.cyan, Color.magenta, Color.darkGray, Color.yellow};
private final int color_n = colors.length;
public ScrollPanel() {
super(new BorderLayout());
area = new Dimension(0, 0);
circles = new Vector<Rectangle>();
drawingPane1 = new DrawingPane();
layeredPane = new JLayeredPane();
drawingPane0 = new DrawingPane();
drawingPane0.setBackground(Color.WHITE);
drawingPane1.addMouseListener(this);
drawingPane1.setOpaque(false);
layeredPane.add(drawingPane0,0);
layeredPane.add(drawingPane1,1);
JScrollPane scroller = new JScrollPane(layeredPane);
add(scroller, BorderLayout.CENTER);
}
public class DrawingPane extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle rect;
for (int i = 0; i < circles.size(); i++) {
rect = circles.elementAt(i);
g.setColor(colors[(i % color_n)]);
g.fillOval(rect.x, rect.y, rect.width, rect.height);
}
}
}
public void mouseReleased(MouseEvent e) {
final int W = 100;
final int H = 100;
boolean changed = false;
if (SwingUtilities.isRightMouseButton(e)) {
circles.removeAllElements();
area.width = 0;
area.height = 0;
changed = true;
} else {
int x = e.getX() - W / 2;
int y = e.getY() - H / 2;
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
Rectangle rect = new Rectangle(x, y, W, H);
circles.addElement(rect);
drawingPane1.scrollRectToVisible(rect);
int this_width = (x + W + 2);
if (this_width > area.width) {
area.width = this_width;
changed = true;
}
int this_height = (y + H + 2);
if (this_height > area.height) {
area.height = this_height;
changed = true;
}
}
if (changed) {
drawingPane1.setPreferredSize(area);
drawingPane1.revalidate();
}
drawingPane1.repaint();
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
}
I want to add 2 buttons to the following code that will let me "FREEZE" and "START" the ball move as it bounces on the window. I've been trying to do this for the last hour but I cant figure this out. I did some work but it mostly crap, if anyone wants please let me know to post it(avoided it in order not to extend my coding). Anyone can help me with this?
Open to any suggestions.
Thanks
import java.awt.*;
import javax.swing.*;
public class BallMoves extends JPanel implements Runnable {
Color color = Color.red;
int dia = 30;
long delay = 40;
private int x = 1;
private int y = 1;
private int dx = 3;
private int dy = 7;
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color);
g.fillOval(x,y,30,30); // adds color to circle
g.setColor(Color.red);
g2.drawOval(x,y,30,30); // draws circle
}
public void run() {
while(isVisible()) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
System.out.println("interrupted");
}
move();
repaint();
}
}
public void move() {
if(x + dx < 0 || x + dia + dx > getWidth()) {
dx *= -1;
color = getColor();
}
if(y + dy < 0 || y + dia + dy > getHeight()) {
dy *= -1;
color = getColor();
}
x += dx;
y += dy;
}
private Color getColor() {
int rval = (int)Math.floor(255);
int gval = (int)Math.floor(0);
int bval = (int)Math.floor(0);
return new Color(rval, gval, bval);
}
private void start() {
while(!isVisible()) {
try {
Thread.sleep(25);
} catch(InterruptedException e) {
System.exit(1);
}
}
Thread thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
public static void main(String[] args) {
BallMoves test = new BallMoves();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
test.start();
}
}
Update version
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class BallMoves extends JPanel implements Runnable {
Color color = Color.red;
int dia = 30;
long delay = 40;
private int x = 1;
private int y = 1;
private int dx = 3;
private int dy = 7;
private boolean isRunning;
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(color);
g.fillOval(x,y,30,30); // adds color to circle
g.setColor(Color.red);
g2.drawOval(x,y,30,30); // draws circle
}
public void run() {
while(isVisible()) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
System.out.println("interrupted");
}
move();
repaint();
}
}
public void move() {
if (isRunning) {
if(x + dx < 0 || x + dia + dx > getWidth()) {
dx *= -1;
color = getColor();
}
if(y + dy < 0 || y + dia + dy > getHeight()) {
dy *= -1;
color = getColor();
}
x += dx;
y += dy;
}
}
private Color getColor() {
int rval = (int)Math.floor(255);
int gval = (int)Math.floor(0);
int bval = (int)Math.floor(0);
return new Color(rval, gval, bval);
}
private void start() {
while(!isVisible()) {
try {
Thread.sleep(25);
} catch(InterruptedException e) {
System.exit(1);
}
}
Thread thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
final BallMoves test = new BallMoves();
JFrame f = new JFrame();
JButton start = new JButton("start");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
test.isRunning = true;
}
});
JButton stop = new JButton("stop");
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
test.isRunning = false;
}
});
JPanel panel = new JPanel();
panel.add(start);
panel.add(stop);
f.add(panel, java.awt.BorderLayout.NORTH);
f.getContentPane().add(test);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(new Dimension(400, 400));
f.setLocationRelativeTo(null);
f.setVisible(true);
test.start();
}
});
}
}
Create a flag and switch it on button click.
private volatile boolean isRunning;
public void move() {
if (isRunning) {
// your existing code
...
}
}
on start button click
isRunning = true;
on stop button click
isRunning = false;
I want to Zoom specific area on image. which is selected by the user. image display on canvas using Swing. i already done full image zoom on canvas but can't implement specific area zoom.
please help
Canvas is awt not swing. Try JPanel instead. Example.
But if you already done full image zoom, try to make the same on a sub-image.
BufferedImage.getSubimage(x, y, w, h);
EDIT
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Example {
private Point startPoint = new Point(0, 0);
private Point rectLocale = new Point();
private Dimension rectSize = new Dimension();
private int zoom = 80;
private BufferedImage capture = null;
private BufferedImage raw;
public Example() throws Exception {
raw = new Robot().createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
MouseBehavior behavior = new MouseBehavior();
JPanel b = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(500, 500);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = ((Graphics2D) g);
g2d.drawImage(raw, 0, 0, null);
if (capture != null) {
int width2 = (int) (rectSize.width + rectSize.width * (zoom / 500d));
int height2 = (int) (rectSize.height + rectSize.height * (zoom / 500d));
int x2 = rectLocale.x - ((width2 - rectSize.width) / 2);
int y2 = rectLocale.y - ((height2 - rectSize.height) / 2);
Image scaledInstance = capture.getScaledInstance(
width2, height2, Image.SCALE_AREA_AVERAGING);
g2d.drawImage(scaledInstance, x2, y2, null);
g2d.drawRect(x2, y2, width2, height2);
} else {
g2d.draw(new Rectangle(rectLocale, rectSize));
}
}
};
b.addMouseMotionListener(behavior);
b.addMouseListener(behavior);
b.addMouseWheelListener(behavior);
JFrame f = new JFrame();
f.setLocation(10, 10);
f.setDefaultCloseOperation(3);
f.add(b);
f.pack();
f.setVisible(true);
}
private class MouseBehavior extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
rectLocale = new Point();
rectSize = new Dimension();
capture = null;
if (e.getSource() instanceof JComponent) {
((JComponent) e.getSource()).repaint();
}
}
#Override
public void mouseDragged(MouseEvent e) {
Point currentPoint = e.getPoint();
rectSize.width = Math.abs(currentPoint.x - startPoint.x);
rectSize.height = Math.abs(currentPoint.y - startPoint.y);
if (e.isShiftDown()) {
rectSize.width = rectSize.height = Math.min(
rectSize.width, rectSize.height);
int dx = startPoint.x - rectSize.width;
int dy = startPoint.y - rectSize.height;
rectLocale.x = startPoint.x < currentPoint.x ? startPoint.x
: Math.max(dx, dy);
rectLocale.y = startPoint.y < currentPoint.y ? startPoint.y
: Math.min(dx, dy);
} else {
rectLocale.x = Math.min(currentPoint.x, startPoint.x);
rectLocale.y = Math.min(currentPoint.y, startPoint.y);
}
if (e.getSource() instanceof JComponent) {
((JComponent) e.getSource()).repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (rectSize.width <= 0 || rectSize.height <= 0) {
capture = null;
} else {
capture = raw.getSubimage(Math.max(0, rectLocale.x),
Math.max(0, rectLocale.y), rectSize.width, rectSize.height);
}
if (e.getSource() instanceof JComponent) {
((JComponent) e.getSource()).repaint();
}
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
zoom = Math.min(2000, Math.max(0, zoom + e.getUnitsToScroll() * 10));
if (e.getSource() instanceof JComponent) {
((JComponent) e.getSource()).repaint();
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Example example = new Example();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}