how to draw on jFrame

hello everyone,

I am trying to draw on a JFrame some circles and some ovals using drawOval() method whenever the user clicks the left mouse button.

I have implemented the above description, however whenever i click the Left MB i dont see the drawings right away. I had to restore down and maximize the window. In which case, the drawing appear this time bt in a different location.

I would really appreciate if someone can provide assistance with these two matters:

1- why do n't the drawinings occur instantly upon clicking the left mouse button.

2- why do the drawings occur in a different location from where i originally clicked. Please bear in mind that i am implementing the mouse action listener to capture the x,y of user clicks.

I also would like to note that the shape that i am drawing, is drawn on a panel which is added to the frame. here is the code:

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

import javax.swing.*;

public class Test{

Node node;

int lastx, lasty;

JFrame f;

MouseListener m;

public Test(){

}

public void create()

{f = new JFrame();

f.setTitle("window one");

f.setLocation(0,0);

f.setSize(500, 500);

f.setBackground(Color.pink);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

f.addMouseListener(m);

}

public void mousePressed(MouseEvent e)

{

}

public void mouseReleased(MouseEvent e)

{

lastx= e.getX();

lasty = e.getY();

System.out.println(e.getX()+ ""+e.getY());

if (e.getButton()==1)

{

node = new Node(lastx,lasty);

System.out.println(node.getX()+ ""+node.getY());

f.getContentPane().add(node);

}

else

if(e.getButton() == 2)

{

}

else

if(e.getButton() == 3)

{

}

}

public void mouseEntered(MouseEvent e)

{

}

public void mouseExited(MouseEvent e)

{

}

public void mouseClicked(MouseEvent e)

{

}

public static void main(String[] args)

{

Test test = new Test();

test.create();

}

Thank you

Regards

[2282 byte] By [islam2104a] at [2007-10-3 8:37:58]
# 1

> the shape that i am drawing, is drawn on a panel which is added to the frame.

> 1- why do n't the drawinings occur instantly upon clicking the left mouse button.

because you are adding a component you would need to call

f.validate();

f.repaint();//sometimes required, sometimes not

immediately after adding the component

> 2- why do the drawings occur in a different location from where i originally clicked.

the default layout manager for JFrame is BorderLayout, so when you call

f.getContentPane().add(node);

you add the 'node' to BorderLayout.CENTER (default location), taking up all

the available space of the contentPane.

you should only be able to see the single (last) node at any time.

depending on what you're trying to do, it might be easier to use a JPanel and

it's paintComponent() to draw your circles/ovals

Michael_Dunna at 2007-7-15 3:45:53 > top of Java-index,Desktop,Core GUI APIs...