【问题标题】:Resize and Redraw a image in a JPanel在 JPanel 中调整图像大小和重绘图像
【发布时间】:2015-10-18 16:00:50
【问题描述】:

我正在创建一个简单的 java 程序来加载图像并放大/缩小图像。 到目前为止,我已经能够加载图片并对其进行缩放。但是在绘制缩小的图像时,我仍然可以在 JPanel 上看到之前的图像。

图片加载代码

JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Images(jpg,png,gif)", "jpg","png","gif"));
int opt = fileChooser.showOpenDialog(this);
if(opt  == JFileChooser.APPROVE_OPTION){
    String filePath = fileChooser.getSelectedFile().getAbsolutePath();
    try {
        bufImage = ImageIO.read(fileChooser.getSelectedFile());
    } catch (IOException ex) {
        Logger.getLogger(ImageZoom.class.getName()).log(Level.SEVERE, null, ex);
    }
    image = new ImageIcon(filePath);
    imgWidth = image.getIconWidth();
    imgHeight = image.getIconHeight();

    imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, image.getIconWidth(), image.getIconHeight(), imagePanel);
}

放大代码

double scale_factor = 1.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);

缩小代码

double scale_factor = 0.5;
imagePanel.getGraphics().drawImage(image.getImage(), 0, 100, (int)(imgWidth*=scale_factor), (int)(imgHeight*=scale_factor), imagePanel);  

有人可以建议一种仅在面板上显示调整大小的图像的方法吗?
这就是缩小的样子。打开新图片时也会出现同样的问题。
我尝试重新粉刷面板,但一切都消失了。

【问题讨论】:

  • @LuxxMiner 试过了。面板上没有显示任何内容。我只是得到一个空窗口。

标签: java image swing


【解决方案1】:

这是因为 imagePanel.getGraphics() 不是自定义绘画在 Swing 中的工作方式。相反,创建一个扩展自 JPanel 之类的自定义类并覆盖它的 paintComponent 方法,在那里绘制您的缩放图像(确保首先调用 super.paintComponent

请参阅Painting in AWT and SwingPerforming Custom Painting 了解更多详情

例如:

【讨论】:

  • 我试过你说的,在面板上看不到我的图像。这是我使用的代码:paste.ubuntu.com/11952468 你能检查一下,让我知道我犯了什么错误
  • 您的绘图面板应该是一个单独的组件,您的绘图面板上目前还有许多其他组件可能会在图像上进行绘画
  • 您也可能遇到 NullPointException,因为在绘制组件之前不会加载图像。您也不应该在任何绘画方法中直接或间接调用重绘
  • 如果不调用repaint,我在加载新图像时应该如何重绘图像?而且我没有收到 NullPointerException。可以举个例子吗?
  • 您可以调用 repaint,但不能从任何 paint 方法中调用,否则您会设置一个无限循环,这将消耗您的 CPU 周期。我已经链接了 3 个示例
猜你喜欢
  • 2015-10-25
  • 2013-11-12
  • 1970-01-01
  • 2012-05-16
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多