【发布时间】:2016-08-10 22:41:36
【问题描述】:
我有这个应该绘制图像的类。
package ro.adlabs.imnuriAZSMR.UIClases;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class JImage extends JPanel {
private BufferedImage image;
private int height;
private int width;
public JImage(String imagePath,int height,int width) {
try {
image = ImageIO.read(getClass().getResourceAsStream(imagePath));
} catch (IOException ex) {
ex.printStackTrace();
}
this.width = width;
this.height = height;
}
public JImage(String imagePath,int size){
new JImage(imagePath,size,size);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, width, height, this);
}
}
还有这个显示关于对话框的类:
package ro.adlabs.imnuriAZSMR.UIClases;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AboutDialog extends JDialog {
public AboutDialog() {
setTitle("About");
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JLabel name = new JLabel("<html><div style='text-align: center;'>Aceasta aplicatie e dezvoltata sub Termenii si Conditiile ADLabs.</div></html>");
JLabel copyright = new JLabel("© ADLabs - www.adlabs.ro");
name.setAlignmentX(0.5f);
copyright.setAlignmentX(0.5f);
add(name);
add(new JImage("../ico/appicon_200x200.png",50));
add(copyright);
JButton close = new JButton("Close");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
close.setAlignmentX(0.5f);
add(close);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(300, 200);
}
}
我在对话框中添加了应用程序徽标的图像。当我第一次创建它工作的 JImage 类时,它绘制了图片。然后我添加了方法:
setSize(width+20,height+20);
到 JImage 类中的 Jpanel,当我再次运行程序时,它没有绘制图像。然后我所做的任何事情都没有解决这个奇怪的错误。 有人有任何想法吗?我做错了什么?
【问题讨论】:
-
1.为了尽快获得更好的帮助,请发布minimal reproducible example 或Short, Self Contained, Correct Example。 2. 例如,获取图像的一种方法是热链接到this Q&A 中看到的图像。
-
new JImage(imagePath, size, size);- 你只需创建一个新的类实例,对当前实例不做任何事情;调用this(imagePath, size, size);来调用另一个构造函数。这解决了我的问题。 -
public class JImage extends JPanel从表面上看,JImage类最好替换为JLabel。将图像设置为图标。