Hi,

I have to add a mouse over event and mouse click event in my rectangles that I draw while taking the values from an input file. Now since I am taking rectangle height and width from the input text file as well I also want to take a text value to be shown while moving a mouse over a particular rectangle from my input file. Also when user clicks on that rectangle the height and width of that particular rectangle only should be displayed (re-adjusted).

Like suppose my input file has 3 fields:-

Height   Width  Test_To_Show
10          23         Hello
20          44         Bye

Now When my paint component draws these 2 rectangles and a user moves his mouse over the rectangle he should see text message attached to it:- Like for first row 10, 23 he should see "Hello". In this case when he clicks on this rectangle the picture should read just to show only 10 and 20 as height and width.
I am trying to write 2 classes. 1st one extends JPanel and the other one MouseInputAdapter.

It would be great to get help and guidance from you guys.

Thanks

Post your initial code that is drawing the rectangles. As a general suggestion, keep a List containing java.awt.Rectangle objects for each entry you have to draw. Your mouseMoved and mouseClicked method implementations can easily test against those Rectangle objects by their contains() methods.

Alternately you could use a null layout and JLabels or a small JComponent class for your rectangles, which would manage some of the mouseover handling for you.

Hi,
I have written this code based on your guidance. I would be obliged to get corrections. I really want to make it work... Only addition I did is I have added 4rth field for color in the input file. That would be some values.

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.util.List;
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.geom.Rectangle2D;
import java.awt.Rectangle;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class MousingExample extends JPanel {

  public MousingExample(Frame f) 
  {
        tips = new ArrayList<String>();
        tips.add("Lets Start The Show");
        toolTip = new JWindow(f);
        label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(UIManager.getColor("MousingExample.background"));
        label.setBorder(UIManager.getBorder("MosusingExample.border"));
        toolTip.add(label);
        setOpaque(true);
  }

    public ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
    public int width;
    public String color;
    public static int score;
    public static int value1;
    public static int value2;
    private final static int NUM_FIELDS = 4;


    public void InputReader() {

        String n = null;  
        try{
            BufferedReader fh = new BufferedReader(new FileReader("inputfile.txt"));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){
               // System.out.println(n);
                f = n.split("\t");
                int height = Integer.parseInt(f[0].trim());
                int width = Integer.parseInt(f[1].trim());
                String message = f[2];
                Color color = new Color(Integer.parseInt(f[3]));
                Rectangle tempLineInfo = new Rectangle(color, value1, value2, width);
                rects.add(tempLineInfo);}
            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }  
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        setBackground(Color.white);

        for(int i=0; i<rects.size(); i++){
            Rectangle c = rects.get(i);
            GradientPaint gpi = new GradientPaint(0, 0,c.getColor() , 0, 20, Color.white, true);
            g2d.setPaint(gpi);
            g2d.drawRect(c.value1, 20, c.width, 35);
            g2d.fillRect(c.value1, 20, c.width, 35);
            System.out.printf("Drawing at %s\n", c);
        } 
    }     
                             
    public static void main(String[] args) {
    
        MousingExample test = new MousingExample();
        test.InputReader();
        Tipster tipster = new Tipster(test);
        test.addMouseListener(tipster);
        test.addMouseMotionListener(tipster);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Trying To MouseOver");
        frame.setSize(400, 400);
        frame.setContentPane(test);
        frame.setVisible(true);
    }
}

class Rectangle {
    private Color color;
    public int value1;
    public int value2;
    public int width;

    public Rectangle(Color c, int value1, int value2, int width){
        this.color = c;
        this.value1 = value1;
        this.value2 = value2;
        this.width = width;
    }

    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), value1, value2, width);
    }
}

class Tipster extends MouseInputAdapter
{
    MousingExample Mousing;
    Point start;
 
    public Tipster(MousingExample tt)
    {
        MousingExample = tt;
    }
 
    public void mousePressed(MouseEvent e) { } 
    public void mouseReleased(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) { }
 
    public void mouseMoved(MouseEvent e)
    {
        List<Rectangle> rects = MousingExample.Rectangle;
        //Not Sure what I should do here
    }
}

