danger.java

来自「里面包含了多个java的编程示例!而且举出初学者常常遇到的错误!」· Java 代码 · 共 55 行

JAVA
55
字号
import java.awt.*;
import javax.swing.*;

public class Danger extends JPanel implements Runnable {
    String text = "No text has been specified";
    float hue = (float) 0.5;
    float saturation = (float) 0.8;
    float brightness = (float) 0.0;
    Font textFont = new Font("Dialog", Font.BOLD, 20);
    int textX;
    Thread runner;

    public Danger(String warning) {
        text = warning;
        FontMetrics fm = getFontMetrics(textFont);
        textX = 200 - fm.stringWidth(text) / 2;
        runner = new Thread(this);
        runner.start();
   }

   public void paintComponent(Graphics comp) {
        Graphics2D comp2D = (Graphics2D) comp;
        comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        comp2D.setColor(Color.black);
        comp2D.fillRect(0, 0, 400, 200);
        Color textColor = Color.getHSBColor(hue, saturation,
            brightness);
        comp2D.setColor(textColor);
        comp2D.setFont(textFont);
        comp2D.drawString(text, textX, 30);
    }

    void pause(int duration) {
        try {
            Thread.sleep(duration);
        } catch (InterruptedException e) {
            // do nothing
        }
    }

    public void run() {
        Thread thisThread = Thread.currentThread();
        while (runner == thisThread) {
            pause(75);
            brightness += 0.05;
            if (brightness > 1) {
                brightness = (float) 0.0;
                pause(75);
            }
            repaint();
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?