0

我想用来JScrollBar放大和缩小图像,但它不起作用。我的代码有什么问题?

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);

       }
     });
  }

}
4

1 回答 1

1

您的代码中有很多错误。它需要普遍的重新思考。

我只会给你一些基本的提示:

  • 您使用ImagePanel不设置侦听器的构造函数(注意NullPointerException);
  • 您没有缩放图像-paintComponent您只是按原样绘制图像;
  • 您正在添加到width侦听器height滚动值并尝试将它们重置paintComponent- 这不是您应该做的。提示:有一个Graphics类方法:g.drawImage(image, x, y, width, height, this);;
  • 每个 Swing 组件都必须在 EDT 上创建和更改:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            JFrame frame = new JFrame();
            //etc.
        }
    });
}
于 2012-07-31T13:28:45.110 回答