Como posso permitir que um usuário para ver a forma ao arrastar o mouse em uma linha de programa de desenho?

jacobay43:

Eu quero que o programa funcione de modo que à medida que arrasta o mouse sobre o painel, a forma deve ser mostrado, o formato deve mudar em tamanho cada vez que você arraste o mouse, e a forma que deve ser exibido, finalmente, é o que estava sendo exibido no momento em que o mouse foi liberado. O que acontece actualmente é a linha é invisível ao ser desenhado com arrastar do mouse e só aparece quando o mouse é liberado

//DrawPanel
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;

public class DrawLine extends JPanel
{
  private LineClass lines[];
  private int lineCount;
  private LineClass currentLine;
  public JLabel statusLabel;
  private int currShapeX1,currShapeY1;

  public DrawLine()
  {
statusLabel = new JLabel("(0,0)");
lines = new LineClass[100];
lineCount = 0;
currentLine = null;

MouseHandler handler = new MouseHandler();
addMouseListener(handler);
addMouseMotionListener(handler);


  }


  public void paintComponent(Graphics g)
  {
super.paintComponent(g);

for(int count = 0; count < lineCount; ++count)
{
  lines[count].draw(g);
} 

  }

  public static void main(String args[])
  {
JFrame frame = new JFrame();
DrawLine panel = new DrawLine();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
  }

  private class MouseHandler extends MouseAdapter implements   MouseMotionListener
  {
    public void mousePressed(MouseEvent event)
{
  //it assigns currentShape a new shape and initializes both points to the mouse position.
  currShapeX1 = event.getX();
  currShapeY1 = event.getY();           
}
public void mouseReleased(MouseEvent event)
{
  //finish drawing the current shape and place it in the array
  //Set the second point of currentShape to the current mouse position
    currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());

  // and add currentShape to the array.
  //Instance variable shapeCount determines the insertion index. Set     currentShape to null and call method repaint to update the drawing with the new shape.
  lines[lineCount] = currentLine;
  lineCount++;

  currentLine = null;
  repaint();
}
public void mouseDragged(MouseEvent event)
{
  //currently not working
  /*What is desired:
   * As you drag the mouse across the panel, the shape should be showing 
   * The shape should change in size each time you drag the mouse
   * Only one shape should be shown as the mouse is being dragged
   * The shape that should be displayed finally is that which was being displayed at the moment the mouse was released
   * */
  //it sets the second point of the currentShape to the current mouse position and calls method repaint

  //finish drawing the current shape and place it in the array
  //Set the second point of currentShape to the current mouse position
    currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());

  // and add currentShape to the array.
  //Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape.
  lines[lineCount] = currentLine;

  currentLine = null;
  repaint();
  statusLabel.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}

public void mouseMoved(MouseEvent event)
{
  //to set the text of the statusLabel so that it displays the mouse coordinates—this will update the label with the coordinates every time the user moves 
  //(but does not drag) the mouse within the DrawPanel
  statusLabel.setText(String.format("(%d,%d)",event.getX(),event.getY()));
}
}
}

//LineClass
class LineClass
{
private int x1;
private int y1;
private int x2;
private int y2;

public LineClass(int x1, int y1, int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

public void draw(Graphics g)
{
g.drawLine(x1,y1,x2,y2);
}
}
Thomas:

Seu problema parece ser que você não está desenhando a última linha que está sendo arrastado.

Em mouseDragged()que você tem isso:

currentLine = new LineClass(currShapeX1,currShapeY1,event.getX(),event.getY());  
lines[lineCount] = currentLine;
currentLine = null;

Isso define a linha no índice lineCountpara a nova linha.

No entanto, em seguida, quando o processamento você fizer isso:

for(int count = 0; count < lineCount; ++count)
{
  lines[count].draw(g);
}

Você está desenhando todas as linhas, exceto a no índice lineCount.

Em mouseReleased()então você tem lineCount++;e é por isso que a linha mostra-se após a liberação do mouse.

Para corrigir isso, eu não gostaria de acrescentar a linha atualmente arrastado para linesenquanto arrasta. Em vez apenas atualizá-lo mouseDragged. Em mouseReleasedvocê, em seguida, adicioná-lo para a matriz e conjunto currentLinepara null.

Pintura seria assim parecido com este:

for(int count = 0; count < lineCount; ++count) {
  lines[count].draw(g);
}

if( currentLine != null ) {
  //you could set different rendering options here, e.g. a different color
  currentLine.draw(g); 
}

Finalmente, em vez de usar uma variedade que poderia ser melhor usar um List<LineClass>. Dessa forma, você não teria que acompanhar a contagem de linha atual, não ser limitado a 100 linhas ou redimensionar a matriz si mesmo.

Como a lista, então, só contêm linhas não nulas, prestação poderia ser assim:

lines.forEach( line -> line.draw(g) );

if( currentLine != null ) {
  currentLine.draw(g);
}

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=210760&siteId=1
Recomendado
Clasificación