如何在Array对象中添加eventListener?

时间:2015-10-01 23:25:33

标签: java arrays swing graphics jpanel

当我将鼠标拖过JFrame时,我正在做一个用数组绘制(创建)面板的程序,但是当我尝试将mousePressedEvent添加到数组对象时,它不起作用。

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);
        }
    });
}

如果您在那里发现错误,请告诉我,
谢谢你的帮助!

2 个答案:

答案 0 :(得分:2)

您仍然没有提及您的代码的目的,但无论如何,您最好不要创建JPanel而不是使用Swing组件,使用逻辑图形结构,如矩形,添加它们是一个ArrayList,而不是一个固定大小的数组。如果您执行此类操作,则可以在单个JPanel上完成所有绘图。例如,运行以下代码:

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();
            }
        });
    }
}

答案 1 :(得分:0)

下面是一个在Frame构造函数中使用此代码并添加1个面板的示例。编译并运行,使用一些颜色和控制台输出进行测试:

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]);
    }
}