无法在 jframe 内的 jscrollpane 中添加图像 [英] Not able to add image in jscrollpane inside a jframe

查看:28
本文介绍了无法在 jframe 内的 jscrollpane 中添加图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jscroll 窗格将图像添加到我的 jframe.我尝试了一些东西,但图像只出现在背景中.像这样,图像编辑器下面的那个.

I'm trying to add an image to my jframe using jscroll pane.I tried fewthings but the image appears only in the background.Something like this,the one below image editor.

这是我的代码:

   private void initComponents(){
     jScrollPane1 = new javax.swing.JScrollPane();
     ImageImplement panel = new ImageImplement(new ImageIcon(mean.get(0)).getImage());
     jScrollPane1.add(panel); setVisible(true); setSize(400,400); setDefaultCloseOperation(EXIT_ON_CLOSE);
   }
   class ImageImplement extends JScrollPane { 
     private Image img; 
     public ImageImplement(Image img) { this.img = img;
     Dimension size = new Dimension(img.getWidth(null), img.getHeight(null)); 
     setPreferredSize(size);
     setMinimumSize(size);
     setMaximumSize(size); 
     setSize(size); 
     setLayout(null); } 
     public void paintComponent(Graphics g) { 
     g.drawImage(img, 0, 0, null); } 
     } 

推荐答案

不要扩展 JScrollPane 也不要自定义绘制.

Don't extend JScrollPane and don't do custom painting.

相反,您只需创建一个带有 ImageIconJLabel.然后将标签添加到滚动窗格,并将滚动窗格添加到框架.

Instead you just create a JLabel with an ImageIcon. Then you add the label to the scroll pane and the scroll pane to the frame.

所以基本逻辑是:

ImageIcon icon = new ImageIcon(...);
JLabel label = new JLabel( icon );
JScrollPane scrollPane = new JScrollPane( label );
frame.add(scrollPane, BorderLayout.CENTER);

这篇关于无法在 jframe 内的 jscrollpane 中添加图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