背景说明
今天在写自己的桌面小工具时,做了一个后台运行的周期性任务,想着每次任务完成时在桌面右下角显示一个文字提示。最终做出来Demo效果如下图,点击"显示提示"按钮,桌面右下角用绿色透明显示"显示提示信息成功!"字样。
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuU2ZhR3ctQnblJXYwNnbhJHdvwVMx8CX1EDMy8CXzRWYvxGc19CX05WZ052bj1Cc39CXuNmLn5WZ65WYsFmL3d3dvw1LcpDc0RHaiojIsJye.png)
实现分析
这里我是新创建了一个Stage,然后将一个Text放到VBox中,进儿放到Stage的Scene中。那么这里就有几个要点:
1) Stage要没有窗口装饰
stage.initStyle(StageStyle.TRANSPARENT);
2) Scene要透明
scene.setFill(null);
3) VBox要透明
box.setStyle("-fx-background:transparent;");
4) Text要设置字体和颜色
text.setFont(new Font(20));
text.setFill(Color.GREEN);
5) Stage要居桌面右下角
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
stage.setX(primaryScreenBounds.getWidth() - width);
stage.setY(primaryScreenBounds.getHeight() - height);
Demo完整代码
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
*
* @author Alan
*/
public class TransparentStage extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("显示提示");
btn.setOnAction((ActionEvent event) -> {
Text text = new Text("显示提示信息成功!");
text.setFont(new Font(20));
text.setFill(Color.GREEN);
VBox box = new VBox();
box.getChildren().add(text);
box.setStyle("-fx-background:transparent;");
final int width = 200;
final int height = 50;
final Scene scene = new Scene(box, width, height);
scene.setFill(null);
final Stage stage = new Stage();
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
stage.setX(primaryScreenBounds.getWidth() - width);
stage.setY(primaryScreenBounds.getHeight() - height);
stage.show();
Task t = new Task() {
@Override
protected Object call() throws Exception {
Thread.sleep(1000);
Platform.runLater(stage::close);
return "";
}
};
new Thread(t).start();
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
http://www.alanzeng.cn/2015/11/javafx-transparent-stage/