So I'm doing this simple draw program where I let the user click a button, i.e. Rectangle, and then click any desired place on the JFrame to draw it. Now, I want the user to first click on the JButton, then click anywhere on the JFrame (so that I get the X and Y coordinates) in order to draw, but I don't seem to be able to use Mouse Event mouseClicked on two things. It worked when I had the event.getSource() for the button only, but I want the user to click the button, then the desired drawing position, here's the part of the code that I'm struggling with:

public void mouseClicked (MouseEvent event)
		{
			if (event.getSource() == rectangle_button) //rectangle_button is a JButton that I created before
			{
				if (event.getSource() == panel) //panel is a JPanel that exists anywhere in the frame
				{
					JOptionPane.showMessageDialog(null, "rectangle is drawn");
				}
			}

Thanks for any help.

Edited 4 Years Ago by Hitman Mania: n/a

Umm... What I suggest is, take two global variables frmc and buttonc , and if they're equal to 0, add them up by 1 every time a JPanel/JButton is clicked. When both of them are equal to 1; do whatever you wish to.

Why are you using low-level mouse events for handling a button click? An actionlistener is simpler, and handles keyboard mnemonics as well.
In general your code will be cleaner if you have separate listeners for each event and source, rather than one giant listener full of if tests on the source. In this case you could enable the frame's mouse listener when the user presses the button, then disable it again when they have used it. If you had buttons for rectangle and circle then you could enable one of two different mouse handlers each handling just one case. That code would be much more modular.

This article has been dead for over six months. Start a new discussion instead.