1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class CrossComponent extends JComponent implements AWTEventListener{
private final JFrame frame;
private boolean displayed;
private int mouseX;
private int mouseY;
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
if(displayed) {
g.drawLine(mouseX, 0,mouseX, getHeight());
g.drawLine(0, mouseY,getWidth(), mouseY);
}
}
public boolean isDisplayed() {
return displayed;
}
public void setDisplayed(boolean displayed) {
this.displayed = displayed;
}
/**
* @param displayed
*/
public CrossComponent(boolean displayed, JFrame frame) {
this.displayed = displayed;
this.frame = frame;
Toolkit.getDefaultToolkit().addAWTEventListener(this,AWTEvent.MOUSE_EVENT_MASK);
Toolkit.getDefaultToolkit().addAWTEventListener(this,AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
public void eventDispatched(AWTEvent arg0) {
// TODO Auto-generated method stub
if(arg0 instanceof MouseEvent) {
MouseEvent event = (MouseEvent) arg0;
if (!SwingUtilities.isDescendingFrom(event.getComponent(), frame)) {
return;
}
Point point = new Point(mouseX,mouseY);
if (event.getID() == MouseEvent.MOUSE_EXITED && event.getComponent() == frame) {
//point = null;
} else {
MouseEvent converted = SwingUtilities.convertMouseEvent(event.getComponent(), event, frame.getGlassPane());
point = converted.getPoint();
}
mouseX = point.x;
mouseY = point.y;
repaint();
//forward(event);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final JFrame f = new JFrame();
JButton b = new JButton("toto");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Hello World");
}
});
f.add(b);
CrossComponent c = new CrossComponent(true, f);
f.setGlassPane(c);
f.getGlassPane().setVisible(true);
f.setSize(200,200);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
} |
Partager