【问题标题】:How add eventListener in an Array Object?如何在数组对象中添加 eventListener?
【发布时间】:2015-10-01 23:25:33
【问题描述】:

我正在做一个程序,当我将鼠标拖过 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);
        }
    });
}

如果您在此处发现错误,请告诉我,
感谢您的帮助!

【问题讨论】:

  • 要获得更好的帮助,请考虑创建并发布Minimal, Complete, and Verifiable Example Program。我们不想看到你的整个程序,而是你应该将你的代码压缩成仍然可以编译的最小部分,没有与你的问题无关的额外代码,但仍然可以证明你的问题。您可以通过简单地尝试隔离和暴露错误来自己解决问题。
  • newPanel[numberOfPanel].setSize(0,0);!!??抱歉,但是零大小的 JPanel 有什么用处呢?如何在太小而无法显示的东西上按下鼠标?另外,我希望您知道setSize(...) 通常会被大多数布局管理器忽略。
  • 它的大小为 0,因为它是程序其余部分的一部分,大小将由 mouseDragged 事件添加
  • 大小为零时不能拖动。连老鼠都找不到。但无论如何,您将希望通过展示一个我们可以运行的小型可编译示例程序来改进这个问题,并为我们展示您的问题。
  • 新代码的目的是什么?它如何无法正常工作?请注意,您的“数学错误”是因为您根据 JFrame 中的位置而不是实际容器中的位置设置大小 - JFrame 的 contentPane。但我可以保证,无论你想做什么,都有更好的方法,但在我知道你的目的之前,我不能说它是什么。

标签: java arrays swing graphics jpanel


【解决方案1】:

您仍然没有提到您的代码的目的,但无论如何,您最好不要创建 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();
            }
        });
    }
}

【讨论】:

    【解决方案2】:

    这是一个在 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]);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-24
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 2020-03-28
      • 2019-04-28
      • 2021-09-25
      相关资源
      最近更新 更多