0

I am new to Java swing desktop graphics applications I got an issue please suggest i need to select a some of the rectangles and fill the rectangles with do we any predefined concept is there like rubber band if any please suggest me to start a drawing

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Exam extends JPanel implements MouseMotionListener {

    private static final int recW = 50;
    private static final int MAX = 100;
    private Rectangle[] rect = new Rectangle[MAX];
    private int numOfRecs = 0;
    private int currentSquareIndex = -1;
    private Point startPoint = new Point();
    private Point currentPoint = new Point();
    private int x, y, width, height;
    private Stroke dashedStroke = new BasicStroke(0.0f, BasicStroke.CAP_ROUND,
            BasicStroke.CAP_SQUARE, 5.0f, new float[] { 5f, 5f, 5f, 5f }, 5.0f);

    ArrayList list = new ArrayList();

    public Exam() {

        addRect(50, 50);
        addRect(100, 50);
        addRect(150, 50);
        addRect(200, 50);
        addRect(250, 50);
        addRect(300, 50);
        addRect(350, 50);
        addRect(400, 50);
        addRect(450, 50);
        addRect(500, 50);
        //
        addRect(50, 100);
        addRect(100, 100);
        addRect(150, 100);
        addRect(200, 100);
        addRect(250, 100);
        addRect(300, 100);
        addRect(350, 100);
        addRect(400, 100);
        addRect(450, 100);
        addRect(500, 100);
        //
        addRect(50, 150);
        addRect(100, 150);
        addRect(150, 150);
        addRect(200, 150);
        addRect(250, 150);
        addRect(300, 150);
        addRect(350, 150);
        addRect(400, 150);
        addRect(450, 150);
        addRect(500, 150);
        //
        addRect(50, 200);
        addRect(100, 200);
        addRect(150, 200);
        addRect(200, 200);
        addRect(250, 200);
        addRect(300, 200);
        addRect(350, 200);
        addRect(400, 200);
        addRect(450, 200);
        addRect(500, 200);

        addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent evt) {
                startPoint = evt.getPoint();
            }

            public void mouseReleased(MouseEvent e) {

                System.out.println(" mouseReleased is " + e.getX() + " y i s "
                        + e.getY());
                Graphics g = getGraphics();
                Graphics2D g2 = (Graphics2D) g;
                g2.setComposite(AlphaComposite.SrcOver.derive(0.8f));
                Color myColour = new Color(255, 0, 0);
                g.setColor(myColour);
                x = Math.min(startPoint.x, currentPoint.x);
                y = Math.min(startPoint.y, currentPoint.y);
                width = Math.abs(startPoint.x - currentPoint.x);
                height = Math.abs(startPoint.y - currentPoint.y);
                rect[numOfRecs] = new Rectangle(x, y, width, height);
                // System.out.println("list size is:"+list.size());
                 Rectangle ggg=new Rectangle(x, y, width, height);
            for(Rectangle rect3d: rect){
                if(ggg.intersects(rect3d)){
                g2.fill(rect3d);
                }
                else
                    System.out.println("doesn't contains");
                }
repaint();
            }

        });

        addMouseMotionListener(this);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < numOfRecs; i++) {
            ((Graphics2D) g).draw(rect[i]);
            list.add(rect[i]);
        }

        x = Math.min(startPoint.x, currentPoint.x);
        y = Math.min(startPoint.y, currentPoint.y);
        width = Math.abs(startPoint.x - currentPoint.x);
        height = Math.abs(startPoint.y - currentPoint.y);
        ((Graphics2D) g).setStroke(dashedStroke);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, width, height);
        // Rectangle dashedRec=new Rectangle(x, y, width, height);

    }

    public void addRect(int x, int y) {
        if (numOfRecs < MAX) {
            rect[numOfRecs] = new Rectangle(x, y, recW, recW);
            currentSquareIndex = numOfRecs;
            numOfRecs++;
            repaint();
        }
    }

    @Override
    public void mouseMoved(MouseEvent event) {
    }

    @Override
    public void mouseDragged(MouseEvent event) {

        currentPoint = event.getPoint();
        repaint();
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        jFrame.setTitle("");
        jFrame.setSize(600, 300);
        Container cPane = jFrame.getContentPane();
        cPane.add(new Exam());
        jFrame.setVisible(true);
    }
}
Vskiran
  • 69
  • 2
  • 8
  • Welcome to Stack Overflow. Please read [Stack Overflow: How to ask](http://stackoverflow.com/questions/how-to-ask) and [Jon Skeet's Question Checklist](http://msmvps.com/blogs/jon_skeet/archive/2012/11/24/stack-overflow-question-checklist.aspx) to find out how to ask a good question that will generate good useful, answers. – Our Man in Bananas Jul 17 '14 at 12:54
  • please show us what you have tried, some code and maybe a jsfiddle – Our Man in Bananas Jul 17 '14 at 12:54
  • MouseMotionListener doesn't react to mousePressed/Clicked – mKorbel Jul 17 '14 at 13:03
  • I have pasted some code please check it once and suggest me to go through the selection of rectangles – Vskiran Jul 17 '14 at 13:03
  • mouse dragged is related to mouse motion listener right – Vskiran Jul 17 '14 at 13:10
  • A complete example is cited [here](http://stackoverflow.com/a/11944233/230513). – trashgod Jul 17 '14 at 14:31

3 Answers3

1

You should start by changing import java.awt.event.MouseMotionListener;

to

import java.awt.event.MouseListener;

mousePressed does not go with MouseMotionListener

charles
  • 61
  • 8
  • Thank you but no one is suggesting and concentrationg on my issue can you please suggest solution for that While dragging i am selecting some of the rectangles which i need to fill color in such away that if i dragged two small rectangles also it should fill the whole rectangle. – Vskiran Jul 17 '14 at 13:32
1

I see the class name is Exam, so since this is for school, I won't give you code solution. Just some logical ways to look at it.

I notice that when you drag the mouse, you are just getting a point and drawing based off that point. What you should do instead is, when the mouse is first pressed, create a Rectangle (and draw the rectangle), and while the mouse is being dragged, increase the size of the rectangle with setRect(). You can see a good example here.

Depending, if you want the color change to be dynamic (while dragging or when dragging is done), you have two options:

  1. While dragging iterate through the list of rectangles and check if each rectangle in the list intersects or is contained by the dragged rectangle. Rectangle inherits method intersects() and contains() from Shape

  2. If you just want the color changed when the dragging is finished, then do the same as above, when the mouse is released.


Also note, you should not be using getGraphics() in any way to do custom painting. All the painting should be done within the context of the Graphics object provided in the paintComponent method


UPDATE

Here is an example based on the points I made above. The example expands on the example provided in the link above

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class RectangleDrawWithDrag extends JPanel{

    private static final int D_W = 400;
    private static final int D_H = 400;
    private static final Color DEFAULT_COLOR = Color.GRAY;
    private static final Color SELECT_COLOR = Color.BLUE;
    private static final Color CURSOR_COLOR = new Color(100, 100, 100, 100);

    private Point p1;
    private Point p2;
    private Rectangle2D rectangle;
    private List<ColoredRectangle> rectangles;

    public RectangleDrawWithDrag() {
        rectangles = createRectangleList();
        addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e) {
                p1 = e.getPoint();
                rectangle = new Rectangle2D.Double(p1.x, p1.y, p1.x - p1.x, p1.y - p1.y);
            }
        });
        addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseDragged(MouseEvent e) {
                p2 = e.getPoint();
                if (isPointTwoInQuadOne(p1, p2)) {
                    rectangle.setRect(p2.x, p2.y, p1.x - p2.x, p1.y - p2.y);
                } else {
                    rectangle.setRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);  
                }
                checkRectangleContainment();
                repaint();
            }
        });
    }

    public void checkRectangleContainment() {
        for (ColoredRectangle rects: rectangles) {
            if (rectangle.contains(rects.getRectangle())) {
                rects.setColor(SELECT_COLOR);
            } else {
                rects.setColor(DEFAULT_COLOR);
            }
        }
    }

    public boolean isPointTwoInQuadOne(Point p1, Point p2) {
        return p1.x >= p2.x && p1.y >= p2.y;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        for (ColoredRectangle rect: rectangles) {
            rect.draw(g2);
        }
        if (rectangle != null) {
            g2.setColor(CURSOR_COLOR);
            g2.fill(rectangle);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_W, D_H);
    }

    private List<ColoredRectangle> createRectangleList() {
        List<ColoredRectangle> rects = new ArrayList<>();
        Random rand= new Random();
        for (int i = 0; i < 20; i++) {
            rects.add(new ColoredRectangle(rand.nextInt(D_W), rand.nextInt(D_H)));
        }
        return rects;
    }

    public class ColoredRectangle {
        Rectangle2D rectangle;
        Color color = DEFAULT_COLOR;
        double size = 20;

        public ColoredRectangle(double x, double y) {
            rectangle = new Rectangle2D.Double(x, y, size, size);
        }

        public ColoredRectangle(double x, double y, double size) {
            this.size = size;
            rectangle = new Rectangle2D.Double(x, y, size, size);
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public Rectangle2D getRectangle() {
            return rectangle;
        }

        public void draw(Graphics2D g2) {
            g2.setColor(color);
            g2.fill(rectangle);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new RectangleDrawWithDrag());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}
Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • No thank you for this help but the example given is not at all related to my output i need to use the intersect color method or contains method in rectangle can you give examples on those methods to draw the rectangles. – Vskiran Jul 18 '14 at 08:58
  • You see how when you drag your mouse, you are just getting a point, and then drawing the rectangle based on the point? What the example does, is it creates a `Rectangle` from the initial pointt, and expands the `Rectangle` as the mouse is dragged. What is being drawn is the `Rectangle`, unlike in your example, where you are drawing based on a point, and not a Rectangle. The difference is that with the `Rectangle`, you can use `rectangle.contains(anotherRetangle)` which return a boolean if the inside rectangle is contained by the outside one – Paul Samsotha Jul 18 '14 at 09:16
  • So basically, you can loop through your array of `Rectangle` in the `mouseDragged` to see if each rectangle is contained. If it is contained, you can change it's color in the painComponent method – Paul Samsotha Jul 18 '14 at 09:18
  • Maybe in a couple hours when I have time, I'll try to expand on that example to show you – Paul Samsotha Jul 18 '14 at 09:19
  • Check out my **UPDATE**. It's an example with the technique I described – Paul Samsotha Jul 18 '14 at 09:47
  • oh nice one it helped me a lot in my requirement but the thing is now i am getting my requirement partially when i am selecting rectangles i am filling intersected rectangles but first rectangle is getting filled and i dont want to visible the dasshed line can you please help in this i am updating my code please check it – Vskiran Jul 18 '14 at 11:00
  • your `g2.fill` should not be in the `mouseXxx` method. Like I said, all the paintcing should be done in the paintComponent method. To make changes, you call `repaint()`. But you need to anticipate what will be drawn and already have it in the paintComponent method. Please go over my code to see what I am talking about – Paul Samsotha Jul 18 '14 at 11:07
  • @peeskillet: Ahha, nice, that you adhering to the concept of `Abstraction` while answering(Good use of Object Oriented Programming concepts, while answering) – nIcE cOw Jul 18 '14 at 13:55
  • Thank you @peeskillet when i am placing fill rect code in paintComponent method its not working previously and one more thing is after dragging i am filling color but i dont want to display the dragged rectangle after filling color can you suggest me to do how i can i do that? – Vskiran Jul 21 '14 at 06:11
  • For the last part, I would put a `isSelected` variable in the `ColoredRectangle` class and if it is contained, set it to `true`. In the paint method, only paint if the rectangle `isSelected`. As for getting rid of the rectangle, you can set it to null when the mouse is release. – Paul Samsotha Jul 21 '14 at 06:15
  • As for the first part, I can't tell. You'd have to do your own debugging. I used a different approach using `Rectangle` and `Graphics2D.fill(Rectangle)`. `.fillRect()` is a method of the `Graphics` class. You can cast it to `Grapchics2D` like I did in my code – Paul Samsotha Jul 21 '14 at 06:17
  • Everything becomes a lot easier to maintain is you create wrapper class for all the properties, as I have. You can just have the method to draw also, in that class – Paul Samsotha Jul 21 '14 at 06:35
  • Yes i got it but what i need is i dont want to display dragged rectangle after dragging it has to disable how can i do that . – Vskiran Jul 22 '14 at 10:45
  • I just told you. Set the rectangle to null when the mouse is released. You can see in my program when it first starts, the drag rectangle is null. That's why you don't see it when you start the program. Do the same thing in a `mouseReleased`, set it to null – Paul Samsotha Jul 22 '14 at 10:49
  • I am using like this to set rectangle but it is not working new Rectangle(x, y, width, height).setRect(null); in mouse released – Vskiran Jul 22 '14 at 11:16
  • In my code, I use the same class rectangle. I only initialize it in the mousePressed. in the mouse releasd just do `rectangle = null, repaint()`. Try it with my code. I haven't tested it, but from what I remember about the code, that simple line in the `public void mouseReleased` should do the trick. If it works with my code, then compare it to yours, and see what's different – Paul Samsotha Jul 22 '14 at 11:21
  • like this i am doing but it is not working where as in your code it is working Rectangle ggg=new Rectangle(x, y, width, height); for(Rectangle rect3d: rect){ if(ggg.intersects(rect3d)){ g2.fill(rect3d);} else System.out.println("doesn't contains"); } ggg=null; repaint(); – Vskiran Jul 22 '14 at 11:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/57753/discussion-between-user3173720-and-peeskillet). – Vskiran Jul 22 '14 at 12:02
-1

I came across your question while searching for something similar I needed. I customized the Paul's code a little bit more for my requirements. I'm writing here because I'm not allowed make comment here my version

import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;

public class TimetableFrame extends javax.swing.JFrame {

Point p1, p2;
Rectangle2D rectangle;
int mode = 0;
HashSet<JLabel> all = new HashSet<JLabel>();
HashSet<JLabel> selected = new HashSet<JLabel>();
HashSet<JLabel> current_selection = new HashSet<JLabel>();
Color empty_color = Color.WHITE;
Color fill_color = Color.RED;
Color empty_select = Color.GRAY;
Color fill_select = Color.PINK;

JPanel grid;
JPanel jPanel1;
JScrollPane jScrollPane1;

public TimetableFrame() {
    initComponents();
    setTitle("Swing grid selector example halimoglu.com");
    String[] col_titles = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

    String[] row_titles = new String[24];
    for (int i = 0; i < row_titles.length; i++) {
        row_titles[i] = (i) + "-" + (i + 1);
    }

    for (int y = 0; y < row_titles.length + 1; y++) {
        for (int x = 0; x < col_titles.length + 1; x++) {
            if (y == 0 && x == 0) {
                grid.add(new JLabel(""));
            } else if (y == 0) {
                JLabel col = new JLabel(col_titles[x - 1]);
                col.setHorizontalAlignment(SwingConstants.CENTER);
                grid.add(col);
            } else if (x == 0) {
                grid.add(new JLabel(row_titles[y - 1]));
            } else {
                JLabel mylabel = new JLabel(" ");

                mylabel.setOpaque(true);
                mylabel.setBackground(empty_color);
                all.add(mylabel);
                grid.add(mylabel);
            }
        }
    }

    grid.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent me) {
            for (JLabel j : all) {
                if (j.getBounds().contains(me.getPoint())) {

                    if (selected.contains(j)) {
                        selected.remove(j);
                        j.setBackground(empty_color);
                    } else {
                        selected.add(j);
                        j.setBackground(fill_color);
                    }
                }
            }
        }

        @Override
        public void mousePressed(MouseEvent me) {
            p1 = me.getPoint();
            rectangle = new Rectangle2D.Double(p1.x, p1.y, p1.x - p1.x, p1.y - p1.y);
        }

        @Override
        public void mouseReleased(MouseEvent me) {

            if (mode == 1) {
                selected.addAll(current_selection);

            } else if (mode == -1) {
                selected.removeAll(current_selection);

            }
            for (JLabel j : all) {
                if (selected.contains(j)) {
                    j.setBackground(fill_color);
                } else {
                    j.setBackground(empty_color);
                }
            }
            current_selection.clear();
            mode = 0;
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }

    });

    grid.addMouseMotionListener(new MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent me) {
            p2 = me.getPoint();

            Point lu;

            int minx = Math.min(p1.x, p2.x);
            int miny = Math.min(p1.y, p2.y);
            int maxx = Math.max(p1.x, p2.x);
            int maxy = Math.max(p1.y, p2.y);

            lu = new Point(minx, miny);// left upper point

            rectangle.setRect(lu.x, lu.y, maxx - minx, maxy - miny);

            //set mode 
            //1 = if first selected cell is empty set mode to fill
            //-1 = otherwise clear 
            if (mode == 0) {
                for (JLabel j : all) {
                    if (j.getBounds().intersects(rectangle)) {
                        if (selected.contains(j)) {
                            mode = -1;
                        } else {
                            mode = 1;
                        }
                        break;
                    }
                }
            }

            for (JLabel j : all) {

                if (selected.contains(j) == (mode != 1)) {
                    if (j.getBounds().intersects(rectangle)) {
                        current_selection.add(j);
                    } else {
                        if (current_selection.contains(j)) {
                            current_selection.remove(j);
                            if (mode == 1) {
                                if (selected.contains(j) == false) {
                                    j.setBackground(empty_color);
                                }
                            } else {
                                if (selected.contains(j) == true) {
                                    j.setBackground(fill_color);
                                }
                            }
                        }
                    }
                }
            }

            for (JLabel j : current_selection) {
                if (mode == 1) {
                    j.setBackground(fill_select);
                } else if (mode == -1) {
                    j.setBackground(empty_select);
                }
            }

        }

        @Override
        public void mouseMoved(MouseEvent me) {
        }
    });
}

private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jPanel1 = new javax.swing.JPanel();
    grid = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setLayout(new java.awt.BorderLayout());

    grid.setLayout(new java.awt.GridLayout(25, 0, 2, 2));
    jPanel1.add(grid, java.awt.BorderLayout.CENTER);

    jScrollPane1.setViewportView(jPanel1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 399, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
    );

    pack();
}

public static void main(String args[]) {

    new TimetableFrame().setVisible(true);

}

}