There are number of problems with this code
public class LineEx extends JFrame implements MouseMotionListener,MouseListener{
int x1,y1,x2,y2;
public LineEx(){
JLabel image=new JLabel("");
JFileChooser chooser=new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int r=chooser.showOpenDialog(new JFrame());
File file=chooser.getSelectedFile();
if(r==JFileChooser.APPROVE_OPTION){
try {
BufferedImage bf;
bf = ImageIO.read(file);
ImageIcon icon=new ImageIcon(bf);
image.setIcon(icon);
image.setHorizontalAlignment(JLabel.CENTER);
} catch (IOException ex) {
Logger.getLogger(LineEx.class.getName()).log(Level.SEVERE, null, ex);
}
}
JScrollPane jsp=new JScrollPane(image);
getContentPane().add(jsp);
image.addMouseListener(this);
image.addMouseMotionListener(this);
this.pack();
}
public static void main(String ar[]){
LineEx line=new LineEx();
line.setVisible(true);
line.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
x1=e.getX();
y1=e.getY();
}
public void mouseReleased(MouseEvent e) {
JOptionPane.showMessageDialog(rootPane, "X1="+x1+" Y1="+y1);
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
@Override
public void paint(Graphics g){
super.paintComponents(g);
Graphics2D gd=(Graphics2D)g;
gd.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Line2D line=new Line2D.Double(x1,y1,x2,y2);
gd.draw(line);
}
public void mouseDragged(MouseEvent e) {
x2=e.getX();
y2=e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
- MouseEvents are not getting exact co-ordinates that means whenever i draw a line it is not on its position. What is the reason behind this?
- I want to move line along the image when scrollbar goes up and down, how can i do that?
JFrame
).BufferedImage
that was loaded.GridBagLayout
with no constraint, so it is centered.BorderLayout.CENTER
) of a parent component.Note that you might also add the line objects to an expandable collection such as an
ArrayList
orDefaultListModel
, then display them in aJList
to theWEST
of the image scroll pane. This would make it easier to manage (and potentially delete) groups of lines.You are getting the correct coordinates from the
JLabel
but paints on theJFrame
. And the frame coordinates begins at the top left point and "includes" the window title/border.Override the
paintComponent
method on theJLabel
and it you will get the correct insets and coordinates.Example:
Test code (generates this screenshot):