是否可以使用JavaFX更改应用程序图标,还是必须使用Swing?
当前回答
stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/icon.png" )));
您可以使用此方法添加多个不同大小的图标。这些图像应该是同一图像的不同大小,并将选择最佳大小。 如。32岁的16 x16 32
其他回答
stage.getIcons().add(new Image("/images/logo_only.png"));
在src文件夹中创建图像文件夹并从中获取图像是一个好习惯。
如果运行jar文件,Michael Berry指定的代码将改变标题栏和任务栏中的图标。快捷图标不可更改。
如果你运行一个用com编译的本地程序。zenjava,你必须添加一个链接到程序图标:
<plugin>
<groupId>com.zenjava</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>8.8.3</version>
<configuration>
...
<bundleArguments>
<icon>${project.basedir}/src/main/resources/images/filename.ico</icon>
</bundleArguments>
</configuration>
</plugin>
这将为快捷方式和任务栏添加一个图标。
在运行时切换图标:
除了这里的响应,我发现一旦你第一次分配了一个图标到你的应用程序,你不能通过添加一个新图标到你的舞台来切换它(这将有助于你的应用程序的图标从打开/关闭启用/禁用)。
要在运行时设置一个新图标,在尝试添加一个新图标之前使用getIcons().remove(0),其中0是你想覆盖的图标的索引,如下所示:
//Setting icon by first time (You can do this on your start method).
stage.getIcons().add(new Image(getClass().getResourceAsStream("enabled.png")));
//Overriding app icon with a new status (This can be in another method)
stage.getIcons().remove(0);
stage.getIcons().add(new Image(getClass().getResourceAsStream("disabled.png")));
为了从其他方法或类中访问stage,你可以在你的主类中为stage创建一个新的静态字段,这样就可以从start()方法中访问它,通过封装在一个静态方法中,你可以从应用程序的任何地方访问它。
public class MainApp extends Application {
private static Stage stage;
public static Stage getStage() { return stage; }
@Override public void start(Stage primaryStage) {
stage = primaryStage
stage.getIcons().add(new Image(getClass().getResourceAsStream("enabled.png")));
}
}
public class AnotherClass {
public void setStageTitle(String newTitle) {
MainApp.getStage().setTitle(newTitle);
MainApp.getStage().getIcons().remove(0);
MainApp.getStage().getIcons().add(new Image(getClass().getResourceAsStream("disabled.png")));
}
}
如果你得到无效的URL或资源没有找到,把你的图标.png在“bin”文件夹在你的工作空间。
这个程序为StackOverflowIcon设置图标。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class StackoverflowIcon extends Application {
@Override
public void start(Stage stage) {
StackPane root = new StackPane();
// set icon
stage.getIcons().add(new Image("/path/to/stackoverflow.jpg"));
stage.setTitle("Wow!! Stackoverflow Icon");
stage.setScene(new Scene(root, 300, 250));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
输出Screnshot
为JavaFX 8更新
不需要更改代码。它仍然可以正常工作。在Java 1.8(1.8.0_45)中测试和验证。路径可设置为本地或远程均支持。
stage.getIcons().add(new Image("/path/to/javaicon.png"));
OR
stage.getIcons().add(new Image("https://example.com/javaicon.png"));
希望能有所帮助。谢谢! !
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap