Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Pixel Color at clickPoint

Posted on 2004-08-12
9
Medium Priority
?
282 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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
 
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 200 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 200 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

916 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