1

i am trying to scale image using mouse motion listener but its not working. so right now i am doing this in manually using 2 JTextfields. I am taking value from Jtextfields and then pass that values to getScaledInstance() method. but it is not working.

my code :

        final JTextField jj = new JTextField();
        jj.setColumns(5);
        buttonPane.add(jj);
        JButton btn  = new JButton("Resize");
        final JTextField jj1 = new JTextField();
        jj1.setColumns(5);
        buttonPane.add(jj1);
        buttonPane.add(btn);
        btn.addActionListener(new ActionListener() {


            @Override
            public void actionPerformed(ActionEvent arg0) 
            {
                int x= Integer.parseInt(jj.getText());
                int y=Integer.parseInt(jj1.getText());

                BufferedImage b = a;
                b.getScaledInstance(x, y,BufferedImage.TYPE_INT_ARGB);
                label.setIcon(new ImageIcon(b));
            }
        });

here a is BufferedImage instance that is popped from stack. and label is JLabel.

Java Curious ღ
  • 3,622
  • 8
  • 39
  • 63

1 Answers1

3

You need assign the return reference to something...

Image scaled = b.getScaledInstance(x, y,BufferedImage.TYPE_INT_ARGB);
label.setIcon(new ImageIcon(scaled));

You may also want to have read through The Perils of Image.getScaledInstance()

Update with Mouse Wheel scaling

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MouseScaleTest {

    public static void main(String[] args) {
        new MouseScaleTest();
    }

    public MouseScaleTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage img;

        private float scale = 1f;
        private float scaleDelta = 0.05f;

        public TestPane() {

            try {
                img = ImageIO.read(new File("/path/to/your/image"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            addMouseWheelListener(new MouseWheelListener() {

                @Override
                public void mouseWheelMoved(MouseWheelEvent e) {
                    int rotation = e.getWheelRotation();
                    if (rotation < 0) {
                        scale -= scaleDelta;
                    } else {
                        scale += scaleDelta;
                    }
                    if (scale < 0) {
                        scale = 0;
                    } else if (scale > 1) {
                        scale = 1;
                    }
                    repaint();
                }
            });
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (img != null) {
                Graphics2D g2d = (Graphics2D) g.create();

                int x = (int)((getWidth() - (img.getWidth() * scale)) / 2);
                int y = (int)(getHeight() - (img.getHeight() * scale)) / 2;

                AffineTransform at = new AffineTransform();
                at.translate(x, y);
                at.scale(scale, scale);

                g2d.setTransform(at);
                g2d.drawImage(img, 0, 0, this);

                g2d.dispose();
            }
        }
    }
}

Take the time to read through How to write a Mouse Listener and How to write a Mouse-Wheel Listener

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • but how it will take `a`'s reference ? because i have to provide some image reference to it that on which image it will perform that operation.. – Java Curious ღ Aug 23 '13 at 06:41
  • ok, will you tell me how to do that ? because it shows an error when i am trying to do that. – Java Curious ღ Aug 23 '13 at 06:45
  • it shows an error of casting i.e. can not convert an image to buffered image. – Java Curious ღ Aug 23 '13 at 06:48
  • 1
    Spend to long using `BufferedImage`s...:P – MadProgrammer Aug 23 '13 at 06:50
  • thank you so much, i have made it using your priceless help. i am just so happy. sir did u know how to do scaling using mouse listener ? i have your code but in my code i have taken a label so while scaling image using mouse i am facing problem. – Java Curious ღ Aug 23 '13 at 06:52
  • it works smoothly & very nice. But i want to resize or scale image using mouse drag event, i have also that code but i am displaying image in JLabel that's why i am facing problem otherwise all works well. when i am dragging or scaling image whole window dragged and scaled, pointer not working on image corners. – Java Curious ღ Aug 23 '13 at 08:07
  • 1
    So? Did you read the tutorial? `MouseMotionListener` has a `mouseDragged` event...you're probably going to need to use a `MouseListener` to determine when the mouse is pressed and released as well. – MadProgrammer Aug 23 '13 at 08:09
  • yes i have read that tutorial, i have to calculate difference between mouse pressed to mouse released but label creates the problem for me. i have your code that have 3 class's one main class, one ViewPane and other is ImagePane, imagepane contain only image which called inside viewpane and viewpane in main class. mouse motionlistener is used when we want to move image inside panel. and MouseAdapter class also used for that to track mouse action. – Java Curious ღ Aug 23 '13 at 08:11
  • and one other problem in your above code is that image is scaled but when we are trying to scale image more than it's original height and width, it not works, it works up to it's maximum resolution. – Java Curious ღ Aug 23 '13 at 08:22
  • @user2659972 That's not a problem, that's by design...I set the scale range to 0 - 1 on purpose. Take a look at the `if` statement in the `mouseWheelMoved` method – MadProgrammer Aug 23 '13 at 08:25
  • Try taking a look at [this example](http://stackoverflow.com/questions/18053310/how-to-make-image-stretchable-in-swing/18054307#18054307) – MadProgrammer Aug 23 '13 at 08:28
  • oh sorry sir for my this silly mistake. i am just getting confused about thinking on mouselistener so that's why, sir can i put this all implementation directly to my image that display inside JLabel ? – Java Curious ღ Aug 23 '13 at 08:29
  • yes i have seen that example and tried to implement it, but in my application i have taken only single class that is PictureEditor and i have perform all in one class and in my case i have displayed image in Jlabel, so that's why i am getting confused, is there any way to perform that ? – Java Curious ღ Aug 23 '13 at 08:31
  • sir i have tried this code to integrate with my application but mousewheel listener don't work in it. – Java Curious ღ Aug 23 '13 at 08:43
  • Where did you implement the mouse listener? – MadProgrammer Aug 23 '13 at 09:39
  • in constructor of PictureEditor class. at below of textfield code. and is it necessary to add `addMouseWheelListener(null);` after that code, i have tried both of them but don't work. – Java Curious ღ Aug 23 '13 at 09:43
  • It's hard to say without the code, but is it on the same component that holds the image? – MadProgrammer Aug 23 '13 at 09:47
  • i have also try to create separate class like you and call constructor inside the constructor of that main PICTUREEDITOR class but it also doesn't scale image. – Java Curious ღ Aug 23 '13 at 09:49
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/36095/discussion-between-user2659972-and-madprogrammer) – Java Curious ღ Aug 23 '13 at 09:50