我已尝试在第一个Applet中编写它并且它工作但是我在drawOval行之后使用了repaint()方法并且它闪烁太多我无法看到..请帮我修复它。
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MouseEvents extends JFrame implements MouseListener, MouseMotionListener {
JFrame frame;
public static void main(String args[]){
MouseEvents obj=new MouseEvents();
obj.go();
}
public void go(){
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void mouseDragged(MouseEvent me) {
repaint();
}
public void mouseMoved(MouseEvent me) {
Graphics g=getGraphics();
g.drawOval(me.getX(), me.getY(), 30,30);
}
}
答案 0 :(得分:0)
getGraphics
)。有关详细信息,请参阅Painting in AWT and Swing和Performing Custom Painting。首先创建一个从JPanel
扩展的类。为此,注册MouseMoitionListener
以跟踪当前鼠标位置。覆盖它的paintComponent
以绘制鼠标移动的圆圈......
public class CirclePane extends JPanel {
private Point p = new Point(100, 100);
public CirclePane() {
MouseAdapter mouseHandler = new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
p = e.getPoint();
repaint();
}
};
addMouseMotionListener(mouseHandler);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawOval(p.x - 50, p.y - 50, 100, 100);
g2d.dispose();
}
}
将此添加到您的相框......
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MouseEvents {
public static void main(String[] args) {
new MouseEvents();
}
public MouseEvents() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CirclePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}