0

我编写了这段代码,每次单击鼠标时都会在白色背景上绘制圆形,唯一的问题是我将图片添加到背景中,我还想在鼠标单击时添加圆形,但它没有这样做。这是下面的代码你能帮我吗

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;

public class Frame {

    JFrame frame;
    MyPanel p;
    Timer t;
    Icon icon;

    //contructor
    public Frame() {
        frame = new JFrame("Painting");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
        frame.add(p);
        frame.pack();
        frame.setVisible(true);
        t.start();

    }

    private void initComponents() {

        final ActionListener action = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {

                p.repaint();
            }
        };
        t = new Timer(50, action);
        p = new MyPanel();

        p.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                p.addEntity(e.getX(), e.getY(), 10, 10, Color.BLACK);
                System.out.println("clicked");
            }
        });

        icon = new ImageIcon("flower.gif");
        JLabel label = new JLabel(icon);
        JScrollPane scrollPane = new JScrollPane(label);
        p.add(scrollPane, BorderLayout.WEST);

        p.setBackground(Color.WHITE);
    }
}

class MyPanel extends JPanel {

    int width = 300, height = 300;
    ArrayList<MyCircle> entities = new ArrayList<MyCircle>();

    void addEntity(int x, int y, int w, int h, Color c) {
        entities.add(new MyCircle(x, y, w, h, c));
    }

    @Override
    protected void paintComponent(Graphics grphcs) {
        super.paintComponent(grphcs);
        Graphics2D g2d = (Graphics2D) grphcs;

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        for (MyCircle entity : entities) {
            g2d.setColor(entity.getColor());
            g2d.fillOval((int) entity.x, (int) entity.y, (int) entity.width, (int) entity.height);
        }
    }

    //frame dimesion
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(width, height);
    }
}

//create the circle
class MyCircle extends Rectangle2D.Double {

    Color color;

    public MyCircle(double x, double y, double w, double h, Color c) {
        super(x, y, w, h);
        color = c;

    }

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

    public Color getColor() {
        return color;
    }
}
4

1 回答 1

0

问题中MouseListener使用的 未注册JLabel. 而不是尝试为 JLabel 创建重复的自定义绘制逻辑,您可以简单地阅读Image启动时的内容并将其包含在现有的自定义绘制逻辑中:

例如

public MyPanel(Image image) {
   this.image = image;
}

@Override
protected void paintComponent(Graphics grphcs) {
   super.paintComponent(grphcs);
   grphcs.drawImage(image, 0, 0, this);
   ...
}
于 2013-07-12T16:58:00.433 回答