-2

i'm doing a program that draw(creates) panels with arrays when i drag mouse through of the JFrame, but when i try add a mousePressedEvent to the array object it doesn't work.

package Swing;
import java.awt.Point; 
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JOptionPane;

public class testRec extends javax.swing.JFrame {
    Point clickPoint;
    JPanel[] panelDraw = new JPanel[10];
    int numberOfRectangle = 0;

public testRec() {
    initComponents();
}

private void initComponents() {

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {
            formMouseDragged(evt);
        }
    });
    addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            formMousePressed(evt);
        }
    });

    javax.swing.GroupLayout layout = new                                 javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void formMousePressed(java.awt.event.MouseEvent evt) {                                  
    clickPoint = evt.getPoint();

    panelDraw[numberOfRectangle] = new JPanel();
    panelDraw[numberOfRectangle].setBorder(new LineBorder(Color.ORANGE,2));
    panelDraw[numberOfRectangle].setSize(0,0);
    panelDraw[numberOfRectangle].setOpaque(false);
    add(panelDraw[numberOfRectangle]);

}                                 

private void formMouseDragged(java.awt.event.MouseEvent evt) {                                  
    Point dragPoint = evt.getPoint();
                int x = Math.min(clickPoint.x, dragPoint.x);
                int y = Math.min(clickPoint.y, dragPoint.y);
                int width = Math.max(clickPoint.x - dragPoint.x, dragPoint.x    - clickPoint.x);
                int height = Math.max(clickPoint.y - dragPoint.y,    dragPoint.y - clickPoint.y);
                //Here is a Mouse Point error and i've solved by subtracting           pixels 
                panelDraw[numberOfRectangle].setBounds(x, y-25, width, height);
}                                 

public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new testRec().setVisible(true);
        }
    });
}

If you found error there, please let me know,
Thanks for helping!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Refer
  • 1
  • 4
  • 1
    For better help, consider creating and posting a [Minimal, Complete, and Verifiable Example Program](http://stackoverflow.com/help/mcve). We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. You might very well solve the problem yourself by simply trying to isolate and expose the bug. – Hovercraft Full Of Eels Oct 01 '15 at 23:27
  • `newPanel[numberOfPanel].setSize(0,0);`!!?? Sorry, but how will a zero sized JPanel be of any use whatsoever? How does one do a mouse press on something that is too small to be displayed? Also, I hope you know that `setSize(...)` is usually ignored by most layout managers. – Hovercraft Full Of Eels Oct 01 '15 at 23:30
  • it's 0 size because is a piece of the rest of programm, the size will be added by a mouseDragged event – Refer Oct 01 '15 at 23:39
  • It can't be dragged if it's zero size. A mouse can't even find it. But regardless, you're going to want to improve this question by showing a small compilable example program that we can run, and that demonstrates your problem for us. – Hovercraft Full Of Eels Oct 01 '15 at 23:40
  • Done! :P if you found errors in there, let me know – Refer Oct 02 '15 at 00:05
  • Put this println `System.out.println("numberOfRectangle: " + numberOfRectangle);` in your formMousePressed method. You never increment your numberOfRectangle variable -- it always stays 0. – Hovercraft Full Of Eels Oct 02 '15 at 00:09
  • 1
    What is the purpose of the new code? How is it not working correctly? Note that your "math bug" is because you're setting sizes based on position in the JFrame and not in the actual container -- the JFrame's contentPane. But I can guarantee that whatever it is you're trying to do, there's a better way, but what it is I can't say until I know what your purpose is. – Hovercraft Full Of Eels Oct 02 '15 at 00:15

2 Answers2

2

You've still not mentioned your code's purpose, but regardless, you're likely better off not creating JPanels but rather than using Swing components, using logical graphic structures, such as Rectangles, adding them to an ArrayList, not a fixed size array. If you do something like this, you can do all your drawing on a single JPanel. For instance, run this code:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
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.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class TestRec2 extends JPanel {
    private static final int PREF_W = 800;
    private static final int PREF_H = PREF_W;
    private static final Stroke STROKE = new BasicStroke(6f);
    private static final Color RECT_BORDER = Color.ORANGE;
    private static final Color DRAW_COLOR = RECT_BORDER.brighter().brighter();
    private static final Color RECT_FILL = Color.LIGHT_GRAY;
    private static final Color SELECTED_RECT_FILL = Color.pink;
    private static final Color SELECTED_RECT_BORDER = Color.red;
    private List<Rectangle> rectangleList = new ArrayList<>();
    private Rectangle rect = null;
    private Rectangle selectedRectangle = null;

    public TestRec2() {
        MyMouse myMouse = new MyMouse();
        addMouseListener(myMouse);
        addMouseMotionListener(myMouse);
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setStroke(STROKE);
        for (Rectangle2D rect2d : rectangleList) {
            Color fillColor = RECT_FILL;
            Color borderColor = RECT_BORDER;
            if (rect2d == selectedRectangle) {
                fillColor = SELECTED_RECT_FILL;
                borderColor = SELECTED_RECT_BORDER;
            }
            g2.setColor(fillColor);
            g2.fill(rect2d);
            g2.setColor(borderColor);
            g2.draw(rect2d);

        }
        g2.dispose(); // since we created this Graphics object
        if (rect != null) {
            g.setColor(DRAW_COLOR);
            ((Graphics2D)g).draw(rect);
        }
    }

    private class MyMouse extends MouseAdapter {
        Point p = null;

        @Override
        public void mousePressed(MouseEvent e) {
            Point innerP = e.getPoint();
            for (int i = rectangleList.size() - 1; i >= 0; i--) {
                if (rectangleList.get(i).contains(innerP)) {
                    selectedRectangle = rectangleList.get(i);
                    System.out.println("Rectangle " + i + " pressed");
                    repaint();
                    return;
                }
            }
            p = innerP;
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            if (p != null) {
                rectangleList.add(createRect(p, e.getPoint()));
                rect = null;
                p = null;
                repaint();
            }
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (p != null) {
                rect = createRect(p, e.getPoint());
                repaint();
            }
        }

        private Rectangle createRect(Point p1, Point p2) {
            int x = Math.min(p1.x, p2.x);
            int y = Math.min(p1.y, p2.y);
            int w = Math.abs(p1.x - p2.x);
            int h = Math.abs(p1.y - p2.y);
            return new Rectangle(x, y, w, h);
        }
    }

    private static void createAndShowGui() {
        TestRec2 mainPanel = new TestRec2();

        JFrame frame = new JFrame("TestRec2");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Here is an example that use this code in the Frame constructor and add 1 panel. compiled and runs, using some colors and console output for testing :

public class Frame extends JFrame {
    public static void main(String[] args) {
        Frame f = new Frame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(null);
        f.setVisible(true);
        f.setSize(200, 200);
    }

    public Frame() {
        JPanel[] newPanel = new JPanel[1];
        newPanel[0] = new JPanel();
        newPanel[0].setBorder(new LineBorder(Color.ORANGE, 2));
        newPanel[0].setSize(100, 100);
        newPanel[0].setBackground(Color.black);
        newPanel[0].addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                Point clickPoint = e.getPoint();
                System.out.println(clickPoint);
            }
        });
        add(newPanel[0]);
    }
}
chenchuk
  • 5,324
  • 4
  • 34
  • 41