我是Java的新手,但不是编程新手,我无法理解hows paintComponent(Graphics graphics)
,mouseDragged(MouseEvent event)
和mouseMoved(MouseEvent event)
与public static void main(String[] args)
方法相关联。请帮我理解这个问题。
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Leaning Java");
HelloComponent helloObject = new HelloComponent("Ajay");
frame.add(helloObject);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
class HelloComponent extends JComponent implements MouseMotionListener {
String theMessage;
int messageX = 125, messageY = 95;
public HelloComponent(String string) {
theMessage = string;
addMouseMotionListener(this);
}
public void paintComponent(Graphics graphics) {
graphics.drawString(theMessage, messageX, messageY);
}
public void mouseDragged(MouseEvent event) {
messageX = event.getX();
messageY = event.getY();
repaint();
}
public void mouseMoved(MouseEvent event) {
}
}
答案 0 :(得分:1)
在您的代码中,您无需再执行任何操作来调用这些方法。
paintComponent
由JComponent
的父级调用。在您的情况下,您要将HelloComponent
的实例添加到JFrame
。 {} {}会在必要时致电JFrame
。
paintComponent
和mouseDragged
是mouseMoved
界面中定义的方法。通过调用MouseMotionListener
,您可以在适当的鼠标操作发生时注册您的类以接收这些消息。