我必须在软件底部加载一个小图标。只是有一个加载/确定/错误图标。正如“http://www.article.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter06/images.html”上的建议,我创建了一个扩展 JPanel 的 dwowing 面板。
class drawingPanel extends JPanel
{
Image img;
drawingPanel (Image img){
this.img = img;
}
public void paintComponent (Graphics g) {
super.paintComponent (g);
// Use the image width & height to find the starting point
int imgX = getSize ().width/2 - img.getWidth (this);
int imgY = getSize ().height/2 - img.getHeight (this);
//Draw image centered in the middle of the panel
g.drawImage (img, imgX, imgY, this);
} // paintComponent
}
我通过以下方式初始化组件:
// Grab the image.
Image img = new ImageIcon(iconPath+"ok.png").getImage();
// Create an instance of DrawingPanel
iconPanel = new drawingPanel(img);
一切正常,但在运行时我希望能够更改面板内的图标。我尝试了以下所有方法,但都没有成功查看新图片:
Image img = new ImageIcon(iconPath+"loading.gif").getImage();
// Create a new instance of DrawingPanel
this.iconPanel = new drawingPanel(img);
this.iconPanel.repaint();
this.iconPanel.revalidate();
this.iconPanel.repaint();
this.repaint();
this.revalidate();
(我尝试这样做是因为我编写代码的类是包含图标面板的 JPanel 的另一个扩展。知道为什么我无法更改图片吗?
谢谢,
斯特凡诺
首先不要以小名称开头。改名drawingPanel
to DrawingPanel
.
我尝试根据您的描述制作一个简单的演示,效果很好。面板中的图像正在完美变化。
public class Demo {
public Demo() {
JFrame frame = new JFrame();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
// Grab the image.
Image img = new ImageIcon("1.png").getImage();
// Create an instance of DrawingPanel
final DrawingPanel iconPanel = new DrawingPanel(img);
frame.add(iconPanel, BorderLayout.CENTER);
JButton button = new JButton("Change image..");
frame.add(button, BorderLayout.NORTH);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
iconPanel.setImg(new ImageIcon("2.png").getImage());
iconPanel.repaint();
}
});
frame.setVisible(true);
}
public static void main(String[] args){
new Demo();
}
}
class DrawingPanel extends JPanel {
Image img;
DrawingPanel(Image img) {
this.img = img;
}
public void setImg(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Use the image width & height to find the starting point
int imgX = getSize().width / 2 - img.getWidth(this);
int imgY = getSize().height / 2 - img.getHeight(this);
// Draw image centered in the middle of the panel
g.drawImage(img, imgX, imgY, this);
} // paintComponent
}
我所做的更改是添加一个 setter 方法img
in DrawingPanel
班级。所以不要创建新的DrawingPanel
您只需使用新图像调用 settIng() ,然后调用 Paint 来绘制新图像。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)