Link to home
Start Free TrialLog in
Avatar of delphi3
delphi3

asked on

Pixel Color at clickPoint

Hi All,

This is not homework.

I have an image drawn and need to identify the color of the respective pixel when I use a


  jPnlMiddle.addMouseListener(
        new MouseAdapter() {
      public void mousePressed(MouseEvent event) {
        clickPoint = event.getPoint();
        System.out.println("X = " + clickPoint.getX() + ", Y = " +
                           clickPoint.getY());
        // What I am attempting to get is a System.out.println("Color is = ", Clr);
        repaint();
      }
    });

Help is appreciated and so is an example.

Delphi3
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

If  Image, use a PixelGrabber, if a BufferedImage, you can use getRGB
Avatar of SlimHealer
SlimHealer

Here's a compile-ready example that displays a gradient filled image, and responds to clicks as you request.


import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class TestCase extends JFrame
{
      static final int             w = 400;
      static final int             h = 400;

      GraphicsEnvironment            ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      GraphicsDevice                   gd = ge.getDefaultScreenDevice();
      GraphicsConfiguration      gc = gd.getDefaultConfiguration();
      BufferedImage                   bi = gc.createCompatibleImage( w, h );
      boolean                              initialized = false;

   class TestPanel extends JPanel {
            Color Clr;

        public TestPanel() {
              setPreferredSize( new Dimension(w,h));
                  addMouseListener( new MouseAdapter() {
                        public void mousePressed(MouseEvent event) {
                              Point clickPoint = event.getPoint();
                              if ( bi != null) {
                                    int x = (int) clickPoint.getX();
                                    int y = (int) clickPoint.getY();
                                    int val = bi.getRGB(x,y);
                                    Clr = new Color(val);
                                    System.out.println("X = " + x + ", Y = " + y);
                                    System.out.println("Color is = " + Clr);
                              }
                        }
                  });
        }

        public void paint( Graphics g ) {
            super.paint( g );
                  g.drawImage(bi, 0, 0, this);
        }
    }

    public TestCase() {
        super( "TestCase" );
        addListeners();
        initBaseImage();
        addPanels();
        pack();
        setVisible( true );
    }

    // Intialize the base image with a gradient fill.  We could use anything here.
    void initBaseImage() {
            Graphics2D ig = (Graphics2D) bi.createGraphics();
            GradientPaint gp = new GradientPaint( 0,0, Color.red, w, h, Color.cyan, false );
            ig.setPaint( gp );
            ig.fillRect( 0, 0, w, h);
            ig.dispose();
      }

    void addPanels() {
        getContentPane().setLayout( new GridLayout( 1, 1, 10, 10 ) );
             getContentPane().add( new TestPanel() );
    }

    void addListeners() {
        addWindowListener( new WindowAdapter()        {
            public void windowClosing( WindowEvent e ) {
                System.exit( 0 );
            }
        } );
    }

    public static void main( String[] args ) {
        new TestCase();
    }
}

Avatar of delphi3

ASKER

Hi to both of you.

I don't see how it will work, either way using the pixelgrabber or the buffer method.

 I have already drawn the image on a panel which is not done using buffering to begin with. I have the clickpoint that will identify the location of the point. Can I copy/put the pixel into the buffer one pixel wide and ask it to tell me the color. Is that possible?

D3
>>I have already drawn the image on a panel

And what's happened to the image - presumably you still have a reference to it?
Avatar of delphi3

ASKER

CEHJ,

Here's my code that I have. It is not the cleanest thing  but what  I can show you at this time.

I need to create a color recogintion test: "Click on a yellow Hexagon".  Praise follows  if a yellow is clicked on. I thought of the user selecting just a rectangular region (x,y,x+12,y+12) but an area such as this is not appropriate because of the inter linking of the figures.
 
 
D3  

//package heximgonpnlwborder;

import javax.swing.UIManager;
import java.awt.*;

public class HexImgOnPnlWBorder {
  boolean packFrame = false;
 
  //Construct the application
  public HexImgOnPnlWBorder() {
    HexImgOnPnlWBorderFrame frame = new HexImgOnPnlWBorderFrame();
    //Validate frames that have preset sizes
    //Pack frames that have useful preferred size info, e.g. from their layout
    if (packFrame) {
      frame.pack();
    }
    else {
      frame.validate();
    }
    //Center the window
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    if (frameSize.height > screenSize.height) {
      frameSize.height = screenSize.height;
    }
    if (frameSize.width > screenSize.width) {
      frameSize.width = screenSize.width;
    }
    frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
  }
  //Main method
  public static void main(String[] args) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    new HexImgOnPnlWBorder();
  }
}



