Java聊天室实现收到消息窗口抖动
时间: 2023-11-30 14:04:45 浏览: 49
以下是Java聊天室实现收到消息窗口抖动的示例:
1. 首先,在聊天室窗口中添加一个方法用于处理收到消息时的抖动效果:
```java
public void shakeWindow() {
Point initialLocation = getLocation();
int shakeDistance = 5;
int shakeDuration = 500;
int shakeUpdateInterval = 30;
Timer shakeTimer = new Timer(shakeUpdateInterval, new ActionListener() {
int elapsed = 0;
@Override
public void actionPerformed(ActionEvent e) {
int deltaX = (int) (Math.random() * shakeDistance * 2) - shakeDistance;
int deltaY = (int) (Math.random() * shakeDistance * 2) - shakeDistance;
setLocation(initialLocation.x + deltaX, initialLocation.y + deltaY);
elapsed += shakeUpdateInterval;
if (elapsed >= shakeDuration) {
((Timer) e.getSource()).stop();
setLocation(initialLocation);
}
}
});
shakeTimer.start();
}
```
2. 在聊天室窗口接收到消息时,调用shakeWindow()方法以触发抖动效果:
```java
public void receiveMessage(String message) {
messageArea.append(message + "\n");
shakeWindow();
}
```
这段代码中,receiveMessage()方法用于接收消息并将消息添加到聊天室窗口中的文本区域(messageArea),然后调用shakeWindow()方法以触发抖动效果。在shakeWindow()方法中,通过使用Timer和ActionListener实现了窗口的抖动效果,抖动的时间和幅度都可以通过变量进行控制,这里设定的抖动时间为500毫秒,抖动距离为5个像素。