用java写一个消息提醒弹窗,且窗口自适应,窗口透明化,文字在桌面滚动
时间: 2023-05-22 20:02:05 浏览: 73
可以使用 Java Swing 库来实现一个消息提醒弹窗,以下是一个简单的实现示例:
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MessagePopup extends JFrame {
private static final long serialVersionUID = 1L;
private static final int POPUP_WIDTH = 300;
private static final int POPUP_HEIGHT = 100;
private static final int POPUP_DURATION = 5000; // in milliseconds
private static final int SCROLL_SPEED = 2; // in pixels per frame
private static final Font MESSAGE_FONT = new Font("Arial", Font.BOLD, 16);
private static final Color MESSAGE_COLOR = Color.WHITE;
private static final Color BACKGROUND_COLOR = new Color(0, 0, 0, 200);
private static final Timer TIMER = new Timer(POPUP_DURATION, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MessagePopup.this.dispose();
}
});
private final JLabel messageLabel;
public MessagePopup(String message) {
super();
setUndecorated(true);
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
messageLabel = new JLabel(message);
messageLabel.setFont(MESSAGE_FONT);
messageLabel.setForeground(MESSAGE_COLOR);
JPanel contentPane = new JPanel();
contentPane.setBackground(BACKGROUND_COLOR);
contentPane.add(messageLabel);
setContentPane(contentPane);
pack();
Dimension screenSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds().getSize();
Point location = new Point(screenSize.width - POPUP_WIDTH - 10, screenSize.height - POPUP_HEIGHT - 10);
setLocation(location);
setVisible(true);
TIMER.start();
new Thread(new Runnable() {
@Override
public void run() {
Rectangle screenRect = new Rectangle(location, new Dimension(POPUP_WIDTH, POPUP_HEIGHT));
int messageWidth = messageLabel.getPreferredSize().width;
int x = screenRect.x + screenRect.width;
while (x > screenRect.x - messageWidth) {
x -= SCROLL_SPEED;
messageLabel.setLocation(x, 0);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
public static void main(String[] args) {
new MessagePopup("这是一条测试消息!");
}
}
```
这个实现使用了 Java Swing 库中的 JFrame、JLabel 和 JPanel 组件,以及 Timer 和 Thread 类来实现弹窗的自动关闭和文字滚动效果。弹窗的大小和位置可以根据屏幕大小自适应,文字滚动速度和字体颜色、背景颜色等都可以自定义。