Here is the input file example below:-

Height   Width  Test_To_Show   Colors
10          23         Hello        300
20          44         Bye      000

Hope to get help soon.

Thanks

Sorry I forgot to initialize :-

List<String> tips;
JWindow toolTip;
JLabel label;

In my MousingExample class.

Thanks and plz reply

Here is my modified code but still not getting what I want :(

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.util.List;
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.geom.Rectangle2D;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class MousingExample extends JPanel {
    List<String> tips;
    JWindow toolTip;
    JLabel label;
    public String f[];
  public MousingExample(Frame f) 
  {
        tips = new ArrayList<String>();
        tips.add("Lets Start The Show");
        toolTip = new JWindow(f);
        label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(UIManager.getColor("MousingExample.background"));
        label.setBorder(UIManager.getBorder("MosusingExample.border"));
        toolTip.add(label);
        setOpaque(true);
  }

    public ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
    public int width;
    public String color;
    public static int score;
    public static int value1;
    public static int value2;
    private final static int NUM_FIELDS = 4;


    public void InputReader() {

        String n = null;  
        try{
            BufferedReader fh = new BufferedReader(new FileReader("inputfile.txt"));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){
               // System.out.println(n);
                f = n.split("\t");
                int height = Integer.parseInt(f[0].trim());
                int width = Integer.parseInt(f[1].trim());
                String message = f[2];
                Color color = new Color(Integer.parseInt(f[3]));
                Rectangle tempLineInfo = new Rectangle(color, value1, value2, width);
                rects.add(tempLineInfo);
            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }  
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        setBackground(Color.white);

        for(int i=0; i<rects.size(); i++){
            Rectangle c = rects.get(i);
            GradientPaint gpi = new GradientPaint(0, 0,c.getColor() , 0, 20, Color.white, true);
            g2d.setPaint(gpi);
            g2d.drawRect(c.value1, 20, c.width, 35);
            g2d.fillRect(c.value1, 20, c.width, 35);
            System.out.printf("Drawing at %s\n", c);
        } 
    }     
                             
    public static void main(String[] args) {
    

        JFrame frame = new JFrame();
        MousingExample test = new MousingExample(frame);
        test.InputReader();
        Tipster tipster = new Tipster(test);
        test.addMouseListener(tipster);
        test.addMouseMotionListener(tipster);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Trying To MouseOver");
        frame.setSize(400, 400);
        frame.setContentPane(test);
        frame.setVisible(true);
    }
}

class Rectangle {
    private Color color;
    public int value1;
    public int value2;
    public int width;

    public Rectangle(Color c, int value1, int value2, int width){
        this.color = c;
        this.value1 = value1;
        this.value2 = value2;
        this.width = width;
    }

    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), value1, value2, width);
    }
}

class Tipster extends MouseInputAdapter
{
    MousingExample Mousing;
    Point start;
 
    public Tipster(MousingExample tt)
    {
        Mousing = tt;
    }
 
    public void mousePressed(MouseEvent e) { } 
    public void mouseReleased(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) { }
 
    public void mouseMoved(MouseEvent e)
    {
        List<Rectangle> rects = MousingExample.Rectangle;
        //Not Sure what I should do here
    }
}

