2

マウスをクリックしたときの長方形の外観を目指しています。これが私の現在のコードの抜粋です:

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

1 に答える 1

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これにより、最初に画像が再描画され、次に画像の上にオーバーレイ四角形が描画されます。

于 2011-11-20T11:00:29.733 に答える