Criar retangulo 2 cliques

8 respostas
O

Pessoal, preciso desenhar um retangulo na tela com 2 cliques do mouse.
Por enquanto, estou criando o retangulo com um clique só.

public class PanelQuad extends JPanel implements MouseListener {

	private Vector vetPonto;
	private int x = 0;
	private int y = 0;

	public PanelQuad() {
		setBackground(Color.white);
		addMouseListener(this);
		vetPonto = new Vector();
	}

	public void mouseClicked(MouseEvent e) {
		vetPonto.add(e.getPoint());
		x = e.getX();
		y = e.getY();
		
		repaint();
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	public void paint(Graphics g) {
		super.paint(g);
		if (vetPonto.size() > 0) {
			g.drawRect(x, y, 80, 30);
					}
	}

Alguém sabe como faço pra criar o retangulo com 2 cliques?

8 Respostas

Marky.Vasconcelos
public class PanelQuad extends JPanel implements MouseListener {
        private boolean firstClick = true;
	private int x1 = 0, y1 = 0;
	private int x2 = 0, y2 = 0;

	public PanelQuad() {
		setBackground(Color.white);
		addMouseListener(this);
	}

	public void mouseClicked(MouseEvent e) {
                if(firstClick){
		x1 = e.getX();
		y1 = e.getY();
                }else{
                x2 = e.getX();
		y2 = e.getY();
		}
                firstClick = !firstClick;
		repaint();
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g.create();
		g2d.drawRect(x1, y1, x2-x1, y2-y1);
		g2d.dispose();
	}
}
O

Legal Mark.
Funcionou aqui.
Meu codigo ficou assim:

public class PanelQuad extends JPanel implements MouseListener {
	
	private Point p1 = null;   
	private Point p2 = null; 

	public PanelQuad() {
		setBackground(Color.white);
		addMouseListener(this);
	}

	public void mouseClicked(MouseEvent e) {
		
		if (p1 == null) {   
	        p1 = e.getPoint();   
	        return;
		}
		
		if (p1 != null && p2 == null) {   
	        p2 = e.getPoint();   
		}
		
		
		repaint();
	}

	public void mouseEntered(MouseEvent e) {
	}

	public void mouseExited(MouseEvent e) {
	}

	public void mousePressed(MouseEvent e) {
	}

	public void mouseReleased(MouseEvent e) {
	}

	public void paint(Graphics g) {
		super.paint(g);
		
		if(p2 != null)
		{
			g.drawRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
		}
	}
	
}

Obrigado Mark =))
Quebrou mó galhão.

Abraço

Marky.Vasconcelos

Repare que sobreescrevi paintComponent e não paint como voce fez.
Fora o fato de criar uma cópia de Graphics2D para pintar sobre ela.

Faça desse modo caso não queira efeitos estranhos na tela quando voce deixar de pintar apenas retangulos para algo mais complexo.

O

É…vc tem razão Mark.
Está dando uns efeitos estranhos no meu programa.
A imagem que eu tinha na tela some quando aparece o quadrado.

Eu coloquei o seu método, mas o quadrado não está aparecendo quando clico duas vezes.
Segue abaixo meu metodo Paint:

public void paintComponent(Graphics g) {

            img = new ImageIcon("img/ibope.jpg").getImage();

            Graphics2D g2 = (Graphics2D) g;
            g2.drawImage(img, 50, 0, null);
            setGraphicsHints(g2);
            
            //quadrado
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawRect(x1, y1, x2 - x1, y2 - y1);
            g2d.dispose();

            //background
            g.setColor(this.getBackground());
            g.fillRect(0, 0, this.getWidth(), this.getHeight());

            //fundo
            paintPage(g2, img, 0, 0, img.getWidth(this) * 5/4, img.getHeight(this), this, true);

            // page 1
            paintPage(g2, currentLeftImage, bookBounds.x, bookBounds.y, pageWidth, bookBounds.height, this, false);

            // page 2
            paintPage(g2, currentRightImage, bookBounds.x + pageWidth, bookBounds.y, pageWidth, bookBounds.height, this, true);
            
		if (leftPageTurn) {
			if (softClipping) {
				paintLeftPageSoftClipped(g2);
			} else {
				paintLeftPage(g2);
			}
		} else {
			if (softClipping) {
				paintRightPageSoftClipped(g2);
			} else {
				paintRightPage(g2);
			}
		}
	}

Vc sabe o que eu estou fazendo de errado?

Marky.Vasconcelos

falta o super.paintComponent(g) na primeira linha.

E Graphics2D g2d = (Graphics2D) g; deveria ser
Graphics2D g2d = (Graphics2D) g.create();

E na ultima linha do método falta g2d.dispose();

M

meio nas pressas eu fiz assim, se for util, boa sorte!

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

/**
 *
 * @author  Miguelito
 */
public class NewJPanel extends javax.swing.JPanel
{

    private int count = 0;
    private int xPoint = 0;
    private int yPoint = 0;
    private int xPointTwo = 0;
    private int yPointTwo = 0;
    