Here is one more correction to my previous code:-

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.util.List;
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.geom.Rectangle2D;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class MouseExample extends JPanel {
    List<String> tips;
    JWindow toolTip;
    JLabel label;
    public String f[];
  public MouseExample(Frame f) 
  {
        tips = new ArrayList<String>();
        tips.add("Lets Start The Show");
        toolTip = new JWindow(f);
        label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(UIManager.getColor("MouseExample.background"));
        label.setBorder(UIManager.getBorder("MosusingExample.border"));
        toolTip.add(label);
        setOpaque(true);
  }

    public ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
    public int width;
    public String color;
    public static int score;
    public static int value1;
    public static int value2;
    private final static int NUM_FIELDS = 4;


    public void InputReader() {

        String n = null;  
        try{
            BufferedReader fh = new BufferedReader(new FileReader("inputfile.txt"));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){
               // System.out.println(n);
                f = n.split("\t");
                int height = Integer.parseInt(f[0].trim());
                int width = Integer.parseInt(f[1].trim());
                String message = f[2];
                Color color = new Color(Integer.parseInt(f[3]));
                Rectangle tempLineInfo = new Rectangle(color, value1, value2, width);
                rects.add(tempLineInfo);
            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }  
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        setBackground(Color.white);

        for(int i=0; i<rects.size(); i++){
            Rectangle c = rects.get(i);
            GradientPaint gpi = new GradientPaint(0, 0,c.getColor() , 0, 20, Color.white, true);
            g2d.setPaint(gpi);
            g2d.drawRect(c.value1, 20, c.width, 35);
            g2d.fillRect(c.value1, 20, c.width, 35);
            System.out.printf("Drawing at %s\n", c);
        } 
    }     
                             
    public static void main(String[] args) {
    

        JFrame frame = new JFrame();
        MouseExample test = new MouseExample(frame);
        test.InputReader();
        Tipster tipster = new Tipster(test);
        test.addMouseListener(tipster);
        test.addMouseMotionListener(tipster);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Trying To MouseOver");
        frame.setSize(400, 400);
        frame.setContentPane(test);
        frame.setVisible(true);
    }
}

class Rectangle {
    private Color color;
    public int value1;
    public int value2;
    public int width;

    public Rectangle(Color c, int value1, int value2, int width){
        this.color = c;
        this.value1 = value1;
        this.value2 = value2;
        this.width = width;
    }

    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), value1, value2, width);
    }
}

class Tipster extends MouseInputAdapter
{
    MouseExample Mousing;
    Point start;
 
    public Tipster(MouseExample tt)
    {
        Mousing = tt;
    }
 
    public void mousePressed(MouseEvent e) { } 
    public void mouseReleased(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) { }
 
    public void mouseMoved(MouseEvent e)
    {

    }
}

Thanks

Where you got this code? There are so many statements either meaningless or written falsely.

1. As stated by Ezzaral, Rectangle classes create ambiguity.
2. MousingExample class has no definition

MousingExample test = new MousingExample();

3. What about this? Is this a way to instantiate MousingExample.Rectangle.

List<Rectangle> rects = MousingExample.Rectangle;

Well I never said I am an expert :) lol. I was looking at many examples and just trying to make my story. I know I am doing many things wrongly. Perhaps this is the first time I am using Java 2D swing. So plz be nice to my mistakes.

Thanks.

Hi... I did some modifications to my mouseMoved function as below:-

public void mouseMoved(MouseEvent e)
    {
        Point p = e.getPoint();
        boolean traversing = false;
        List<Rectangle> rect = mousing.rects;
        for(int i; i<rect.size() ; i++ ){ 
            Rectangle r = rect.get(i);
            if(r.contains(p)) {
              
               // I am not sure howto assign something like setText() method to read from my input file f[2] field so that the message comes up. Need help here .!! 
 
                break;
            }
        }
    }

Thanks

