我要做的是创建一个gui,允许您选择一个图像,显示图像,然后在它上面为学校项目执行操作。这是启动时发生的事情。 完美!但是,当我更新图标时,它会在其后面添加新图标:
以下是我在Jlabel上使用的代码:
ImageIcon imageIcon = new ImageIcon();
try {
imageIcon = new ImageIcon(ImageIO.read(new File("/Users/ryanauger/Repos/JavaGUI/GUI/Images/cameraIcon.png")));
} catch (IOException e2) {
// TODO Auto-generated catch block
imageIcon = new ImageIcon();
e2.printStackTrace();
}
JLabel lblNewLabel = new MyJLabel(imageIcon);
lblNewLabel.setBounds(0, 6, 600, 600);
frame.getContentPane().add(lblNewLabel);
JButton btnNewButton = new JButton("Pick Image File");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser jfc;
jfc = new JFileChooser();
File f = new File(System.getProperty("user.dir"));
jfc.setCurrentDirectory(f);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
jfc.showOpenDialog(btnNewButton);
File selFile = jfc.getSelectedFile();
try {
lblNewLabel.setIcon(new ImageIcon(ImageIO.read(new File(selFile.getAbsolutePath()))));
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(selFile.getAbsolutePath());
e1.printStackTrace();
}
}
});
我是java的新手,所以任何帮助都表示赞赏。谢谢!
编辑:这是MyJLabel的代码:
class MyJLabel extends JLabel
{
ImageIcon imageIcon;
public MyJLabel(ImageIcon icon)
{
super();
this.imageIcon = icon;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(imageIcon.getImage(),0,0,getWidth(),getHeight(),this);
}
}
答案 0 :(得分:3)
当您致电
时,您的问题就出现了JLabel lblNewLabel = new MyJLabel(imageIcon);
您正在将图标存储在自己的图标中,而不是将图标传递给超类。所以当你画画时,它会画相机。然后当你打电话:
lblNewLabel.setIcon(new ImageIcon(ImageIO.read(new File (selFile.getAbsolutePath()))));
您实际上正在调用超类的setIcon()方法,而不是更改您在本地存储的Icon。然后超级类别就像应该的那样绘制手机,但你也在相机上画画。