java实现三个箭头内红绿蓝每隔一秒交替,其余部分为白色的功能,可尝试在此基础上增加姓名水印
时间: 2023-06-02 10:02:07 浏览: 213
以下是使用Java Swing实现的三个箭头交替变色的代码,其中添加了姓名水印:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ArrowPanel extends JPanel {
private int colorIndex = 0;
private Color[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.WHITE};
private String name = "Watermark";
private Font font = new Font("Arial", Font.BOLD, 20);
public ArrowPanel() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
colorIndex = (colorIndex + 1) % colors.length;
repaint();
}
}, 0, 1000);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
int centerX = width / 2;
int centerY = height / 2;
// 绘制箭头
g.setColor(colors[colorIndex]);
g.drawLine(centerX, centerY - 40, centerX, centerY + 40);
g.drawLine(centerX, centerY - 40, centerX - 10, centerY - 30);
g.drawLine(centerX, centerY - 40, centerX + 10, centerY - 30);
g.drawLine(centerX, centerY + 40, centerX - 10, centerY + 30);
g.drawLine(centerX, centerY + 40, centerX + 10, centerY + 30);
// 绘制水印
g.setColor(colors[3]);
g.setFont(font);
g.drawString(name, width - 120, height - 20);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Arrow Panel");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ArrowPanel panel = new ArrowPanel();
frame.add(panel);
frame.setVisible(true);
}
}
```
在这个例子中,我们使用了一个定时器来定期地调用`repaint()`方法,从而实现箭头的颜色交替。在`paintComponent()`方法中,我们首先绘制箭头,然后绘制水印。
要修改水印的内容,只需要将`name`变量赋值为所需的字符串即可。要修改水印的样式,可以修改`font`变量中的字体、大小和样式。
阅读全文