Reputation: 1513
This example opens a JFrame with a button. When the button is clicked a JDialog is opened. The XY location of the mouse on the button is captured and used to open the JDialog.
The problem is the XY captured on the button is correct but it is the XY relative to the JFrame. When the JDialog is opened, it is done so relative to the monitor.
Is it possible to have the JDialog open based on the location of the XY from the mouse click?
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class JDialogInJFrame {
private static int index;
MouseEvent mouseXY;
JFrame f;
private void display() {
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jb = new JButton(new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("actionPerformed");
JDialog jd = new JDialog(f);
jd.setTitle("D" + String.valueOf(++index));
jd.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
jd.add(new JButton());
jd.setSize(200, 200);
jd.setLocation(mouseXY.getX(), mouseXY.getY());
jd.setVisible(true);
}
}
);
jb.addMouseListener(new MouseListener ()
{
public void mousePressed(MouseEvent e) {
mouseXY = e;
saySomething("Mouse pressed; # of clicks: "
+ e.getClickCount(), e);
}
public void mouseReleased(MouseEvent e) {
saySomething("Mouse released; # of clicks: "
+ e.getClickCount(), e);
}
public void mouseEntered(MouseEvent e) {
saySomething("Mouse entered", e);
}
public void mouseExited(MouseEvent e) {
saySomething("Mouse exited", e);
}
public void mouseClicked(MouseEvent e) {
saySomething("Mouse clicked (# of clicks: "
+ e.getClickCount() + ")", e);
}
void saySomething(String eventDescription, MouseEvent e) {
System.out.println(eventDescription + " detected on "
+ e.getComponent().getClass().getName());
}
});
f.add(jb);
f.setSize(200, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
new JDialogInJFrame().display();
}
}
Upvotes: 0
Views: 772
Reputation: 1090
There are several SwingUtilities
functions for converting coordinates between component coordinate system and the screen's one. Used like here. It helps for such sort of things.
JButton component = new JButton();
Point pt = new Point(component.getLocation());
SwingUtilities.convertPointToScreen(pt, component);
Upvotes: 3