gpt4 book ai didi

java - PaintComponent 如何链接到用户定义的类?

转载 作者:行者123 更新时间:2023-12-01 13:09:55 26 4
gpt4 key购买 nike

我是java新手,但对编程并不陌生,我无法理解paintComponent(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) {

}

}

最佳答案

您无需在代码中执行任何操作即可调用这些方法。

paintComponentJComponent 的父级调用。在您的例子中,您将 HelloComponent 的实例添加到 JFrame 中。 JFrame 将在必要时调用 paintComponent

mouseDraggedmouseMoved 是在 MouseMotionListener 接口(interface)中定义的方法。通过调用 addMouseMotionListener(this),您可以注册您的类,以便在发生适当的鼠标操作时接收这些消息。

关于java - PaintComponent 如何链接到用户定义的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22965818/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com