JFileChooser é possivel ter preview?

1 resposta
cardosodario

Amigos,

Eu criei um programinha onde o usuario pode alterar o icone dos botões, estou usando o JFileChooser para poder selecionar os icones, eu gostaria de saber se tem como ter um preview dentro deste componente para o usuario ir olhando os icones antes de selecionar como no explorer do windows.
Caso não alguém tem alguma ideia?

Dario.

1 Resposta

H

É só colocar um Acessory no JFIleChooser:

JFileChooser chooser = new JFileChooser();
PreviewPane previewPane = new PreviewPane();
chooser.setAccessory(previewPane);
chooser.addPropertyChangeListener(previewPane);
chooser.showDialog(frame, "OK");

static class PreviewPane extends JPanel implements PropertyChangeListener {
	private JLabel label;
	private int maxImgWidth;
	public PreviewPane() {
		setLayout(new BorderLayout(5,5));
		setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		add(new JLabel("Preview:"), BorderLayout.NORTH);
		label = new JLabel();
		label.setBackground(Color.WHITE);
		label.setOpaque(true);
		label.setPreferredSize(new Dimension(200, 200));
		maxImgWidth = 195;
		label.setBorder(BorderFactory.createEtchedBorder());
		add(label, BorderLayout.CENTER);
	}
 
	public void propertyChange(PropertyChangeEvent evt) {
		Icon icon = null;
		if(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt
					.getPropertyName())) {
			File newFile = (File) evt.getNewValue();
			if(newFile != null) {
				String path = newFile.getAbsolutePath();
				if(path.endsWith(".gif") || path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".bmp")) {
					try {
						BufferedImage img = ImageIO.read(newFile);
						float width = img.getWidth();
						float height = img.getHeight();
						float scale = height / width;
						width = maxImgWidth;
						height = (width * scale); // height should be scaled from new width							
						icon = new ImageIcon(img.getScaledInstance(Math.max(1, (int)width), Math.max(1, (int)height), Imag.SCALE_SMOOTH));
					}
					catch(IOException e) {
						// couldn't read image.
					}
				}
			}
				
			label.setIcon(icon);
			this.repaint();
					
		}
	}
}

[]s

Criado 25 de fevereiro de 2008
Ultima resposta 25 de fev. de 2008
Respostas 1
Participantes 2