    /** Creates new form NewJPanel */
    public NewJPanel()
    {
        initComponents();
    }

    @Override
    public void paint( Graphics g )
    {
        Graphics2D g2d = (Graphics2D) g.create();
        
        g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
        
        g2d.setColor( Color.WHITE );
        
        g2d.fillRect( 0, 0, getWidth(), getHeight() );
        
        g2d.setColor( Color.BLACK );
            
        if ( count == 1 )
        {
            int x = getMousePosition().x;
            int y = getMousePosition().y;
        
            int xMax = Math.max( x, xPoint );
            int xMin = Math.min( x, xPoint );
            int yMax = Math.max( y, yPoint );
            int yMin = Math.min( y, yPoint );
            
            g2d.fillRoundRect( xMin, yMin, xMax - xMin, yMax - yMin, 10, 10 );
        }
        
        else if ( count == 2 )
        {
            int xMax = Math.max( xPointTwo, xPoint );
            int xMin = Math.min( xPointTwo, xPoint );
            int yMax = Math.max( yPointTwo, yPoint );
            int yMin = Math.min( yPointTwo, yPoint );
            
            g2d.fillRoundRect( xMin, yMin, xMax - xMin, yMax - yMin, 10, 10 );
        }
    }

    private void initComponents()
    {
        addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt) 
            {
                formMouseClicked(evt);
            }
        });

        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() 
        {
            public void mouseMoved(java.awt.event.MouseEvent evt) 
            {
                formMouseMoved(evt);
            }
        });
    }

    private void formMouseClicked(java.awt.event.MouseEvent evt) 
    {
        count++;
    
        if ( count < 3 )
        {
            if ( count == 1 )
            {
                xPoint = getMousePosition().x;
                yPoint = getMousePosition().y;
            }
        
            else if ( count == 2 )
            {
                xPointTwo = getMousePosition().x;
                yPointTwo = getMousePosition().y;
            }
        }
    
        else
        {
            count = 0;
        }
    }

    private void formMouseMoved(java.awt.event.MouseEvent evt) 
    {
        repaint();
    }



    public static void main ( String[] args )
    {
        JFrame f = new JFrame();
        
        f.setLayout( new BorderLayout() );
        f.add( new NewJPanel() );
        f.setSize( 800, 600 );
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        f.setVisible( true );
    }
}
O

Poxa, ainda não está funcionando.
Fiz do jeito que vc falou Mark, mas eu clico a segunda vez e o quadrado não aparece.
Segue abaixo meu codigo:

public void paintComponent(Graphics g) {

            super.paintComponent(g);
            //Crio o Graphics g2d para desenhar o quadrado
            Graphics2D g2d = (Graphics2D) g.create();

            img = new ImageIcon("img/ibope.jpg").getImage();

            Graphics2D g2 = (Graphics2D) g.create();
            g2.drawImage(img, 50, 0, null);
            setGraphicsHints(g2);

            //se o usuario clicou pela segunda vez, faz o quadrado
            if (x2 > 0) {

			if (x1 < x2) {
				g2d.drawRect(x1, y1, x2 - x1, y2 - y1);
			}

			if (x1 > x2) {
				g2d.drawRect(x2, y2, x1 - x2, y1 - y2);
			}
		}

            //background
            g.setColor(this.getBackground());
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            //fundo
            paintPage(g2, img, 0, 0, img.getWidth(this) * 5/4, img.getHeight(this), this, true);
            // page 1
            paintPage(g2, currentLeftImage, bookBounds.x, bookBounds.y, pageWidth, bookBounds.height, this, false);
            // page 2
            paintPage(g2, currentRightImage, bookBounds.x + pageWidth, bookBounds.y, pageWidth, bookBounds.height, this, true);
            
		if (leftPageTurn) {
			if (softClipping) {
				paintLeftPageSoftClipped(g2);
			} else {
				paintLeftPage(g2);
			}
		} else {
			if (softClipping) {
				paintRightPageSoftClipped(g2);
			} else {
				paintRightPage(g2);
			}
		}

            g2d.dispose();
            g2.dispose();
	}

public void mouseClicked(MouseEvent e) {

     if (firstClick) {
		x1 = e.getX();
		y1 = e.getY();
      } else {
                x2 = e.getX();
                y2 = e.getY();
      }
		firstClick = !firstClick;
		m_FLIPPAINEL.repaint();
}

Por que será que não está aparecendo o quadrado?

Marky.Vasconcelos

Voce tem certeza que o Jpanel tem o tamanho correto para desenhar na tela?
Talvez ele esteja dentro de outro Container com nada dentro então fica com 0w e 0h.

No seu JFrame se tiver apenas esse JPanel não adicione (add) e sim faça

frame.setContentPane(flipPane);

E pra ter certeza de onde ele está coloque uma borda.

fliPane.setBorder(new TitledBorder(""));
Criado 15 de outubro de 2009
Ultima resposta 16 de out. de 2009
Respostas 8
Participantes 3