下面列出了怎么用javafx.scene.image.Image的API类实例代码及写法,或者点击链接到github查看源代码。
@InvokableAction(
name = "Save Screenshot",
category = "general",
description = "Save image of visible screen",
alternatives = "Save image;save framebuffer;screenshot",
defaultKeyMapping = "ctrl+shift+s")
public static void saveScreenshot() throws IOException {
FileChooser select = new FileChooser();
Emulator.computer.pause();
Image i = Emulator.computer.getVideo().getFrameBuffer();
// BufferedImage bufImageARGB = SwingFXUtils.fromFXImage(i, null);
File targetFile = select.showSaveDialog(JaceApplication.getApplication().primaryStage);
if (targetFile == null) {
return;
}
String filename = targetFile.getName();
System.out.println("Writing screenshot to " + filename);
String extension = filename.substring(filename.lastIndexOf(".") + 1);
// BufferedImage bufImageRGB = new BufferedImage(bufImageARGB.getWidth(), bufImageARGB.getHeight(), BufferedImage.OPAQUE);
//
// Graphics2D graphics = bufImageRGB.createGraphics();
// graphics.drawImage(bufImageARGB, 0, 0, null);
//
// ImageIO.write(bufImageRGB, extension, targetFile);
// graphics.dispose();
}
public PauseResumeButton(boolean isPaused) {
this.isPaused[0] = isPaused;
this.imagePause = new Image(getClass().getResourceAsStream("/gearth/ui/buttons/files/ButtonPause.png"));
this.imagePauseOnHover = new Image(getClass().getResourceAsStream("/gearth/ui/buttons/files/ButtonPauseHover.png"));
this.imageResume = new Image(getClass().getResourceAsStream("/gearth/ui/buttons/files/ButtonResume.png"));
this.imageResumeOnHover = new Image(getClass().getResourceAsStream("/gearth/ui/buttons/files/ButtonResumeHover.png"));
this.imageView = new ImageView();
setCursor(Cursor.DEFAULT);
getChildren().add(imageView);
setOnMouseEntered(onMouseHover);
setOnMouseExited(onMouseHoverDone);
imageView.setImage(isPaused() ? imageResume : imagePause);
setEventHandler(MouseEvent.MOUSE_CLICKED, event -> click());
}
public File getImageFile() throws FileNotFoundException {
File privateStorage = Services.get(StorageService.class)
.flatMap(StorageService::getPrivateStorage)
.orElseThrow(() -> new FileNotFoundException ("Could not access private storage"));
Image image = this.getImage();
PngEncoderFX encoder = new PngEncoderFX(image, true);
byte[] bytes = encoder.pngEncode();
File file = new File(privateStorage, "Image-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("uuuuMMdd-HHmmss")) + ".png");
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(bytes);
return file;
} catch (IOException ex) {
System.out.println("Error: " + ex);
return null;
}
}
@Override
public void start(Stage stage) {
Image logo = new Image(getClass().getResourceAsStream("/pattypan/resources/logo.png"));
Scene scene = new Scene(new StartPane(stage), Settings.getSettingInt("windowWidth"), Settings.getSettingInt("windowHeight"));
stage.setResizable(true);
stage.setTitle("pattypan " + Settings.VERSION);
stage.getIcons().add(logo);
stage.setScene(scene);
stage.show();
stage.setOnCloseRequest((WindowEvent we) -> {
Settings.setSetting("windowWidth", (int) scene.getWidth() + "");
Settings.setSetting("windowHeight", (int) scene.getHeight() + "");
Settings.setSetting("version", Settings.VERSION);
Settings.saveProperties();
});
}
/**
* @Title: addWebView
* @Description: 添加WebView视图
*/
public void addWebView(String title, String url, String iconPath) {
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
if (url.startsWith("http")) {
webEngine.load(url);
} else {
webEngine.load(IndexController.class.getResource(url).toExternalForm());
}
if (indexController.getSingleWindowBootCheckBox().isSelected()) {
JavaFxViewUtil.getNewStage(title, iconPath, new BorderPane(browser));
return;
}
Tab tab = new Tab(title);
if (StringUtils.isNotEmpty(iconPath)) {
ImageView imageView = new ImageView(new Image(iconPath));
imageView.setFitHeight(18);
imageView.setFitWidth(18);
tab.setGraphic(imageView);
}
tab.setContent(browser);
indexController.getTabPaneMain().getTabs().add(tab);
indexController.getTabPaneMain().getSelectionModel().select(tab);
}
public void optionsButton(MouseEvent mouseEvent)
{
if (mouseEvent.getSource() instanceof ImageView)
{
ImageView imgView = (ImageView) mouseEvent.getSource();
if (mouseEvent.getEventType().equals(MouseEvent.MOUSE_ENTERED))
imgView.setImage(new Image(getClass().getResource("ico/options1.png").toString()));
else if (mouseEvent.getEventType().equals(MouseEvent.MOUSE_EXITED))
imgView.setImage(new Image(getClass().getResource("ico/options0.png").toString()));
else if (mouseEvent.getEventType().equals(MouseEvent.MOUSE_CLICKED))
{
HelperZonePane.setVisible(false);
gemSelectorAnchorPane.setVisible(false);
optionsAnchorPane.setVisible(true);
act1Button.setVisible(true);
act2Button.setVisible(true);
act3Button.setVisible(true);
act4Button.setVisible(true);
act5Button.setVisible(true);
inOptions = true;
}
}
}
/**
* Display a dialog grabbing the user's input.
*
* @param message the message to display to the user on the dialog.
* @param title the title of the dialog.
* @return the user entered text.
*/
public static String getUserInput(final String message, final String title) {
Utils.fxRunAndWait(() -> {
dialog = new LiveTextDialog();
dialog.setTitle(title);
dialog.textField.clear();
dialog.messageLabel.setText(message);
dialog.messageLabel.setWrapText(true);
dialog.getIcons().add(new Image("file:icons/live_text.png"));
dialog.showAndWait();
});
while (dialog.isShowing()) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
if (!dialog.isShowing()) {
QueleaApp.get().getMobileLyricsServer().setText("");
}
return dialog.textField.getText();
}
public static Image replaceColor(Image image, Color oldColor, Color newColor, int distance) {
if (image == null || oldColor == null || newColor == null || distance < 0) {
return image;
}
try {
ImageScope scope = new ImageScope(image);
scope.setScopeType(ScopeType.Color);
scope.setColorScopeType(ImageScope.ColorScopeType.Color);
scope.getColors().add(ImageColor.converColor(oldColor));
scope.setColorDistance(distance);
PixelsOperation pixelsOperation = PixelsOperation.create(image,
scope, PixelsOperation.OperationType.Color, PixelsOperation.ColorActionType.Set);
pixelsOperation.setColorPara1(ImageColor.converColor(newColor));
Image newImage = pixelsOperation.operateFxImage();
return newImage;
} catch (Exception e) {
return null;
}
}
@Override
protected void updateItem(final ActionInfo action, final boolean empty)
{
super.updateItem(action, empty);
try
{
if (action == null)
{
setText("");
setGraphic(null);
}
else
{
setText(action.toString());
setGraphic(new ImageView(new Image(action.getType().getIconURL().toExternalForm())));
}
}
catch (Exception ex)
{
logger.log(Level.WARNING, "Error displaying " + action, ex);
}
}
/** @param clazz Class from which to load, if not already cached
* @param path Path to the image, based on clazz
* @return Image, may be cached copy
*/
public static Image getImage(final Class<?> clazz, final String path)
{
return cache(path, () ->
{
final URL resource = clazz.getResource(path);
if (resource == null)
{
PhoebusApplication.logger.log(Level.WARNING, "Cannot load image '" + path + "' for " + clazz.getName());
return null;
}
try
{
return new Image(resource.toExternalForm());
}
catch (Throwable ex)
{
PhoebusApplication.logger.log(Level.WARNING, "No image support to load image '" + path + "' for " + clazz.getName(), ex);
return null;
}
});
}
public static Image blendImages(Image foreImage, Image backImage,
ImagesRelativeLocation location, int x, int y,
boolean intersectOnly, ImagesBlendMode blendMode, float opacity) {
if (foreImage == null || backImage == null || blendMode == null) {
return null;
}
BufferedImage source1 = SwingFXUtils.fromFXImage(foreImage, null);
BufferedImage source2 = SwingFXUtils.fromFXImage(backImage, null);
BufferedImage target = ImageBlend.blendImages(source1, source2,
location, x, y, intersectOnly, blendMode, opacity);
if (target == null) {
target = source1;
}
Image newImage = SwingFXUtils.toFXImage(target, null);
return newImage;
}
public void fillRefundTable()
{
final ObservableList<Refund> data = FXCollections.observableArrayList();
ArrayList<ArrayList<String>> refundData = cashier.cashier.getWaitingRefunds();
int size = refundData.size();
for(int i = 1; i < size; i++)
{
String refundId = refundData.get(i).get(0);
String billId = refundData.get(i).get(1);
//String paymentType = refundData.get(i).get(2);
String reason = refundData.get(i).get(3);
String amount = refundData.get(i).get(4);
String date = refundData.get(i).get(5);
Image img2 = new Image(getClass().getResource("/imgs/refund.png").toString(), true);
ImageView imageView = new ImageView(img2);
imageView.setFitHeight(25);
imageView.setFitWidth(25);
imageView.setPreserveRatio(true);
data.add(new Refund(refundId,date,billId,reason,amount,imageView));
}
refundTable.setItems(data);
}
/**
* Create the SceneManager.
*
* <p>This constructor creates instances of the non-controller-specific classes used by this
* class.
*
* @param stage the stage of the main application window
*/
public SceneManager(Stage stage) {
Config loaded_config = Data.loadConfig();
this.config = loaded_config == null ? new Config() : loaded_config;
this.stage = stage;
this.stageConfig = new Stage();
this.roots = new HashMap<>();
this.controllers = new HashMap<>();
this.pluginManager = new PluginManager(this.config);
this.contentLoader = new ContentLoader();
// add icon to the window bar
Image window_icon = new Image(getClass().getResourceAsStream("/img/window_icon.png"));
stage.getIcons().add(window_icon);
stageConfig.getIcons().add(window_icon);
}
public SpriteView(Image spriteSheet, SpriteView following) {
this(spriteSheet, following.getLocation().offset(-following.getDirection().getXOffset(), -following.getDirection().getYOffset()));
number.set(following.number.get() + 1);
this.following = following;
setDirection(following.getDirection());
following.follower = this;
setMouseTransparent(true);
}
private void select(Image image, String value) {
alert.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> {
System.out.println(value);
});
}
/**
* Get the preview icon of this song.
* <p/>
*
* @return the song's preview icon.
*/
@Override
public ImageView getPreviewIcon() {
if (getID() < 0) {
return new ImageView(new Image("file:icons/lyricscopy.png"));
} else if (hasChords()) {
return new ImageView(new Image("file:icons/lyricsandchords.png"));
} else {
return new ImageView(new Image("file:icons/lyrics.png"));
}
}
private final void update() {
text.setText(model.getText());
currentCompilation = latexData.getCompilationPool().submit(() -> {
final Tuple<Image, String> image = createImage();
Platform.runLater(() -> updateImageText(image));
});
}
public void gemRewardForward(MouseEvent mouseEvent)
{
if (mouseEvent.getSource() instanceof ImageView)
{
ImageView imgView = (ImageView) mouseEvent.getSource();
if (mouseEvent.getEventType().equals(MouseEvent.MOUSE_ENTERED))
imgView.setImage(new Image(getClass().getResource("ico/collapse0_hl.png").toString()));
else if (mouseEvent.getEventType().equals(MouseEvent.MOUSE_EXITED))
imgView.setImage(new Image(getClass().getResource("ico/collapse0.png").toString()));
else if (mouseEvent.getEventType().equals(MouseEvent.MOUSE_CLICKED))
setGemSelectionData(lastUsedPageHandler(true));
}
}
@Override
public void start(Stage stage) {
VBox vbox = new VBox();
Scene scene = new Scene(vbox);
stage.setTitle("Hyperlink Sample");
stage.setWidth(570);
stage.setHeight(550);
selectedImage.setLayoutX(100);
selectedImage.setLayoutY(10);
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
for (int i = 0; i < captions.length; i++) {
final Hyperlink hpl = hpls[i] = new Hyperlink(captions[i]);
final Image image = images[i] = new Image(getClass().getResourceAsStream(imageFiles[i]));
hpl.setGraphic(new ImageView(image));
hpl.setFont(Font.font("Arial", 14));
final String url = urls[i];
hpl.setOnAction((ActionEvent e) -> {
webEngine.load(url);
});
}
HBox hbox = new HBox();
hbox.setAlignment(Pos.BASELINE_CENTER);
hbox.getChildren().addAll(hpls);
vbox.getChildren().addAll(hbox, browser);
VBox.setVgrow(browser, Priority.ALWAYS);
stage.setScene(scene);
stage.show();
}
public void init_for_popup(Image iv, String buildName,String ascendAndLevel,int id, Consumer<Integer> callback){
banner.setImage(iv);
this.buildName.setText(buildName);
//this.ascendAndLevel.setText(ascendAndLevel+" lvl.95");
this.ascendAndLevel.setText(ascendAndLevel);
this.buildSelectorCallback = callback;
this.id_for_popup = id;
}
public Image getThemePreviewImage() {
previewImage = new WritableImage(200, 150);
canvas.snapshot(new SnapshotParameters(), previewImage);
BufferedImage bi = SwingFXUtils.fromFXImage((WritableImage) previewImage, null);
SwingFXUtils.toFXImage(bi, previewImage);
return previewImage;
}
public IconPane(Image normalImage, Image hoverImage, Image pressedImage) {
this.normalImage = normalImage;
this.hoverImage = hoverImage;
this.pressedImage = pressedImage;
initComponent();
iniEvent();
}
public DigitalClock() {
super(480, 412);
// add background image
ImageView background = new ImageView(new Image(getClass().getResourceAsStream("DigitalClock-background.png")));
// add digital clock
clock = new Clock(Color.ORANGERED, Color.rgb(50,50,50));
clock.setLayoutX(45);
clock.setLayoutY(186);
clock.getTransforms().add(new Scale(0.83f, 0.83f, 0, 0));
// add background and clock to sample
getChildren().addAll(background, clock);
}
/**
* Creates a client mainframe and showing it
*
* @param stage javafx application stage
* @param clientversion version of the client
* @param clientversiondate date of the version of the client
* @param clientupgradepage the page to show in case of upgrade
* @param actionsourcetransformer transformer of widgets sending events to
* action event to their significant parent (e.g.
* tablecell -> tableview)
* @param pagenodecatalog list of CPageNodes managed
* @param urltoconnectto URL to connect to at start
* @param nolog no logs are shown in the server
* @param smallicon URL to the small icon (32x32)
* @param bigicon URL to the big icon (64x64)
* @param questionmarkicon URL of the question mark uicon
* @param cssfile URL to the CSS file
* @throws IOException if any bad happens while setting up the logs
*/
public ClientMainFrame(Stage stage, String clientversion, Date clientversiondate,
ClientUpgradePageGenerator clientupgradepage, ActionSourceTransformer actionsourcetransformer,
CPageNodeCatalog pagenodecatalog, String urltoconnectto, boolean nolog, String smallicon, String bigicon,
String questionmarkicon, String cssfile) throws IOException {
this.nolog = nolog;
this.stage = stage;
this.clientversion = clientversion;
this.clientversiondate = clientversiondate;
this.clientupgradepage = clientupgradepage;
CPageNode.setPageCatelog(pagenodecatalog);
initiateLog();
logger.severe("--------------- * * * Open Lowcode client * * * ---------------");
logger.severe(" * * version="+clientversion+", client built date="+sdf.format(clientversiondate)+"* *");
// ---------------------------------------- initiates the first tab
uniqueclientsession = new ClientSession(this, actionsourcetransformer, urltoconnectto, questionmarkicon);
if (smallicon != null)
stage.getIcons().add(new Image(smallicon));
if (bigicon != null)
stage.getIcons().add(new Image(bigicon));
Scene scene = new Scene(this.uniqueclientsession.getClientSessionNode(), Color.WHITE);
if (cssfile != null)
scene.getStylesheets().add(cssfile);
stage.setScene(scene);
stage.setTitle("Open Lowcode client");
// ---------------------------------------- show the stage
stage.setMaximized(true);
this.stage.show();
}
private TreeView<Object> createTreeView(Field listField, ObservableValue<String> filter) {
TreeView<Object> elements = new TreeView<>();
elements.setCellFactory(param -> new TreeCell<Object>() {
@Override
protected void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText(null);
setGraphic(null);
} else {
setText(item.toString());
if (UIEntity.class.isAssignableFrom(item.getClass())) {
try (InputStream is = getClass().getResourceAsStream("/acmi/l2/clientmod/xdat/nodeicons/" + UI_NODE_ICONS.getOrDefault(item.getClass().getSimpleName(), UI_NODE_ICON_DEFAULT))) {
setGraphic(new ImageView(new Image(is)));
} catch (IOException ignore) {}
}
}
}
});
elements.setShowRoot(false);
elements.setContextMenu(createContextMenu(elements));
InvalidationListener treeInvalidation = (observable) -> buildTree(editor.xdatObjectProperty().get(), listField, elements, filter.getValue());
editor.xdatObjectProperty().addListener(treeInvalidation);
xdatListeners.add(treeInvalidation);
filter.addListener(treeInvalidation);
return elements;
}
@Override
protected void updateItem(Integer cond, boolean empty) {
super.updateItem(cond, empty);
this.getStyleClass().removeAll("cond0", "cond1", "cond2", "cond3");
if (!empty) {
if (cond != null) {
URL url = null;
if (cond == 2) {
url = PluginServices.getResource("logbook/gui/cond_orange.png");
} else if (cond == 3) {
url = PluginServices.getResource("logbook/gui/cond_red.png");
}
if (url != null) {
this.setGraphic(new ImageView(new Image(url.toString())));
}
this.setText(cond.toString());
this.getStyleClass().add("cond" + cond);
} else {
this.setGraphic(null);
this.setText(null);
}
} else {
this.setGraphic(null);
this.setText(null);
}
}
/**
* Create our input dialog.
*/
private InputDialog() {
initModality(Modality.APPLICATION_MODAL);
setResizable(false);
BorderPane mainPane = new BorderPane();
messageLabel = new Label();
BorderPane.setMargin(messageLabel, new Insets(5));
mainPane.setTop(messageLabel);
textField = new TextField();
BorderPane.setMargin(textField, new Insets(5));
mainPane.setCenter(textField);
okButton = new Button(LabelGrabber.INSTANCE.getLabel("ok.button"), new ImageView(new Image("file:icons/tick.png")));
okButton.setDefaultButton(true);
okButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
hide();
}
});
BorderPane.setMargin(okButton, new Insets(5));
BorderPane.setAlignment(okButton, Pos.CENTER);
mainPane.setBottom(okButton);
Scene scene = new Scene(mainPane);
if (QueleaProperties.get().getUseDarkTheme()) {
scene.getStylesheets().add("org/modena_dark.css");
}
setScene(scene);
}
private void retrieveFakePicture() {
InputStream sixStream = StartPresenter.class.getResourceAsStream("/six.png");
Image im = new Image(sixStream);//, 28d,28d,true, true);
imageView.updateImage(main, im);
try {
model.setCurrentImageFile(imageView.getImageFile());
} catch (FileNotFoundException ex) {
Logger.getLogger(StartPresenter.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Image getImage() {
Rectangle2D viewport = new Rectangle2D(pane.getLayoutX(), pane.getLayoutY(), pane.getWidth(), pane.getHeight());
SnapshotParameters p = new SnapshotParameters();
p.setViewport(viewport);
WritableImage image = baseStackPane.snapshot(p, null);
return image;// imageView.getImage();
}
public SettingsDialog(javafx.stage.Stage owner, PlainDictAppOptions _opt, ResourceBundle _bundle)
{
super();
opt=_opt;
bundle=_bundle;
setTitle(bundle.getString(UI.settings));
getIcons().add(new Image(HiddenSplitPaneApp.class.getResourceAsStream("shared-resources/settings.png")));
addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
public void handle(KeyEvent e) {
if (EscComb.match(e)) {
hide();
e.consume();
}
}
});
content = new VBox(make_switchable_path_picker(true, UI.overwrite_browser,opt.getBrowserPathOverwrite(), opt.GetBrowserPathOverwriteEnabled())
, make_switchable_path_picker(true, UI.overwrite_browser_search,opt.GetSearchUrlOverwrite(), opt.GetSearchUrlOverwriteEnabled())
, make_switchable_path_picker(false, UI.overwrite_browser_search1,opt.getSearchUrlMiddle(), false)
, make_switchable_path_picker(false, UI.overwrite_browser_search2,opt.getSearchUrlRight(), false)
, make_switchable_path_picker(false, UI.ow_bsrarg,opt.getBrowserArgs(), false)
, make_switchable_path_picker(true, UI.overwrite_pdf_reader,opt.GetPdfOverwrite(), opt.GetPdfOverwriteEnabled())
, make_switchable_path_picker(true, UI.overwrite_pdf_reader_args,opt.GetPdfArgsOverwrite(), opt.GetPdfArgsOverwriteEnabled())
, make_simple_buttons(UI.pdffolders, regex_config)
, make_simple_seperator()
, make_3_simple_switcher(bundle,this, regex_enable, opt.GetRegexSearchEngineEnabled(), ps_regex, opt.GetPageSearchUseRegex(), class_case, opt.GetClassicalKeyCaseStrategy())
, make_3_simple_switcher(bundle,this, tintwild, opt.GetTintWildResult(), remwsize, opt.GetRemWindowSize(), remwpos, opt.GetRemWindowPos())
, make_3_simple_switcher(bundle,this, tintfull, opt.GetTintFullResult(), doclsset, opt.GetDoubleClickCloseSet(), doclsdict, opt.GetDoubleClickCloseDict())
, make_simple_seperator()
, make_3_simple_switcher(bundle,this, dt_dictpic, opt.GetDetachDictPicker(), dt_advsrch, opt.GetDetachAdvSearch(), dt_setting, opt.GetDetachSettings())
, make_simple_seperator()
, make_3_simple_switcher(bundle,this, autopaste, opt.GetAutoPaste(), filterpaste, opt.GetFilterPaste(), Toodoo, false)
, make_simple_seperator()
);
ScrollPane sv = new ScrollPane(content);
sv.setFitToWidth(true);
Scene Scene = new Scene(sv, 800, 600);
setScene(Scene);
}