我必须使用飞重模式显示图像,但无法将图像打印到屏幕上,这是演示该问题的代码。
public void draw(Graphics g, int tx, int ty, String name) {
grem.paintIcon(null, g, tx, ty);
g.drawString(name, tx, ty + H + 15 );
ImageIcon grem = new ImageIcon("../images/grem.png");
}
/// next class that calls the above class
public void paint(Graphics g) {
Folder folderIcon;
String name;
int j = 0; //count number in row
int row = Top; //start in upper left
int x = Left;
//go through all the names and folders
for (int i = 0; i< names.size(); i++) {
name = (String)names.elementAt(i);
if (name.equals(selectedName))
folderIcon = fact.getFolder(true);
else
folderIcon = fact.getFolder(false);
//have that folder draw itself at this spot
folderIcon.paint(g);
x = x + HSpace; //change to next posn
j++;
if (j >= HCount) { //reset for next row
j = 0;
row += VSpace;
x = Left;
}
}
}
最佳答案
不要重写paint()。自定义绘画是通过重写paintComponent()来完成的。
不要在绘画方法中执行 I/O。您无法控制 Swing 何时重新绘制组件,因此您不想在绘制方法中读取图像。应在类的构造函数中读取图像。
重写
getPreferredSize(...)
方法以返回组件的大小,否则组件的大小将为 (0, 0),因此可能没有任何内容可绘制(取决于所使用的布局管理器。如果您需要更多帮助,请发布适当的 SSCCE这说明了问题,因为我们不知道您的代码如何使用的上下文,也没有时间花时间猜测您可能会做什么或可能不会做什么。
阅读 Swing 教程中关于 Custom Painting 的部分了解更多信息。此外,您还可以使用 JList 以网格模式显示图标,而不是进行自定义绘制。查看教程链接的目录,找到有关如何使用列表
的部分以获取更多信息。
关于java - 无法显示图像图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36288446/