//package heximgonpnlwborder;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;


public class HexImgOnPnlWBorderFrame
  extends JFrame {
  JPanel jpnlDisplay;
  BorderLayout borderLayout1 = new BorderLayout();
  JPanel jPanel1 = new JPanel();
  Point clickPoint = null;
private TitledBorder titledBorder1;
  private BorderLayout borderLayout2 = new BorderLayout();
 
  private GridLayout gridLayout1 = new GridLayout();
  private MyPanelA jPnlMiddle = new MyPanelA();
 
  //Construct the frame
  public HexImgOnPnlWBorderFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  //Component initialization
  private void jbInit() throws Exception {
   
    Color Clr;
    jpnlDisplay = (JPanel)this.getContentPane();
    titledBorder1 = new TitledBorder("");  
    this.setSize(new Dimension(190, 225));
    this.setTitle("Hex Shape");
    jPanel1.setLayout(null);
    BevelBorder loweredBevelBorder = (BevelBorder)BorderFactory.createLoweredBevelBorder();
    jPnlMiddle.setBorder(loweredBevelBorder);
    jPnlMiddle.setBounds(new Rectangle(12, 63, 152, 97));
    jPnlMiddle.setLayout(borderLayout2);
   
    jPanel1.add(jPnlMiddle, null);
    jpnlDisplay.setBorder(loweredBevelBorder);
    jpnlDisplay.setLayout(borderLayout1);
    jpnlDisplay.add(jPanel1, BorderLayout.CENTER);
   
    jPnlMiddle.addMouseListener(
                                new MouseAdapter() {
      public void mousePressed(MouseEvent event) {
        clickPoint = event.getPoint();
        System.out.println("X = " + clickPoint.getX() + ", Y = " +
                           clickPoint.getY());
        repaint();
      }
    });
  }
 
  //Overridden so we can exit when window is closed
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }
}







//package heximgonpnlwborder;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;

public class MyPanelA extends JPanel {
 
  public MyPanelA() {    
  }
 
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
         
    g.setColor(Color.red);
    g.drawString("Hexagons",75,25);
    int HexAGons = 5;
   
    int [] loc_a  = {24,48,36,60,48};
    int [] loc_id  = {0,-24,10,-14,20};
    Color [] loc_clr = {Color.blue,Color.yellow,Color.red,Color.green,Color.magenta};
   
   
    int HexaPts = 7;
    int HexaPtsX[] = new int[HexaPts];
    int HexaPtsY[] = new int[HexaPts];
   
   
    int rad = 15; // radius of circle containing hexagon
    int x1, y1;
    for (int i = 0; i < HexaPts; i++) {
      x1 = (int) (rad * Math.cos((2 * Math.PI / 6)*(0.5+i)));
      y1 = (int) (rad * Math.sin((2 * Math.PI / 6)*(0.5+i)));
      HexaPtsX[i]=x1;
      HexaPtsY[i]=y1;
    }
    for (int ci = 0; ci <5; ci++){
      g.setColor(loc_clr [ci]);
      int a = loc_a [ci];
      int id = loc_id [ci];  
     
      Graphics2D g2d = (Graphics2D) g;
      GeneralPath gp1 = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
      gp1.moveTo((int)(a  + HexaPtsX[0]),(int)(a + id + HexaPtsY[0]));
     
      for (int ib = 1; ib <2; ib++) {
        for (int ic = 1; ic < HexaPts - 1; ic++) {  // six + 1 sides
          gp1.lineTo((int)(a * ib + HexaPtsX[ic]),(int)(a + id + HexaPtsY[ic]));
        }
      }
      gp1.closePath();
      g2d.fill(gp1);
     
    }
   
   
  }
}
ASKER CERTIFIED SOLUTION
Avatar of SlimHealer
SlimHealer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of delphi3

ASKER

Hi,

Thanks to you both. "backing buffered image".

A real bit of computer wizardry.

Since the original post was worth 50 points and the expectations were for only 50 points, then here is another bit of wizardry. I am feeling really generous today.
D3
:-)