JScrollPane与JPanel 滚动条 解决canvas的滚动条问题

时间:2022-05-30 07:52:49

当用JScrollPane和JPanel显示图片时,需要将JPanel的PrefferedSize及时传递给JScrollPane,否则容易出现JScrollPane的滚动条无法与图片大小匹配的问题,下面是从Matrix网上搜到的一段代码供参考使用:

 

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ScrollPaneDemo extends JFrame implements MouseListener {
        ImagePanel jp;
        JScrollPane jsp;
        public ScrollPaneDemo() {
                super("JScrollPane Demo");
                jp = new ImagePanel();
                jp.setPreferredSize(new Dimension(600, 400));
                jsp = new JScrollPane(jp);
                jp.addMouseListener(this);
                getContentPane().add(jsp);
                setSize(640, 480);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setVisible(true);
        }
        public void mouseClicked(MouseEvent e) {
                System.out.println("mouseClicked");
                jp.enlarge();
                jp.setPreferredSize(jp.getPreferredSize());
                jsp.validate();
        }
        public void mousePressed(MouseEvent e) {
                // System.out.println("mousePressed");
        }

        public void mouseReleased(MouseEvent e) {
                // System.out.println("mouseReleased");
        }
        public void mouseEntered(MouseEvent e) {
                // System.out.println("mouseEntered");
        }
        public void mouseExited(MouseEvent e) {
                // System.out.println("mouseExited");
        }
        public static void main(String[] args) {
                new ScrollPaneDemo();
        }
}
class ImagePanel extends JPanel {
        private Image image;
        private Dimension theSize = new Dimension(600, 400);
        public void setImage(Image image) {
                this.image = image;
                this.repaint();
        }
        public Image getImage() {
                return this.image;
        }
        public void paintComponent(Graphics g) {
                ImageIcon img = new ImageIcon("Winter.jpg");
                g.drawImage(img.getImage(), 0, 0, theSize.width, theSize.height, null);
        }
        public void enlarge() {
                theSize.width = (theSize.width * 101) / 100;
                theSize.height = (theSize.height * 101) / 100;
                setSize(theSize);
        }        
        public Dimension getPreferredSize() {
                return this.theSize;
        }
}

因为scrollPane是根据里面的子控件的preferredSize来确定滚动条的。
所以图片变化而滚动条无响应的问题在于让image尺寸变化时,scrollPane能得到新的数据。

解决方式有两种,一种是改变大小时重新设置JPanel的preferred size;
一种是重载getPreferredSize()方法,按照需要返回,楼主的情况可以返回当前
图片的大小的Dimension。

文章出自:http://xu.wy.blog.163.com/blog/static/11568296200786103315608/