Drawing an image in JScrollPane within scale

时间秒杀一切 提交于 2019-12-04 18:12:08

JScrollPane, or more to the point JViewport will use the component's (or in this case the "view's") preferred size as a bases for determining how big the view should be.

When the view expands beyond the size of the scroll pane, it will show the scroll bars.

So basically, you need to override the getPreferredSize of the public class Mappa extends JPanel { panel, for example

public class Mappa extends JPanel {
    //...
    public Dimension getPreferredSize() {
        return immagine == null ? new Dimension(200, 200) : new Dimension(immagine.getWidth(), immagine.getHeight());
    }
    //...
}

This will encourage the JViewport to always be the same size as the image.

Also, two things...

First, you shouldn't rely on magic numbers, for example

g.clearRect(0, 0, 4000, 4000);

Should be more like...

g.clearRect(0, 0, getWidth(), getHeight());

And secondly,

super.paintComponent(g);

Will do this any way, so calling clearRect is kind of pointless...

You might also like to take a look at Scrollable, but it is quite an advanced topic

I wont this image with her natural size, and if this image is too big, I wont activated the scrollbar,

Using JLabel to contain the image and wrap it in a JScrollPane should easily achieve what you want. Take hints from the following example:

class AFrame extends JFrame
{
   public AFrame()
  {

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setTitle("Image view Demo with JScrollPane");

     ImageIcon image = new ImageIcon("myImage.png"); // pass the file location of an image
     JLabel label = new JLabel(image);
     JScrollPane scrollPane = new JScrollPane(label);
     scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
     scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
     add(scrollPane, BorderLayout.CENTER);
     pack();
  }

 public static void main(String[] args)
 {
    SwingUtilities.invokeLater(new Runnable() {

       @Override
       public void run() {
          new AFrame().setVisible(true);
       }
    });

  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!