Getting MouseListener on panel containing canvas'

Hi.
I'm using Java 1.2 and AWT, and have created a simple colour scale.
At the moment, I am trying to code it so that clicking on one square within the scale will highlight it. To do this I tried adding a MouseListener to the scale itself --- but this didn't seem to work.
Any help would be much appreciated!
public class ColourScale extends java.awt.Panel {
    private ColourSquare cs[];
    private int csNum;
    private boolean squareNum;
    private java.awt.GridBagConstraints gridBagConstraints;
    /** Creates a new instance of ColourScale */
    public ColourScale(int cn) {
        int i = 0;
        csNum = 0;
        squareNum = true;
        cs = new ColourSquare[6];
        for (i = 0; i < 6; i++) {
            cs[i] = new ColourSquare();
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                java.awt.Point pt = evt.getPoint();
                for(int i = 0; i < csNum; i++) {
                    if (cs.contains(pt)) {
cs[i].setMyBorder(true);
} else {
if(squareNum) {
cs[i].setMyBorder(false);
if (cn > 6 || cn < -1) {
cn = 6;
setCsNum(cn);
setLayout(new java.awt.GridLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 0;
for(i = 0; i < cn; i++) {
gridBagConstraints.gridx = i;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(cs[i]);
class ColourSquare extends java.awt.Canvas {
private int bgColour;
private boolean border;
ColourSquare() {
super();
bgColour = 0;
border = false;
setSize(new java.awt.Dimension(15, 15));
// addMouseListener(new java.awt.event.MouseAdapter() {
// public void mouseClicked(java.awt.event.MouseEvent evt) {
// ColourSquare c = (ColourSquare) evt.getSource();
// c.setMyBorder(!c.getMyBorder());
public int getBgColour() {
return bgColour;
public void setBgColour (int newC) {
bgColour = newC;
repaint();
public boolean getMyBorder() {
return border;
public void setMyBorder(boolean newB) {
border = newB;
repaint();
public void paint(java.awt.Graphics g) {
// changes square colours, and draws border around square...

Here's something:import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
    public Test () {
        setContentPane (new TestPanel ());
        setDefaultCloseOperation (EXIT_ON_CLOSE);
        setTitle ("Test");
        pack ();
        setLocationRelativeTo (null);
        setVisible (true);
    public static void main (String[] parameters) {
        new Test ();
    private class TestPanel extends JPanel {
        private final int cx = 3;
        private final int cy = 3;
        private ClickablePanel[][] clickablePanels;
        private ClickablePanel selectedPanel;
        public TestPanel () {
            setLayout (new GridLayout (cx, cy));
            clickablePanels = new ClickablePanel[cy][cx];
            for (int r = 0; r < cy; r ++) {
                for (int c = 0; c < cx; c ++) {
                    clickablePanels[r][c] = new ClickablePanel ();
                    add (clickablePanels[r][c]);
            selectedPanel = null;
            addMouseListener (new MouseAdapter () {
                public void mouseClicked (MouseEvent event) {
                    selectedPanel = (ClickablePanel) findComponentAt (event.getPoint ());
                    for (int r = 0; r < cy; r ++) {
                        for (int c = 0; c < cx; c ++) {
                            clickablePanels[r][c].setSelected (clickablePanels[r][c] == selectedPanel);
                            clickablePanels[r][c].repaint ();
        public Dimension getPreferredSize () {
            return new Dimension (cx * 50, cy * 50);
        private class ClickablePanel extends JPanel {
            private boolean selected;
            public ClickablePanel () {
                selected = false;
            public void setSelected (boolean selected) {
                this.selected = selected;
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                int w = getWidth ();
                int h = getHeight ();
                g.drawLine (0, 0, 0, h);
                g.drawLine (0, h, w, h);
                g.drawLine (w, h, w, 0);
                g.drawLine (w, 0, 0, 0);
                if (selected) {
                    g.drawLine (0, 0, w, h);
                    g.drawLine (0, h, w, 0);
}Kind regards,
  Levi

Similar Messages

  • Adding mouselistener on Panel and Canvas

    Hi,
    I m building an application in which I m making a frame, adding a panel on it and then adding a Canvas on the panel. On this Canvas my Native C code is drawing an Image. This image is very small with respect to the size of the frame.
    The size of the Panel and the Canvas is made equal to the size of Image drawn.
    Now I want a mouseclick event on this image.
    Now the problem is that when I add mouselistener to the Panel I don't get any event.
    And when I add mouselistener to the Canvas I get the event but I get the event on the whole frame even if I set the canvas size equal to the drawn image size. I only want the mouse event only if mouse is clicked on the image.
    Can anyone tell the mistake or suggest any other way of doing this ?

    Hi,
    I m building an application in which I m making a frame, adding a panel on it and then adding a Canvas on the panel. On this Canvas my Native C code is drawing an Image. This image is very small with respect to the size of the frame.
    The size of the Panel and the Canvas is made equal to the size of Image drawn.
    Now I want a mouseclick event on this image.
    Now the problem is that when I add mouselistener to the Panel I don't get any event.
    And when I add mouselistener to the Canvas I get the event but I get the event on the whole frame even if I set the canvas size equal to the drawn image size. I only want the mouse event only if mouse is clicked on the image.
    Can anyone tell the mistake or suggest any other way of doing this ?

  • Unable to find the  'Panel Container 2' object

    Hi,
    I am unable to find the  'Panel Container 2' object under the containers folder of components. I am using xcelsius enterprise 2008.
    I have a scenario where in which i need to use it, Is there any way I can get it into the canvas.
    Thanks in advance,
    Shreesh.

    Hi,
    Which Theme are you using now? Not all of the themes have "Panel Container 2" object. Theme "Aqua" and Theme "Nova" have "Panel Container 2", please try them.
    Thanks,
    Grace

  • How to find out if a panel contains a specific component

    I am in a situation where i need to know whether a panel contains a specific component or not, like is there a specific method for that.
    To clarify, example :
    Suppose i have a panel
    JPanel p1;
    p1 = new JPanel();
    JLabel label = new JLabel("LABEL");
    p1.add(label);In this code i already know that p1 contains label, however at runtime, i would like to know if p1 contains label or not (assuming i removed the label at some point)

    verminator wrote:
    I thought that should have done the trick, and maybe it will, but did i do something wrong here :
    JPanel p1 = new JPanel();
    JLabel l1 = new JLabel("LABEL");
    p1.add(l1);
    if(isDescendingFrom(l1,p1))          //error here
    System.out.println("true");
    else
    System.out.println("false");
    }do you have to import some other package other than javax.swing.SwingUtilities for this method, because i'm getting an error "cannot find symbol" referring to the isDescendingFrom() methodSwingUtilities isn't a package, it's a class. isDescendingFrom() is a static method in that class.
    To call isDescendingFrom(), it should look like this:
    SwingUtilities.isDescendingFrom(c1, c2);

  • Panel or canvas into swf

    Dear friends,
    I am developing a simple application to convert a panel or a
    canvas (whatever i am having in that panel or canvas) into swf
    file.
    In that i need how to proceed to convert into swf.
    can anyone help me in this regards?
    thanx,
    Dhinakaran.C
    to convert a panel or a canvas (whatever i am having in that
    panel or canvas) to swf file

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.setLayout(null);
        for (int i=0; i<5; i++) {
          JLabel jl = new JLabel(new ImageIcon("C:\\duke.gif"));
          jl.setToolTipText("Tip-" + i);
          jl.setBounds(i%3*40, i/3*40,30,30);
          content.add(jl);
        setSize(200,200);
        setVisible(true);
      public static void main(String[] args) { new Test(); }
    }

  • Having trouble getting objects on panel

    i am just attempting to build a simple gui frame and am having some trouble getting my labels to appear. here is what I have for the panel that the labels and buttons will be on. everything shows up no problem except clearButton and welcome2. Any suggestions would be greatly appreciated...thanks in advance
    class CountClicks2Panel extends JPanel
    constructs a count-clicks-1 panel instance
    public CountClicks2Panel()
    // button has not been clicked yet
    this.numClicks = 0;
    // create the labels and buttons for this panel
    JLabel welcome = new JLabel("Button-Click Counter");
    welcome.setForeground(Color.BLUE);
    JLabel welcome2 = new JLabel("Jared Letendre");
    welcome2.setForeground(Color.RED);
    JButton clickMe = new JButton("Click Me");
    clickMe.setForeground(Color.BLUE);
    clickMe.setBackground(Color.RED);
    JButton clearButton = new JButton("Clear Count");
    clearButton.setForeground(Color.BLUE);
    clearButton.setBackground(Color.RED);
    showNumClicks = new JLabel("# of clicks: " +
    this.numClicks);
    // add labels and button to this panel
    this.add(welcome);
    this.add(clickMe);
    this.add(showNumClicks);
    this.add(welcome2);
    this.add(clearButton);
    // create button action (so clicks will be counted),
    // and associate that action with clickMe button
    CountClicks2Action countAction = new CountClicks2Action();
    CountClicks2Action clearAction = new CountClicks2Action();
    clearButton.addActionListener(clearAction);
    clickMe.addActionListener(countAction);
    } // end CountClicks2Panel

    Sorry about that...i put it in code blocks originally but it didnt show when i previewed it...anyway here is the complete code. thanks for helping out
    import  java.awt.*;
    import  java.awt.event.*;
    import  javax.swing.*;
       A GUI application with a button for which the number
       of clicks is kept track of and displayed
       @author Sharon Tuttle
       @version 09-10-07
    public class CountClicks2Test
           creates a CountClicks1 frame
           @param args not used here
        public static void main(String args[])
            CountClicks2Frame mainFrame = new CountClicks2Frame();
            mainFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
            mainFrame.setVisible(true);   
       A frame with a panel containing two labels and a button
    class CountClicks2Frame extends JFrame
           constructs a count-clicks-1 frame instance
        public CountClicks2Frame()
            this.setTitle("Button-click Counter");
            this.setSize(this.DEFAULT_WIDTH, this.DEFAULT_HEIGHT);
            // add count-clicks-1 panel to frame
            CountClicks1Panel panel = new CountClicks1Panel();
            this.add(panel);
        // data fields
        private final static int DEFAULT_WIDTH = 150;
        private final static int DEFAULT_HEIGHT = 200;
       A panel with two labels and a button, that displays how many times
       the button has been clicked
    class CountClicks2Panel extends JPanel
           constructs a count-clicks-1 panel instance
        public CountClicks2Panel()
            // button has not been clicked yet
            this.numClicks = 0;
            // create the labels and buttons for this panel
            JLabel welcome = new JLabel("Button-Click Counter");
            welcome.setForeground(Color.BLUE);
            JLabel welcome2 = new JLabel("Jared Letendre");
            welcome2.setForeground(Color.RED);
            JButton clickMe = new JButton("Click Me");
            clickMe.setForeground(Color.BLUE);
            clickMe.setBackground(Color.RED);
            JButton clearButton = new JButton("Clear Count");
            clearButton.setForeground(Color.BLUE);
            clearButton.setBackground(Color.RED);
            showNumClicks = new JLabel("# of clicks: " +
                                       this.numClicks);
            // add labels and button to this panel
            this.add(welcome);
            this.add(clickMe);
            this.add(showNumClicks);
            this.add(welcome2);
            this.add(clearButton);
            // create button action (so clicks will be counted),
            //    and associate that action with clickMe button
            CountClicks2Action countAction = new CountClicks2Action();
            CountClicks2Action clearAction = new CountClicks2Action();
            clearButton.addActionListener(clearAction);
            clickMe.addActionListener(countAction);
        } // end CountClicks2Panel constructor 
           An action listener that counts the number of times the
           clickMe button has been clicked
        private class CountClicks2Action implements ActionListener
            // default constructor will suffice, in this case
               increases and displays the number of clicks of this
               button
            public void actionPerformed(ActionEvent event)
                CountClicks2Panel.this.numClicks++;
                CountClicks2Panel.this.showNumClicks.setText(
                    "# of clicks: "
                    + CountClicks2Panel.this.numClicks);
            public void actionPerformed2(ActionEvent event2)
                 CountClicks2Panel.this.numClicks = 0;
                 CountClicks2Panel.this.showNumClicks.setText(
                    "# of clicks: "
                    + CountClicks2Panel.this.numClicks);
        // data fields for CountClicks1Panel
        private int numClicks;
        private JLabel showNumClicks;
    } // end of class CountClicks1Panel

  • Panel and Canvas

    Hi all,
    I am working on a maintenance project.
    in this project,the programmers have used Canvas.
    But i want to use panel.
    Is there any difference between Panel and canvas.
    Regards,
    Tapas

    Panel is a container (and may contain subcomponents).
    Cnavas is a simple drawing surface component.
    Ragnvald Barth
    Software enigneerhttp://blake.prohosting.com/ragnvald

  • HT4759 i downloaded the icloud to my pc it says to login with apple id and it says it is a valid apple id but not cloud but i cannot get the control panel for icloud to come up to set it up on my pc which runs windows 8

    i downloaded the icloud to my pc it says to login with apple id and it says it is a valid apple id but not cloud but i cannot get the control panel for icloud to come up to set it up on my pc which runs windows 8

    An update.
    From iCloud Control Panel 2.1.1 for Windows
    "iCloud Control Panel 2.1 and later includes support for Windows 8"
    but you still need to set it up on a Mac or iOS device, "Note: To create an iCloud account you need an iPhone, iPad, or iPod touch with iOS 5 or later, or a Mac with OS X Lion v10.7.5 or later."

  • I have re-installed Adobe Reader on to my Windows 7 PC. When I open a PDF I was getting an error message containing  . . . .Acrord32.exe application error . . . . I now cannot open any PDF's. Adobe seems to be unresponsive.

    I have re-installed Adobe Reader on to my Windows 7 PC. When I open a PDF I was getting an error message containing  . . . .Acrord32.exe
    I now cannot open any PDF's and Adobe seems unresponsive. I have tried to follow a step by step guide on how to fix this but Adobe won't stay open long enough for me to complete the steps. When I open Adobe it stays open for a matter of seconds then minimises to the task bar and when I click on it again I can't do anything with it and have to close it via task manager
    Please help!?

    Disabling Protected Mode should fix the problem.  But since you cannot even open Adobe Reader by itself, you need to do it via the Windows registry.  If you tell me your installed Reader version, I can give you a registry script to do that.

  • I got locked out of Mac os 9 and now I can't get into OS 9 or OS X.  All I see is the Macintosh SE and a finder face and text that says "mac os 9.2 welcome to mac os".  I can't get into COntrol Panel to reset the password to allow me to get in.

    I got locked out of Mac os 9 and now I can't get into OS 9 or OS X.  All I see is the Macintosh SE and a finder face and text that says "mac os 9.2 welcome to mac os".  I can't get into COntrol Panel to reset the password to allow me to get in.

    Do you have OS X and OS 9 installed on your Mac? If so, startup with the Option key depressed. This will open the Startup Manager window. Select the OS you want to start from & click the right arrow.
     Cheers, Tom

  • Can I get the kuler panel in illustrator cs6?

    I Cant get the kuler panel to work in illustrator cs6.

    everyone here is right, dreamweaver is better and you will need to understand html for this to work. HOWEVER, you can make a functional website using just illustrator and notepad (or text edit if you're on a mac).
    Design your site in illy, slice it up with the slice tool. http://s23.postimg.org/mv311kpp7/test_illy.jpg 
    Save for web and select html and images, you'll get an html file and an images folder. Open the HTML file in your text editing program and it will look like this: http://s10.postimg.org/f32nf6r2h/html_stuff.jpg   you'll have to know HTML codes but you can find tutorials online for most stuff, you'll just have to figure it out. In my fake site, i linked a button to google so i had to add <a href> tags to the code. http://s22.postimg.org/5avpadhch/a_href.jpg  save the html file and open it in your web browser, hopefully not IE. You can't tell in the picture but the middle button actually does link to google. http://s21.postimg.org/qd77slqmf/firefox.jpg

  • How do i get the password panel to come up??

    the only help i get drom apple is tro go to a dealer and pay for a new hard drive

    That's kind of nuts.  
    Apple menu -> System Preferences -> Accounts  or Users & Groups
    Turn off the auto-login feature.  This will allow you to get the password panel on startup.

  • How do I get the basic panel in the develop module to reappear in Lightroom 5?

    Hello! I was editing a photo in Lightroom 5 the other day, and I thought I hit something, but all of a sudden the basic panel was missing. I went online to see how I can fix it, and what was suggested was to right click on one of the panels and it should have an option that says basic, in order to get the basic panel back. That is what I did, but what it does is just opens and closes the panels. I don't know how to get my basic panel back, I hope I can get some advice.
    Thank You!

    The trick is to right-click on one of the other panel headers, e.g. Tone Curve, and you'll see a context menu allowing you ro reselect the Basic Panel.
    Alternatively, when in the Develop Module simply do Ctrl+1 (Cmd+1 on a Mac), or in the menu bar go to Window>Panels>Basic Panel.

  • Browser.download.useToolkitUI to true on the about:config to get old download panel Does NOT work. How do I get it back?

    Firefox 26:
    The fix turning browser.download.useToolkitUI to true on the about:config does not work. How do I get rid of the library crap and get my download panel back?

    Mozilla, if a large number of people use a feature to the point that they are digging in to the configuration to re-enable it when you turn it off my default, please don't remove the feature altogether. It disrupts users' browsing experience and upsets them.

  • Problem with scrolling a panel containing an image

    I am having a problem adding scrolling capabilities to a tabbed panel containing pages containing an image. In my program, I have a class called ImagePanel that extends JPanel and contains an image read from a file. In another class, I create a tabbed panel and add to it ImagePanels.
    The problem I'm facing is that the pages added to my tabbed panel contain scroll bars, but these scroll bars are not scrollable (i.e. I cannot use the bars the scroll and see the missing parts of the image).
    Any help on this manner is highly appreciated.
    The code is shown below:
    JTabbedPane m_pathwayTabbedPane = new JTabbedPane();
    ImageIcon overviewImageIcon = IconLoader.readImageIcon(pathway.gif);
    ImagePanel overviewPanel = new ImagePanel(overviewImageIcon.getImage());
    JScrollPane graphcrollPane = new JScrollPane(overviewPanel,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    m_pathwayTabbedPane.addTab(StringManager.OVERVIEW, graphcrollPane);

    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ScrollingImages
        public static void main(String[] args)
            String[] fileNames = {
                "images/bclynx.jpg", "images/mtngoat.jpg", "images/redfox.jpg"
            JPanel panel = new JPanel(new GridBagLayout());
            panel.setBackground(Color.black);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.gridwidth = gbc.REMAINDER;
            for(int j = 0; j < fileNames.length; j++)
                panel.add(new ImageComponent(fileNames[j]), gbc);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(panel));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class ImageComponent extends JPanel
        Image image;
        public ImageComponent(String fileName)
            loadImage(fileName);
            setBackground(Color.black);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = image.getWidth(this);
            int imageHeight = image.getHeight(this);
            int x = (w - imageWidth)/2;
            int y = (h - imageHeight)/2;
            g.drawImage(image, x, y, this);
         * For the JScrollPane which will inquire about our size
         * which it needs to properly set its scrollbars.
        public Dimension getPreferredSize()
            return new Dimension(image.getWidth(this), image.getHeight(this));
        private void loadImage(String fileName)
            try
                URL url = getClass().getResource(fileName);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.out.println(mue.getMessage());
            catch(IOException ioe)
                System.out.println(ioe.getMessage());
    }

Maybe you are looking for

  • Computer Fan

    So my computer has been randomly shutting down on me for the last couple of days. When I turn my computer back on it says a cooling error in one of my fans has occured. How do I go about fixing this problem so my computer doesnt keep randomly shuttin

  • Bigfile in oracle 10g

    Hi All, I have a bigfile in oracle 10g which is of size 110G and its located in E drive.Now the problem i am facing is Drive E:\ has only 5GB free space left and the considering the data growth 5GB wont sufice long.Other drives in server have suffici

  • SirAdmin Deleting Mail Accounts

    I am trying to get to grips with siradmin and deleting mailaccounts which have become corrupted. I have created a user called mailman in wgm who belongs to no group. I have logged on as root opened siradmin logged in as mailman. The address is the se

  • Several tabs leading to single page?

    Hi I'd like to use Tabs as the key navigation vehicle in my app. They give the user info where he/she is, where he/she can go and enable arbitrary graphical desing. But I need several tabs leading to the same page, The page's content is just parametr

  • How can we know who deleted the objects (iView, Page, ...) ?

    Hi All Can you tell us how to find the Portal user id that deleted iView ? Thank you very much, Anek.