Erro ao selecionar a borda da imagem

1 resposta
tartaruga.df

Pessoal,

Meu código pega uma imagem e coloca na tela. Depois disso tenho que capturar o ponto do pixel da imagem quando clico com o mouse mas quando clico na borda na ultima linha ou coluna da imagem dá o seguinte erro:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
	at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)
	at java.awt.image.BufferedImage.getRGB(Unknown Source)
	at TrabalhaImagem$3.mousePressed(TrabalhaImagem.java:146)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$200(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)

Clicando em qualquer outro ponto funciona normalmente.

o código que estou usando é esse:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class TrabalhaImagem extends JFrame {

	private JPanel painelNorte = new JPanel();

	private JPanel Central = new JPanel();
	private JPanel painelImagem = new JPanel();
	private Container container;
	private FlowLayout layout;
	private JButton botaoCarregar;
	private JButton botaoMatriz;
	private JButton botaoIniciar;

	private BufferedImage imagemOriginal = null;
	private BufferedImage imagemResultado = null;

	private int larguraImagem;
	private int alturaImagem;
	private int imagem[][];
	private int limiar;
	private int pixelLinha;

	private final int BORDER = 10;

	public int getPixelLinha() {
		return pixelLinha;
	}

	public TrabalhaImagem() throws IOException {

		super("Inicio");
		container = getContentPane();
		setLayout(layout);

		botaoCarregar = new JButton("Buscar Imagem Local");
		painelImagem = new JPanel();
		botaoMatriz = new JButton("Gerar Matriz");

		botaoIniciar = new JButton("Iniciar Varredura");

		painelNorte.setLayout(new GridLayout(2, 5));
		painelNorte.setBackground(Color.white);
		painelNorte.add(botaoCarregar);
		painelNorte.add(botaoMatriz);
		painelNorte.add(botaoIniciar);

		Central.add(painelImagem);
		Central.setBackground(Color.gray);

		this.setLayout(new BorderLayout());
		this.add("North", painelNorte);
		this.add("Center", Central);

		botaoCarregar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				BufferedImage image = null;
				JFileChooser arquivo = new JFileChooser();
				arquivo.setDialogTitle("Escolha uma imagem");

				arquivo.setFileFilter(new javax.swing.filechooser.FileFilter() {

					public boolean accept(File f) {
						return f.getName().toLowerCase().endsWith(".jpg")
								|| f.isDirectory()
								|| f.getName().toLowerCase().endsWith(".png")
								|| f.getName().toLowerCase().endsWith(".gif")
								|| f.getName().toLowerCase().endsWith(".jpeg");
					}

					public String getDescription() {
						return "Arquivos de imagem (.jpg, .png, .gif, .jpeg)";

					}
				});
				int res = arquivo.showOpenDialog(null);

				if (res == JFileChooser.APPROVE_OPTION) {

					File arquivos = arquivo.getSelectedFile();
					{
						try {
							image = ImageIO.read(arquivos);
							imagemOriginal = image;
						} catch (IOException ex) {
							JOptionPane.showMessageDialog(null,
									"Erro ao processar imagem.");
						}
					}

					ImageIcon im = new ImageIcon(image);

					JLabel label1 = new JLabel();
					label1.setPreferredSize(new Dimension(image.getWidth()
							+ BORDER, image.getHeight() + BORDER));

					label1.setVerticalAlignment(SwingConstants.CENTER);
					label1.setHorizontalAlignment(SwingConstants.CENTER);
					label1.setIcon(im);
					painelImagem.setBorder(BorderFactory.createEmptyBorder());
					painelImagem.setPreferredSize(new Dimension(image
							.getWidth() + 2 * BORDER, image.getHeight() + 2
							* BORDER));
					painelImagem.add(label1, null);
					painelImagem.setVisible(true);

				} else
					JOptionPane.showMessageDialog(null,
							"Voce nao selecionou nenhum arquivo.");
			}
		});

		});
		// captura a posição da tela
		painelImagem.addMouseListener(new MouseListener() {
			public void mousePressed(MouseEvent e) {

				int c = imagemOriginal.getRGB(e.getX(), e.getY());

				int red = (c & 0x00ff0000) >> 16;
				int green = (c & 0x0000ff00) >> 8;
				int blue = c & 0x000000ff;

				System.out.println("Cores: Vermelho = " + red + ", Verde = "
						+ green + ", Azul = " + blue);
				System.out.println("RGB da imagem: " + c);
				System.out.println("Posição marcada: " + red + " " + e.getX()
						+ " / " + e.getY());
				System.out.println("Largura da imagem: "
						+ imagemOriginal.getWidth());
				System.out.println("Altura da imagem: "
						+ imagemOriginal.getHeight());

			}

			public void mouseClicked(MouseEvent e) {
			}

			public void mouseEntered(MouseEvent e) {
			}

			public void mouseExited(MouseEvent e) {
			}

			public void mouseReleased(MouseEvent e) {
			}
		});

	}
}

1 Resposta

ViniGodoy

Teste se o evento onClick está mesmo sobre a imagem. Não é raro ele indicar um pixel além da borda.

Além disso, esse código está desnecessariamente rebuscado:
int c = imagemOriginal.getRGB(e.getX(), e.getY());  
  
int red = (c & 0x00ff0000) >> 16;  
int green = (c & 0x0000ff00) >> 8;  
int blue = c & 0x000000ff;
O correto seria:
Color c = new Color(imagemOriginal.getRGB(e.getX(), e.getY()));  
  
    int red = c.getRed();  
    int green = c.getGreen();  
    int blue = c.getBlue();
Criado 10 de novembro de 2012
Ultima resposta 10 de nov. de 2012
Respostas 1
Participantes 2