Solved

Pixel Color at clickPoint

Posted on 2004-08-12
9
267 Views
Last Modified: 2010-03-31
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
0
Comment
Question by:delphi3
  • 4
  • 3
  • 2
9 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11786320
If  Image, use a PixelGrabber, if a BufferedImage, you can use getRGB
0
 
LVL 1

Expert Comment

by:SlimHealer
ID: 11787159
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();
    }
}

0
 
LVL 4

Author Comment

by:delphi3
ID: 11792436
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11792627
>>I have already drawn the image on a panel

And what's happened to the image - presumably you still have a reference to it?
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 4

Author Comment

by:delphi3
ID: 11793647
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);
     
    }
   
   
  }
}
0
 
LVL 1

Accepted Solution

by:
SlimHealer earned 50 total points
ID: 11795531
The trick is to render into a backing buffered image, and extract the color from said image.  Here's your code back atcha, re-worked to extract a color on a click.  The whole thing should be pasted into a file called "Example.java"...


import java.awt.*;
import java.awt.event.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.UIManager;


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;
class HexImgOnPnlWBorderFrame extends JFrame {
    JPanel jpnlDisplay;
    BorderLayout borderLayout1 = new BorderLayout();
    JPanel jPanel1 = new JPanel();
    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 );
    }

    //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;
class MyPanelA extends JPanel {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();
    BufferedImage bi;
    Point clickPoint = null;

    public MyPanelA() {
        addMouseListener( new MouseAdapter()        {
            public void mousePressed( MouseEvent event ) {
                clickPoint = event.getPoint();
                int x = (int) clickPoint.getX();
                int y = (int) clickPoint.getY();
                System.out.println( "X = " + x + ", Y = " + y );
                System.out.println( new Color( bi.getRGB( x, y ) ) );
                repaint();
            }
        } );
    }

    void handleRender() {
        Dimension dim = getSize();
        bi = gc.createCompatibleImage( (int) dim.getWidth(), (int) dim.getHeight() );
        Graphics2D ig = (Graphics2D) bi.createGraphics();
        ig.setColor( Color.red );
        ig.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++) {
            ig.setColor( loc_clr[ci] );
            int a = loc_a[ci];
            int id = loc_id[ci];
            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++) {
                    gp1.lineTo( (int) (a * ib + HexaPtsX[ic]), (int) (a + id + HexaPtsY[ic]) );
                }
            }
            gp1.closePath();
            ig.fill( gp1 );
        }
        ig.dispose();
    }

    public void paintComponent( Graphics g ) {
        super.paintComponent( g );
        // note that we can be much smarter about things, and regenerate the backing image only when needed...
        handleRender();
        g.drawImage( bi, 0, 0, this );
    }
}


public class Example {
    public Example() {
        HexImgOnPnlWBorderFrame f = new HexImgOnPnlWBorderFrame();
        addListeners( f );
        f.setSize( 500, 500 );
        f.setVisible( true );
    }

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

    public static void main( String[] args ) {
        new Example();
    }
}
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
ID: 11799794
>>The trick is to render into a backing buffered image, and extract the color from said image

Yep - that's the way i'd do it
0
 
LVL 4

Author Comment

by:delphi3
ID: 11799849
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
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11800137
:-)
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now