因此,我在JPanel内部绘制了一个图像,该图像本身已添加到JFrame中。 但是,当第一次绘制图像时,它看起来很小。 我不确定这是面板问题还是图像问题。 如下图所示:
![在此处输入图片描述] [1]
我在图像周围绘制了一个矩形。
现在,应该将JPanel包含在JFrame中。 如上所示,不应将JFrame着色。 JPanel的大小约为JFrame的四分之一,并且图像应该占据了几乎所有的JPanel。
您能告诉我是问题的图像还是面板。 抱歉,似乎很明显。
等待SSCCE
根据您发布的几行随机代码,我不知道您在做什么。在代码中,您实际上没有创建/读取图像。
据我所知,Mandelbrot集实际上是通过绘画代码完成的。如果是这样,则问题可能出在您没有覆盖绘画面板的getPreferredSize()(不要使用setSize()方法)来返回您正在绘画的图像的大小。阅读Swing教程中有关"自定义疼痛"的部分,以获取更多信息。
或者,如果您实际上正在使用现有图像,请阅读Swing教程中有关如何使用图标的部分,以获取使用图像的工作示例。
另外,在使框架可见之前,应将组件添加到框架。
如果您需要更多帮助,请发布适当的SSCCE来演示问题。
抱歉,如果含糊不清,Ive现在提供了绘制图像的代码。
@ user3352349 Ive now included the code which draws the image-没有帮助。 仍然没有帮助。 我们仍然不知道如何调用draw()方法。 看起来您正在绘制BufferedImage,但是我们不知道您实际在面板上绘制BufferedImage的位置,还是为什么您不使用JLabel显示BufferedImage的原因。 您是否添加了调试代码以显示您的size变量的Dimension大小? 再次,如果您需要更多帮助,请选择适当的SSCCE
BufferedImage image = ImageIO.read(file); //Read image through BufferedReader
labelimage.setIcon(new ImageIcon(image.getScaledInstance(labelimage.getWidth(), labelimage.getHeight(), image.SCALE_SMOOTH))); // This line will automaticallically set Image size equal to size of Jlabel
如何在面板内添加标签,并使用setIcon(..)绘制图像
通常,我使用以下类使图像适合标签尺寸(我使我的标签具有静态尺寸-无法调整大小)..您可能想要对其进行修改以适合您的需要。
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.net.URL;
import javax.swing.ImageIcon;
public class CustomImageIcon extends ImageIcon {
private BufferedImage dest;
public CustomImageIcon(String filename) {
super(filename);
}
public CustomImageIcon(Image image) {
super(image);
}
public CustomImageIcon(URL location) {
super(location);
}
@Override
public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
if(c!=null)
dest = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);
else dest = new BufferedImage(getIconWidth(), getIconHeight(), BufferedImage.TYPE_INT_ARGB);
ImageObserver imgObs = getImageObserver();
if(imgObs==null) imgObs = c;
int width;
int height;
if(c!=null)
{
width = c.getWidth();
height = c.getHeight();
}
else
{
width = getIconWidth();
height = getIconHeight();
}
g.drawImage(dest, 0, 0, c);
g.drawImage(
getImage(),
0,
0,
width,
height,
imgObs);
}
}
-1,为什么要通过扩展Icon来进行自定义绘画代码。 使用Icon的目的是使用ImageIcon类并将Icon添加到标签中,因此您无需进行自定义绘制。
如我之前所说,无论图像的大小如何,都需要使图像自动适合标签。.有时图像不适合标签,我会遇到问题..对不起,这对您来说是错误的。 。=)