单击鼠标时如何使图像顶部出现?

时间:2011-11-20 10:36:26

标签: java swing drawrect paintcomponent mouselistener

我的目标是在点击鼠标时出现矩形。 这是我当前代码的片段:

    try{
            image = ImageIO.read(file);
            g.setColor(new Color(255,0,0));
            g.drawRect(x, y, 100, 100);
            }

    icon = new ImageIcon(image);
    label = new JLabel(icon);
    label.addMouseListener(this);

     public void mouseReleased(MouseEvent event) {
            // TODO Auto-generated method stub

            if(event.getSource() == label){

                x = event.getX();
                y = event.getY();

                repaint();

                input = JOptionPane.showInputDialog("Something:");
                System.out.println(input);
            }
        }

1 个答案:

答案 0 :(得分:3)

您可以扩展JPanel以完全按照您的意愿执行:

class MyPanel extends JPanel{
    //....
    private java.awt.Rectangle rectangle = null;
    private Image imageToDraw;
    private Point imageLocation;
    public setImageToDraw(Image toDraw,Point p){
      imageToDraw=toDraw;
      imageLocation = p;
    }
    public void setRectangle(java.awt.Rectangle rectangle overlayRect){
       rectangle = overlayRect;
    }
    // Override paintComponent to draw image and rectangle
    @Override
    public void paintComponent(Graphics g) {
      g.drawImage(imageToDraw,imageLocation.getX(),imageLocation.getY(),this);
      if(rectangle != null) {
         // Draw your rectangle here...
      }
    }
}

在鼠标监听器中,执行以下操作:

// Declare a field of type MyPanel
private MyPanel drawingPanel = new MyPanel
// ... Initialization stuff...
drawingPanel.setImageToDraw(toDraw,p);
public void mouseReleased(MouseEvent event) {
        // TODO Auto-generated method stub
        if(event.getSource() == label){
           // Compute rectangle boundaries
           drawingPanel.setRectangle(overlayRect);
        }
        drawingPanel.repaint();
}

基本上,MyPanel对象将始终具有要绘制的图像集。这样,图像一直在面板上绘制。如果需要叠加矩形,您需要做的就是设置MyPanel.rectangle字段并刷新MyPanel实例。这将首先重绘图像,然后在图像顶部绘制叠加矩形。