晚上好。我已经在stackoverflow甚至互联网上阅读了很多主题,但我无法找到解决问题的方法。
我有这样的界面:
当我点击"加载图像A"时,我可以选择我想要的图像。接下来,我想在JLabel "图像A" 下绘制此图像。但它并不想显示出来。
这是我写的代码:
package projet;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class MonPanelImage extends JPanel{
private static final long serialVersionUID = -8267224342030244581L;
private BufferedImage image;
public MonPanelImage(File adresse)
{
try{
image = ImageIO.read(adresse);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
System.out.println("paint");
if(image != null){
g.drawImage(image, 20, 20, this);
}
}
}
这就是我所说的:
//panel image. This is my second panel which will be for the images
final JPanel second = new JPanel(new BorderLayout());
//panel button. This is the third panel for the buttons
rows = 0;
cols = 3;
hgap = 5;
vgap = 0;
JPanel third = new JPanel(new GridLayout(rows,cols,hgap,vgap));
//buttons
JButton boutonLoad1 = new JButton("Load image A");
boutonLoad1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int retour = fc.showDialog(frame, "Charger l'image");
if(retour == JFileChooser.APPROVE_OPTION){
String pathImage1 = fc.getSelectedFile().getAbsolutePath();
path1 = pathImage1;
File file = fc.getSelectedFile();
MonPanelImage panelImage1 = new MonPanelImage(file);
second.add(panelImage1, BorderLayout.WEST);
second.revalidate();
second.repaint();
}
}
});
最后,我将3个面板添加到我的框架并将框架设置为可见。 但我不能画一幅图像。也许我没有正确地做到这一点。有人能帮帮我吗?
由于
答案 0 :(得分:2)
super.paintComponents(g);
首先,它应该是super.paintComponent(g)
,而不是"s"
。
second.add(panelImage1, BorderLayout.WEST);
您正在使用BorderLayout将图像添加到组件。 BorderLayout将尊重组件的宽度,即0,因此无需绘制任何内容。
每当您进行自定义绘制时,您需要覆盖getPreferredSize()
方法以返回组件的大小,以便布局管理器完成其工作。
但是,更简单的解决方案是使用JLabel
和Icon
。当您以真实尺寸绘制图像时,无需进行自定义绘制。