使用java程序 在window系统实现靠屏幕边缘悬浮球 给出程序示例
时间: 2023-12-10 07:39:32 浏览: 31
以下是一个简单的 Java 程序示例,可以实现在 Windows 系统上实现靠屏幕边缘悬浮球的功能。
```
import java.awt.*;
import javax.swing.*;
public class FloatingBall extends JFrame {
private JPanel ballPanel;
private int ballRadius = 50;
private int ballPosX = 0;
private int ballPosY = 0;
private int screenWidth;
private int screenHeight;
private int directionX = 1;
private int directionY = 1;
public FloatingBall() {
// 获取屏幕尺寸
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
screenWidth = screenSize.width;
screenHeight = screenSize.height;
// 创建悬浮球面板
ballPanel = new JPanel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(ballPosX, ballPosY, ballRadius, ballRadius);
}
};
ballPanel.setPreferredSize(new Dimension(ballRadius, ballRadius));
// 设置窗口属性
setUndecorated(true);
setAlwaysOnTop(true);
setResizable(false);
add(ballPanel);
pack();
setLocation(screenWidth - ballRadius, screenHeight - ballRadius);
// 悬浮球移动
Thread ballThread = new Thread() {
public void run() {
while (true) {
if (ballPosX <= 0) {
directionX = 1;
} else if (ballPosX + ballRadius >= screenWidth) {
directionX = -1;
}
if (ballPosY <= 0) {
directionY = 1;
} else if (ballPosY + ballRadius >= screenHeight) {
directionY = -1;
}
ballPosX += directionX * 5;
ballPosY += directionY * 5;
ballPanel.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
ballThread.start();
}
public static void main(String[] args) {
FloatingBall floatingBall = new FloatingBall();
floatingBall.setVisible(true);
}
}
```
该程序使用了 Java 的 Swing 组件来实现界面的绘制,通过设置窗口的属性和位置,使其在屏幕边缘悬浮。同时,使用线程来实现悬浮球的移动,每次移动的距离为 5 个像素。你可以根据自己的需要来修改代码中的参数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)