Java 在Swing中的面板上绘制多个矩形

Java 在Swing中的面板上绘制多个矩形,java,swing,Java,Swing,我试图在一个面板上画多个矩形。我创建了一个ArrayList,并在构造函数中初始化。在我的paintComponent方法中,我绘制了一个矩形,然后将其添加到ArrayList。但当我这样做的时候,我的面板上的绘图结果就变得很奇怪了。当我拖动以绘制第一个矩形时,我得到以下结果: 以下是我的部分代码: public class MyMouseListener extends MouseAdapter { @Override public void mousePressed(fin

我试图在一个面板上画多个矩形。我创建了一个
ArrayList
,并在构造函数中初始化。在我的
paintComponent
方法中,我绘制了一个矩形,然后将其添加到
ArrayList
。但当我这样做的时候,我的面板上的绘图结果就变得很奇怪了。当我拖动以绘制第一个矩形时,我得到以下结果:

以下是我的部分代码:

public class MyMouseListener extends MouseAdapter {
    @Override
    public void mousePressed(final MouseEvent theEvent) {
        myStartPoint = theEvent.getPoint();
        repaint();

    }

    @Override
    public void mouseReleased(final MouseEvent theEvent) {
        myEndPoint = theEvent.getPoint();
        repaint();            
    }
}

public class MyMouseMotionHandler extends MouseMotionAdapter {
    @Override
    public void mouseDragged(final MouseEvent theEvent) {           
        myEndPoint = theEvent.getPoint();
        repaint(); 
    }       
}



/**
* Paints some rectangles.
* 
* @param theGraphics The graphics context to use for painting.
*/
@Override
public void paintComponent(final Graphics theGraphics) {
    super.paintComponent(theGraphics);
    final Graphics2D g2d = (Graphics2D) theGraphics;

    // for better graphics display
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                         RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setPaint(new Color(51, 0, 111));
    g2d.setStroke(new BasicStroke(3));

    final double x = myStartPoint.getX();
    final double y = myStartPoint.getY();
    final double xEnd = myEndPoint.getX();
    final double yEnd = myEndPoint.getY();

    if (xEnd> x && yEnd > y) { 
        final Shape rectangle = new Rectangle2D.
                Double(x, y, xEnd - x, yEnd - y);
        g2d.draw(rectangle);
        myDrawings.add(rectangle);
    }


    for (Shape s : myDrawings) {
        g2d.draw(s);
    }
}

不要在paintComponent中执行任何代码逻辑——该方法仅用于绘图和绘图,而这正是错误的根源。释放鼠标时,将矩形添加到鼠标侦听器中的ArrayList

当我完成一个类似的项目时,我通常有一个矩形字段,我用鼠标拖动鼠标监听器来绘制,它是在paintComponent中绘制的。然后在鼠标释放时,我将该矩形放入ArrayList,并将类字段设置为null

e、 g

导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Point;
导入java.awt.Rectangle;
导入java.awt.Shape;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.util.ArrayList;
导入java.util.List;
导入javax.swing.*;
@抑制警告(“串行”)
公共类矩形绘制扩展JPanel{
专用静态最终整型预调W=800;
专用静态最终int PREF_H=650;
专用静态最终颜色TEMP_RECT_Color=Color.LIGHT_GRAY;
私有静态最终颜色形状\u Color=Color.RED;
私有矩形tempRect=null;
私有列表形状=新的ArrayList();
公共矩形绘图(){
MyMouse MyMouse=新建MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
@凌驾
受保护组件(图形g){
超级组件(g);
图形2d g2=(图形2d)g;
//如果不为空,则绘制临时矩形
if(tempRect!=null){
g2.设置颜色(温度校正颜色);
g2.绘制(tempRect);
}
//绘制列表中的所有矩形
g2.设置颜色(形状和颜色);
用于(形状:形状){
g2.绘制(形状);
}
}
//根据我的规范调整GUI的大小
@凌驾
公共维度getPreferredSize(){
如果(isPreferredSizeSet()){
返回super.getPreferredSize();
}
返回新维度(PREF_W,PREF_H);
}
//我的鼠标监听器和鼠标运动监听器
私有类MyMouse扩展了MouseAdapter{
专用点p1;//起点
@凌驾
公共无效鼠标按下(MouseEvent e){
p1=e.getPoint();
}
@凌驾
公共无效鼠标标记(鼠标事件e){
//创建临时矩形
tempRect=createRectangle(e);
重新油漆();
}
@凌驾
公共无效MouseEvent(MouseEvent e){
tempRect=null;//null临时矩形和
//将矩形添加到列表中
添加(createRectangle(e));
重新油漆();
}
//从起点和当前点创建矩形
私有矩形createRectangle(MouseEvent e){
点p2=e.getPoint();
intx=数学最小值(p1.x,p2.x);
int y=数学最小值(p1.y,p2.y);
int w=数学绝对值(p1.x-p2.x);
inth=Math.abs(p1.y-p2.y);
矩形rect=新矩形(x,y,w,h);
返回矩形;
}
}
私有静态void createAndShowGui(){
JFrame=新的JFrame(“矩形绘制”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(新矩形绘制());
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
}
公共静态void main(字符串[]args){
调用器(()->createAndShowGui());
}
}

不要在paintComponent中执行任何代码逻辑——该方法仅用于绘图和绘图,而这正是错误的根源。释放鼠标时,将矩形添加到鼠标侦听器中的ArrayList

当我完成一个类似的项目时,我通常有一个矩形字段,我用鼠标拖动鼠标监听器来绘制,它是在paintComponent中绘制的。然后在鼠标释放时,我将该矩形放入ArrayList,并将类字段设置为null

e、 g

导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Point;
导入java.awt.Rectangle;
导入java.awt.Shape;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.util.ArrayList;
导入java.util.List;
导入javax.swing.*;
@抑制警告(“串行”)
公共类矩形绘制扩展JPanel{
专用静态最终整型预调W=800;
专用静态最终int PREF_H=650;
专用静态最终颜色TEMP_RECT_Color=Color.LIGHT_GRAY;
私有静态最终颜色形状\u Color=Color.RED;
私有矩形tempRect=null;
私有列表形状=新的ArrayList();
公共矩形绘图(){
MyMouse MyMouse=新建MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
@凌驾
受保护组件(图形g){
超级组件(g);
图形2d g2=(图形2d)g;
//如果不为空,则绘制临时矩形
if(tempRect!=null){
g2.设置颜色(温度校正颜色);
g2.绘制(tempRect);
}
//绘制列表中的所有矩形
g2.设置颜色(形状和颜色);
用于(形状:形状){
g2.绘制(形状);
}
}
//根据我的规范调整GUI的大小
@凌驾
公共维度getPreferredSize(){
如果(isPreferredSizeSet()){
返回super.getPrefe
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.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

@SuppressWarnings("serial")
public class RectangleDraw extends JPanel {
    private static final int PREF_W = 800;
    private static final int PREF_H = 650;
    private static final Color TEMP_RECT_COLOR = Color.LIGHT_GRAY;
    private static final Color SHAPE_COLOR = Color.RED;
    private Rectangle tempRect = null;
    private List<Shape> shapes = new ArrayList<>();

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

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        // draw the temporary rectangle if not null
        if (tempRect != null) {
            g2.setColor(TEMP_RECT_COLOR);
            g2.draw(tempRect);
        }

        // draw all the rectangles in the list
        g2.setColor(SHAPE_COLOR);
        for (Shape shape : shapes) {
            g2.draw(shape);
        }

    }

    // size the GUI to my specification
    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    // My mouse listener and mouse motion listener
    private class MyMouse extends MouseAdapter {
        private Point p1; // start point

        @Override
        public void mousePressed(MouseEvent e) {
            p1 = e.getPoint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            // create temporary rectangle
            tempRect = createRectangle(e);
            repaint();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            tempRect = null; // null temp rectangle and
            // add rectangle to List
            shapes.add(createRectangle(e));
            repaint();
        }

        // create a rectangle from start point and current point
        private Rectangle createRectangle(MouseEvent e) {
            Point p2 = e.getPoint();
            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);
            Rectangle rect = new Rectangle(x, y, w, h);
            return rect;
        }

    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Rectangle Draw");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new RectangleDraw());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}