Hi this is new version of my program. I am still struggling :( Need your kind guidance.

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.util.List;
import java.awt.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.geom.Rectangle2D;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class MouseExample extends JPanel {
    List<String> tips;
    JWindow toolTip;
    JLabel label;
    public String f[];
  public MouseExample(Frame f) 
  {
        tips = new ArrayList<String>();
     //   tips.add("Lets Start The Show");
        toolTip = new JWindow(f);
        label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(UIManager.getColor("MouseExample.background"));
        label.setBorder(UIManager.getBorder("MosusingExample.border"));
        toolTip.add(label);
        setOpaque(true);
  }

    public ArrayList<Rectangle> rects = new ArrayList<Rectangle>();
    public int width;
    public String color;
    public static int score;
    public static int value1;
    public static int value2;
    private final static int NUM_FIELDS = 4;


    public void InputReader() {

        String n = null;  
        try{
            BufferedReader fh = new BufferedReader(new FileReader("inputfile.txt"));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){
               // System.out.println(n);
                f = n.split("\t");
                int height = Integer.parseInt(f[0].trim());
                int width = Integer.parseInt(f[1].trim());
                String message = f[2];
                tips.add(message);
                Color color = new Color(Integer.parseInt(f[3]));
                Rectangle tempLineInfo = new Rectangle(color, value1, value2, width);
                rects.add(tempLineInfo);
            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }  
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        setBackground(Color.white);

        for(int i=0; i<rects.size(); i++){
            Rectangle c = rects.get(i);
            GradientPaint gpi = new GradientPaint(0, 0,c.getColor() , 0, 20, Color.white, true);
            g2d.setPaint(gpi);
            g2d.drawRect(c.value1, 20, c.width, 35);
            g2d.fillRect(c.value1, 20, c.width, 35);
            System.out.printf("Drawing at %s\n", c);
        } 
    }   
      public boolean isToolTipShowing()
    {
        return toolTip.isShowing();
    }
       public void showToolTip(int index, Point p)
    {
        for(index = 0; index<tips.size();index++){
        label.setText(tips.get(index));
        }
        toolTip.pack();
        toolTip.setLocation(p);
        toolTip.setVisible(true);
    }
 
                             
    public static void main(String[] args) {
    

        JFrame frame = new JFrame();
        MouseExample test = new MouseExample(frame);
        test.InputReader();
        Tipster tipster = new Tipster(test);
        test.addMouseListener(tipster);
        test.addMouseMotionListener(tipster);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Trying To MouseOver");
        frame.setSize(400, 400);
        frame.setContentPane(test);
        frame.setVisible(true);
    }
}

class Rectangle {
    private Color color;
    public int value1;
    public int value2;
    public int width;

    public Rectangle(Color c, int value1, int value2, int width){
        this.color = c;
        this.value1 = value1;
        this.value2 = value2;
        this.width = width;
    }

    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), value1, value2, width);
    }
}

class Tipster extends MouseInputAdapter
{
    MouseExample mousing;
    Point start;
 
    public Tipster(MouseExample tt)
    {
        mousing = tt;
    }
 
    public void mousePressed(MouseEvent e) { } 
    public void mouseReleased(MouseEvent e) { }
    public void mouseDragged(MouseEvent e) { }
 
    public void mouseMoved(MouseEvent e)
    {
Point p = e.getPoint();
        boolean traversing = false;
        List<Rectangle> rect = mousing.rects;
        for(int i; i<rect.size() ; i++ ){ 
            Rectangle r = rect.get(i);
            if(r.contains(p)) {
              if(!mousing.isToolTipShowing())
                {
                    SwingUtilities.convertPointToScreen(p, mousing);
                    mousing.showToolTip(i, p);
                }
                traversing = true;
                break;
            }
        }
    }
}

Thanks

You've defined your own Rectangle class, so you can't expect to use the java.awt.Rectangle method contains() for a hit test on that. You could change your class a little to keep a java.awt.Rectangle internally for it's bounds and use that for the hit testing and stuff.

For the tooltip behavior, I think you'd have an easier time just using JLabels for your rectangles, which already have a tool tip that you can just set directly, instead of your custom class. You can also set their size, location, text, and background color directly on JLabels and you inherit a ton of JComponent methods for handling other UI behaviors if you need them.

If you decide to stick with a class that uses a Rectangle and rendering it yourself, I would recommend moving the rendering code into the class itself by adding a draw(Graphics g) method and passing in the graphics reference. You can then draw the label string yourself if need be and your frame class doesn't have to keep track of all of the pieces. Your paintComponent() methods would just loop your List and call draw() on each of them.

