展开全部
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
/**
* @e68a84e8a2ad3231313335323631343130323136353331333262373932author Hardneedl
*/
class CoordinateDemo extends JFrame {
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(600, 400);
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "Coordinate Demo";}
private class CoordinateCanvas extends JComponent{
private String s;
private CoordinateCanvas() {
addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e) {
s = MessageFormat.format("X:{0,number,integer}, Y:{1,number,integer}",e.getX(),e.getY());
paintImmediately(getBounds());
}
});
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics g2d = g.create();
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0,getWidth(),getHeight());
g2d.setColor(Color.YELLOW);
g2d.drawString(s==null?"":s,20,20);
g2d.dispose();
}
};
CoordinateDemo() throws HeadlessException {
doLay();
attachListeners();
}
private void doLay() {
getContentPane().add(new CoordinateCanvas(),BorderLayout.CENTER);
pack();
}
private void attachListeners() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {new CoordinateDemo().setVisible(true);}
}