¿Cómo usar la imagen de zoom de JScrollBar?

Quiero usar JScrollBar to zoom in and zoom out images but it doesn't work. What's wrong with my code?

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

 public class piczoominandout extends JFrame
{
  public JScrollBar scroll;
  public JLabel lbl;
  public Image image;
  public int x, y, width, height;

  public piczoominandout()
 {
   super("picture zoom");
   Toolkit toolkit = Toolkit.getDefaultToolkit();
   image = toolkit.getImage("Snake.jpg");
   Container c = getContentPane();
   ImagePanel imagePane = new ImagePanel(image);

   c.setLayout(new BorderLayout());
   lbl = new JLabel("0");
   c.add(lbl, BorderLayout.SOUTH);
   scroll = new JScrollBar(
           JScrollBar.HORIZONTAL,50,10,0,100);
   scroll.addAdjustmentListener(new AdjustmentListener() {
     public void adjustmentValueChanged(
                         AdjustmentEvent evt) {
        JScrollBar s = (JScrollBar)evt.getSource();
        if ( !s.getValueIsAdjusting() ) {
           int v = (int)s.getValue();
           width +=v;
           height +=v;

           repaint();
           lbl.setText(Integer.toString(v));
        }
     } });
    c.add(imagePane,BorderLayout.CENTER );

    c.add(scroll, BorderLayout.NORTH);
 }
 class ImagePanel extends JPanel
 {
  public ImagePanel(Image img) { image = img;}
  public void paintComponent(Graphics g)
  {
   Insets ins = getInsets();
   super.paintComponent(g);
   width = image.getWidth(this);
   height = image.getHeight(this);
   x = ins.left+5; y = ins.top+5;
   g.drawImage(image,x,y,width,height,this);
  }
 }

  public static void main(String[] args)
  {
   SwingUtilities.invokeLater(new Runnable() {
     public void run()
     {
      piczoominandout frame = new piczoominandout();
      frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
      frame.setSize(600,300);
      frame.setVisible(true);

       }
     });
  }

}

preguntado el 31 de julio de 12 a las 13:07

1 Respuestas

There is so many errors in your code. It needs general rethinking.

I'll give you some basic hints only:

  • Usas un ImagePanel contructor that don't set a listener (look out for NullPointerException);
  • You're not scaling image - on paintComponent you just painting image as it is;
  • Estás agregando a width y height in listener scroll value and you try to reset them in paintComponent - this is not what you should do. HINT: there's a method of Graphics clase: g.drawImage(image, x, y, width, height, this);;
  • Every Swing component must be created and changed on EDT:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame();
            //etc.
        }
    });
}

Respondido 31 Jul 12, 14:07

I change some code , then i dunno what to do , can u help me again? >< - user1565659

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.