Studyon Minte9.com
Java SE




Mouse (listener)



Draw a line in any direction.

package testexample; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import javax.swing.*; public class Test extends JFrame { public static void main(String[] args) { Test frame = new Test(); frame.setBounds(200, 200, 300, 200); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setTitle("Draw line with the mouse"); frame.setVisible(true); } public Test() { JPanel p = new JPanel() { Point start = null; // --- Look Here --- // Point end = null; { addMouseListener(new MouseAdapter() { // --- Look Here --- // @Override public void mousePressed(MouseEvent e) { start = e.getPoint(); } @Override public void mouseReleased(MouseEvent e) { start = null; end = null; } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { end = e.getPoint(); repaint(); } }); } @Override public void paint(Graphics g) { super.paint(g); if (start != null) { g.setColor(Color.red); // --- Look Here --- // g.drawLine(start.x, start.y, end.x, end.y); } } }; add(p); } }
  Chart (mouse dragged)
package testexample; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.geom.Line2D; import javax.swing.*; public class Test extends JFrame { public static Test frame = new Test(); public static void main(String[] args) { frame.setBounds(200, 200, 350, 320); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setTitle("Chart with Grid & Numbers"); frame.setVisible(true); } public Test() { final Chart chart = new Chart(); chart.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { // --- Look Here --- // chart.drawLine(e.getY()); frame.repaint(); } }); add(chart); } } class Chart extends JPanel { public int x = 50; public int y = 50; public int height = 200; public int weight = 30; public Line2D line = new Line2D.Double(x, y, x, height); @Override public void paintComponent(Graphics g1) { super.paintComponent(g1); Graphics2D g = (Graphics2D) g1; g.setPaint(new GradientPaint(x, y, Color.green, x, height, Color.red)); g.setStroke(new BasicStroke(weight)); g.draw(line); } public void drawLine(int yy) { line = new Line2D.Double(50, yy, 50, height); } }
 


http://stackoverflow.com/questions/9711938/java-draw-line-as-the-mouse-is-moved