可以托拽的图片显示控件,JViewport 用法演示

这篇博客通过实例展示了如何利用JViewport控件解决JPanel中图片超出显示范围的问题。用户可以通过鼠标拖动查看图片的其他部分。文章提供了一个简单的代码实现,包括创建包含图片的面板和可拖动的JViewport,以及一个测试程序来打开和查看图片。
摘要由CSDN通过智能技术生成

有人发贴问,一个 JPanel 里的图片太大了,超出了 JPanel 的大小范围,“我想拖动鼠标按住JPanel,拖动JPanel,把那些显示不了的线段“拖回来”。


这是 JViewport 的典型应用场景,很多人会用 JScrollPane,但是对  JViewport 可能不熟悉,其实 JScrollPane 是整合了几个 JViewport,JScrollBar,以及特别设计的布局的一个控件,其中的 JViewport 单独拿出来也很好用,下面就是示例代码。


为了显示图片,先做一个 panel,如下


/*
 * Copyright 2013 (raistlic@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.swing.JPanel;


/**
 *
 * @author raistlic
 */
public class JImagePanel extends JPanel {
  
  private static final Color GRID_1 = Color.GRAY.brighter();
  private static final Color GRID_2 = GRID_1.brighter();
  private static final int GRID_SIZE = 10;
  
  private Image image;
  
  public void setImage(Image image) {
    
    // although not checked, this method should be called with-in EDT.
    
    this.image = image;
    revalidate();
    repaint();
  }
  
  @Override
  public Dimension getPreferredSize() {
    
    if( image == null )
      return getMinimumSize();
    else {
      
      Insets i = getInsets();
      return new Dimension(
              i.left + i.right + image.getWidth(this), 
              i.top + i.bottom + image.getHeight(this));
    }
  }
  
  @Override
  protected void paintComponent(Graphics g) {
    
    super.paintComponent(g);
    
    int width = getWi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值