Hi I am completely lost :( How can I accomodate java.awt.Rectangle to my Rectangle class ? I am confused since never done this before.
I tried many combinations but unfortunately all failed to give desired results :(
If there is a breakthrough I will inform you but as of now I am completely lost :(

Thanks

Ok, here's a small example using a Glyph class that internally uses Rectangle to manage its bounds and shows a label when moused over:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class RectangleMouseover extends JFrame {
    
    private JPanel paintPanel;

    public RectangleMouseover() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(300, 300));

        paintPanel = new  PaintPanel();
        getContentPane().add(paintPanel, BorderLayout.CENTER);
        pack();
    }

    class PaintPanel extends JPanel implements MouseMotionListener {
        private List<Glyph> glyphs;
        
        public PaintPanel(){
            super();
            addMouseMotionListener(this);

            glyphs = new ArrayList<Glyph>();
            glyphs.add(new Glyph(25, 15, 60, 30, Color.BLUE, "Blue node"));
            glyphs.add(new Glyph(75, 60, 50, 60, Color.ORANGE, "Orange node"));
        }
        
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (Glyph glyph : glyphs){
                glyph.draw(g);
            }
        }

        public void mouseDragged(MouseEvent e) {}

        public void mouseMoved(MouseEvent e) {
            for(Glyph g : glyphs){
                g.showLabel( g.contains(e.getX(), e.getY()) );
            }
            repaint();
        }
    }

    class Glyph {
        private Rectangle bounds;
        private Color color;
        private String label;
        private boolean showLabel = false;

        public Glyph(int x, int y, int width, int height, Color color, String label) {
            bounds = new Rectangle(x, y, width, height);
            this.color = color;
            this.label = label;
        }

        public void draw(Graphics g){
            Graphics2D g2 = (Graphics2D)g;
            g2.setColor(color);
            g2.draw(bounds);
            if (showLabel){
                g2.setColor(Color.BLACK);
                int labelWidth = g2.getFontMetrics().stringWidth(label);
                int fontHeight = g2.getFontMetrics().getHeight();
                g2.drawString( label, 
                   (int)(bounds.getX() + (bounds.getWidth()-labelWidth) / 2), 
                   (int)(bounds.getY() + (bounds.getHeight()+fontHeight/2) / 2d));
            }
        }

        public boolean contains(int x, int y){
            return bounds.contains(x,y);
        }

        public void showLabel(boolean show){
            showLabel = show;
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RectangleMouseover().setVisible(true);
            }
        });
    }
}

As I mentioned before, using JLabel instead of a custom Glyph class would get you a lot of that functionality for free.

Hi Thanks for your kind suggestions... I am able to come this far but still one problem is there. In this code I donno howto deal with the Constructor. Since at the end I am doing like this

public void run() {
      new RectangleMouseover().setVisible(true);
      }
      });

I don't know howto pass my constructor with values and make it work. I know that is the problem why my code below is showing empty window. How can I deal with this problem ? I just created a dummy empty constructor to make this code work but donno howto pass my actual construtor with values ?

I mean howto pass my this constructor

