gui重绘的问题

时间:2011-06-05 14:35:36

标签: java image swing user-interface repaint

第一次选择图像时,效果很好。但是当我尝试更改它时,它不起作用,第一个图像保留在屏幕上。

label = new JLabel("");
panel_1.add(label); 

btnAddImage = new JButton("Select Image");
btnAddImage.addMouseListener(new MouseAdapter() {
@Override
  public void mouseClicked(MouseEvent arg0) {
  File f = null ;
  fileChooser = new JFileChooser();
  fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  int value = fileChooser.showOpenDialog(fileChooser);
  if (value == JFileChooser.APPROVE_OPTION)
  {
    f = fileChooser.getSelectedFile();
    if (f.exists())
    {
      inputImage_textField.setText(f.getName());        
      BufferedImage bi = getMyBuffImage();
      label = new JLabel(new ImageIcon(bi));
      label.setBounds(0, 68, 98, 92);
      panel_1.add(label);
      panel_1.repaint();
    }
   }
 }
});

当我重新粉饰或其他问题时,我做错了吗?

由于

1 个答案:

答案 0 :(得分:2)

如果要替换现有标签,请替换

label = new JLabel(new ImageIcon(bi));
label.setBounds(0, 68, 98, 92);
panel_1.add(label);
panel_1.repaint();

label.setIcon(new ImageIcon(bi));
label.setBounds(0, 68, 98, 92);
panel_1.revalidate();

或者如果您想添加第二个标签,只需替换

即可
label = new JLabel(new ImageIcon(bi));
label.setBounds(0, 68, 98, 92);
panel_1.add(label);
panel_1.repaint();

JLabel newLabel = new JLabel(new ImageIcon(bi));
label.setBounds(0, 68, 98, 92);
panel_1.add(newLabel);
panel_1.revalidate();