RectangleMouseover(int height, int fixvalue1, int width, int fixvalue2, Color c,String text)
import java.io.*;
      import java.awt.BorderLayout;
      import java.awt.Color;
      import java.awt.Dimension;
      import java.awt.Graphics;
      import java.awt.Graphics2D;
      import java.awt.Rectangle;
      import java.awt.event.MouseEvent;
      import java.awt.event.MouseMotionListener;
      import java.util.ArrayList;
      import java.util.List;
      import javax.swing.JFrame;
      import javax.swing.JPanel;
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.BufferedReader;

      public class RectangleMouseover extends JFrame {
              public Color color;
              public int height;
              public int fixvalue1;
              public int fixvalue2;
              public int width;
              public String text;
              
              private JPanel paintPanel;
              public RectangleMouseover(){
                  
              }
              
      public RectangleMouseover(int height, int fixvalue1, int width, int fixvalue2, Color c,String text) {
        this.color = c;
        this.height = height;
        this.fixvalue1 = fixvalue1;
        this.width = width;
        this.fixvalue2 = fixvalue2;
        this.text = text;

      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setMinimumSize(new Dimension(800, 400));
      paintPanel = new PaintPanel();
      getContentPane().add(paintPanel, BorderLayout.CENTER);
      pack();
      }
      class PaintPanel extends JPanel implements MouseMotionListener {
      private List<Glyph> glyphs;
          public int height;
          public int width;
          public String f[];
          
      public PaintPanel(){
      super();
      addMouseMotionListener(this);
      glyphs = new ArrayList<Glyph>();
              String n = null;  
        try{
            BufferedReader fh = new BufferedReader(new FileReader("InputFile.txt"));    
            while((n = fh.readLine()) != null && (n = n.trim()).length() > 0){

                f = n.split("\t");
                int height = Integer.parseInt(f[0].trim());
                int width = Integer.parseInt(f[1].trim());
                String text = f[2];
                Color color = new Color(Integer.parseInt(f[3]));
                int fixvalue1 = 60;
                int fixvalue2 = 27;

                glyphs.add(new Glyph(height, fixvalue1, width, fixvalue2, color, text));

            }
            fh.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e2) {
            e2.printStackTrace();
        }
      }
      public void paintComponent(Graphics g) {
      super.paintComponent(g);
      for (Glyph glyph : glyphs){
      glyph.draw(g);
      }
      }
      public void mouseDragged(MouseEvent e) {}
      public void mouseMoved(MouseEvent e) {
      for(Glyph g : glyphs){
      g.showLabel( g.contains(e.getX(), e.getY()) );
      }
      repaint();
      }
      }
      class Glyph {
      private Rectangle bounds;
      private Color color;
      private String label;
      private boolean showLabel = false;
      public Glyph(int x, int y, int width, int height, Color color, String label) {
      bounds = new Rectangle(x, y, width, height);
      this.color = color;
      this.label = label;
      }
      public void draw(Graphics g){
      Graphics2D g2 = (Graphics2D)g;
      g2.setColor(color);
      g2.draw(bounds);
      if (showLabel){
      g2.setColor(Color.BLACK);
      int labelWidth = g2.getFontMetrics().stringWidth(label);
      int fontHeight = g2.getFontMetrics().getHeight();
      g2.drawString( label,
      (int)(bounds.getX() + (bounds.getWidth()-labelWidth) / 2),
      (int)(bounds.getY() + (bounds.getHeight()+fontHeight/2) / 2d));
      }
      }
      public boolean contains(int x, int y){
      return bounds.contains(x,y);
      }
      public void showLabel(boolean show){
      showLabel = show;
      }
      }
      public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
      new RectangleMouseover().setVisible(true);
      }
      });
      }
    public Color getColor(){
        return color;
    }

    public String toString() {
        return String.format("Color=%s,top=%d,bottom=%d,width=%d", color.toString(), height, fixvalue1, width, fixvalue2, text);
    }
      }

My input file is like this:-

10	40	Web_Sailor	003
51	60	Ezzaral	000
112	46	DaniWeb	933

Thanks

Ezzral you are great :-) I cracked it myself :-)
I called the constructor like this: - constructor(0, 0, 0, 0, null, null) and it worked.
I know its very basic for you but for me its new ;-) lo
Thanks a lot for your kind guidance. Again I can tell you are great :-) lol.

Now I am working to add a drag function on this code. Will let you know my progress once I reach to some extent :-)

Thanks a lot.

Hi... I am now trying to use gradient paint in my code but again getting into complications. Also my code is not taking colors from my text input field.

I am trying to do something like this inside Glyph class:-

    for(int i=0; i<glyph.size(); i++){
        PaintPanel c = glyph.get(i);

        GradientPaint gpi = new GradientPaint(0, 0,c.getColor() , 0, 20, Color.white, true);
      //  g2d.setColor(c.getColor());
        g2d.setPaint(gpi);
        g2d.drawRect(c.height, fixedvalue1, c.width, fixedvalue2);
        g2d.fillRect(c.height, fixedvalue1, c.width, fixedvalue2);

Will it work ? but I need to do it.

Thanks

Dear Ezzaral since the initial problem is solved so I marked it as solved to add a feather to your cap :-)
I have opened another thread "Contd from Mouse Event" in which I have posted my code for Gradient paint. Please have a look and guide me where I am wrong. That code is compiling but I am getting runtime errors.

Thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.