Why is the toolbar not visible in executable Jar created using IntelliJ? - image

I have created a jar file for my GUI application using IntelliJ. However, when I run the file, I cannot see the toolbar which contains the buttons with ImageIcon for different functionaltites. On looking around over stackoverflow (like here: Java Swing ImageIcon, where to put images?), I found that the file path for the images could be an issue. At present I am using the following code:
OpenImagingFileButton = new JButton(createImageIcon(currentPath.concat("/src/main/java/uni/images/open-file-icon-img.png")));
The currentPath variable is obtained using this:
final String currentPath = currentRelativePath.toAbsolutePath().toString();
And the createImageIcon method has the following code:
/**
* Returns an ImageIcon, or null if the path was invalid.
*/
protected static ImageIcon createImageIcon(String path) {
ImageIcon toolBarImage = new ImageIcon(path);
Image image = toolBarImage.getImage(); // transform it
Image newImg = image.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
toolBarImage = new ImageIcon(newImg); // transform it back
return toolBarImage;
}
This code works perfectly when I run it in intelliJ, however, the toolbar is not visible when I run the jar. I also tried moving the images folder directly under src folder and then doing this:
ImageIcon(this.getClass().getResource("/images/open-file-icon-img.png"));
But this gives me aNullPointerException. Where am I going wrong?

You don’t need to use the current path here. Since you are working in IntelliJ, simply mark the folder as resources root, by selecting the src folder and right clicking it to find
mark directory as
Move the images folder under the src folder. Then use the following code to set the image icon as a button
Java - setting classpath
openProject = new JButton();
openProject.setIcon(createToolIcon("/images/openProject.png"));
And place the createToolIcon method in the same class file or create a separate class and call the method using that class.
public static ImageIcon createToolIcon(String path) {
URL url = System.class.getResource(path);
if(url == null) {
System.err.println("Unable to load Image: " + path);
}
ImageIcon icon = new ImageIcon(url);
Image img = icon.getImage();
Image newimg = img.getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)
ImageIcon newIcon = new ImageIcon(newimg);
return newIcon;
}

Related

Setting link URL with Google Docs API doesn't result in update of image

I'm trying to update a placeholder image with a new image that has an updated URL. The URL in fact is a valid Google Static Map URL that I'm using in other contexts successfully. I'm using the Google Document API to manipulate the document. Following the code I've been using:
var element = body.findElement(DocumentApp.ElementType.INLINE_IMAGE).getElement();
var imageMap = element.asInlineImage();
// if there was an image found in document
if (imageMap != null) {
// get current parent and index inside parent
var parent = imageMap.getParent();
var childIndex = parent.getChildIndex(imageMap);
// remove image from paragraph
imageMap = imageMap.removeFromParent();
// get static image url for territory
var url = getStaticMapURLForTerritory(id);
Logger.log(url);
imageMap.setLinkUrl(url);
// create a new image
parent.insertInlineImage(childIndex, imageMap)
}
This seems to work fine in that it does update the image url correctly. However, the image itself (the result of the url) is not updated. When I click on the link URL it does return the correct image.
Is there a way to force a refetch of the image blob associated with the URL? I've also attempted to use UrlFetchApp but that complains about a missing size parameter (google static api) which is certainly included in the url string and within the max 640x640 bounds.
I've exhausted all my options unless....
TIA, --Paul
setLinkUrl only does that: sets the link. To actually add a new image you'll have to get its blob:
function replaceImage() {
// [...]
// get static image url for territory
const url = getStaticMapURLForTerritory(id)
const response = UrlFetchApp.fetch(url)
// create a new image
parent.insertInlineImage(childIndex, response.getBlob())
.setAltDescription(img.getAltDescription())
.setAltTitle(img.getAltTitle())
.setWidth(img.getWidth())
.setHeight(img.getHeight())
.setLinkUrl(url)
}
References
Class InlineImage (Google Apps Script reference)

Using ImageIcon to access a picture, can't access it, how to fix?

I am using ImageIcon to access a photo I have cropped. I put all the cropped pictures in a pic source folder in side the project. Yet when I try to use this.getClass().getResource("image 2.png") to find the image 2.png photo, the code couldn't find it. Is there anyway to fix this, do I have to re upload all the picture into a different folder?
the "image 2.png" is inside the pic source folder, which is within the folder of the project Alle, according to the navigator panel on the right. (I am using eclipse)
Here is my code:
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
public class alle extends JFrame {
JButton button1, button2;
JLabel Label1, Label2;
ImageIcon Icon1;
ImageIcon Icon2;
public alle() {
setLayout(new GridLayout(2,3)); //create a gridwolrd like thing that's like 2 row, 3 column
button1 = new JButton("set");
add(button1);
Label1 = new JLabel(" button");
add(Label1);
Icon1 = new ImageIcon(this.getClass().getResource("/alle/pic/image 2.png")) ;
JLabel p = new JLabel(Icon1);
add(p);
}
public static void main (String arg[]) {
alle adfc = new alle();
adfc.setResizable(false);
adfc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
adfc.setVisible(true);
adfc.pack();
File f = new File ("/alle/pic/image 2.png");
System.out.print(f.exists());}}
I also had this kind of problem about a year ago. You should be able to resolve it by writing a loader method for retrieving the images. You can find a detailed answer on this article which also worked for me: Images Won't Appear In A Jar
If you don't want to read through the whole post here's the code sample that should resolve things, you only need to adjust it to your needs:
public ImageIcon loadIcon(String iconName) throws IOException {
ClassLoader loader = this.getClass().getClassLoader();
BufferedImage icon = ImageIO.read(loader.getResourceAsStream(iconName));
return new ImageIcon(icon);
}
From this method you should be able to retrieve your images. I hope this helps you.

Define download path dotnetbrowser

I use dotnetbrowser to display a web browser on a old windows framework.
have you an idea to define the download path ?
My dotnetbroser is enable, i can show my webpage but i don't found in documentation or exemple how define this simple download path.
The only exemple that i've found is about the download event detection.
I use WPF in C#
Thanks.
The DotNetBrowser.DownloadItem.DestinationFile property is writable and can be used to configure the path to store the file.
To set this property in your application, you need to subclass the DotNetBrowser.DefaultDownloadHandler and implement its AllowDownload(DownloadItem) method. Then you need to configure your download handler as shown in the documentation article: File Download
You can also configure and use DotNetBrowser.WPF.WPFDefaultDownloadHandler instance to show file chooser and select the path to store the file.
This is a solution
Défine your browser like variable :
BrowserView myBrowserView;
Browser myBrowser;
Create the browser properly :
this.myBrowser = BrowserFactory.Create();
this.myBrowserView = new WPFBrowserView(this.myBrowser);
Create event detection for download
this.myDowloadHandler = new SampleDownloadHandler();
this.myBrowser.DownloadHandler = myDowloadHandler;
Add it to a container, here, a grid
grid_navigateur.Children.Add((UIElement)myBrowserView.GetComponent());
Now we are going to use our "SampleDownloadHandler" class
class SampleDownloadHandler : DownloadHandler
{
public bool AllowDownload(DownloadItem download)
{
download.DestinationFile = "exemple\of\path\whith\file\name";
download.DownloadEvent += delegate(object sender, DownloadEventArgs e)
{
DownloadItem downloadItem = e.Item;
if (downloadItem.Completed)
{
System.Windows.MessageBox.Show("Download complete");
}
};
return true;
}
My personalisated class define path and name of the file who is download and pop a message when is over.
(to found the file name, you do to cut the string download.DestinationFile after the last )

XAML Image source has issues displaying a deep nested path

This is quite vexing.
I am working on an app for image management. Part of the value is the ability to store images in sub-folders based on image properties, eg. creation date.
If I store the image source in a shallow folder (app\images\img.jpg), everything works fine.
If I store the image in KnownFolders.Pictures\source\year\month\day\img.jpg, Image does not render. (Yes, that specific path won't work, I am trying to give you a sense of how the path is constructed)...
The file is actually there. The path is correct (I can open it in a browser, e.g.). The app has access to the file.
But it does not render the bitmap.
I tried to render the bitmap manually using
new BitmapImage(new Uri("KnownFolders.Pictures\source\year\month\day\img.jpg"),UriKind.Absolute))
That does not render anything. (Again, assume the path is valid and has a file at its bottom).
What Am I Missing?
The head scratcher: for GIF anims, I am using Thomas Levesque's useful component: https://github.com/XamlAnimatedGif. That one, unfortunately, does only render gifs... and it does so even when the path is the one given above. So the Standard IMAGE control does not render correctly, but Thomas's control does... infuriating.
An UWP app can't load a BitmapImage from an absolute URL to a file in a folder structure below the Pictures Library Folder.
So this won't work:
var relativePath = #"source\year\month\day\img.jpg";
var imageFile = await KnownFolders.PicturesLibrary.GetFileAsync(relativePath);
var bitmapImage = new BitmapImage(new Uri(imageFile.Path));
However, you could do this:
var relativePath= #"source\year\month\day\img.jpg";
var imageFile = await KnownFolders.PicturesLibrary.GetFileAsync(relativePath);
var bitmapImage = new BitmapImage();
using (var stream = await imageFile.OpenAsync(FileAccessMode.Read))
{
await bitmapImage.SetSourceAsync(stream);
}
So, after way too much time spent on this...
First, link to DataContextChanged of the IMAGE element. In there, parse the DataContext out. If you are using the IMAGE outside of an ItemsControl etc, this is not required...
private async void ImageView_DataContextChanged(FrameworkElement sender, DataContextChangedEventArgs args)
{
if (sender is Image)
{
Image img = (Image)sender;
if (img.DataContext is ImageView)
{
MyViewDataContext dc = (MyViewDataContext)img.DataContext;
img.Source = await dc.bitmap();
}
}
}
And here the implementation of MyViewDataContext.bitmap() which has a property called source that yields, you guessed it, absolute paths:
public async Task<BitmapImage> MyViewDataContext.bitmap()
{
if (_bitmap == null)
{
try
{
StorageFile file = await StorageFile.GetFileFromPathAsync(source);
bool r = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.CheckAccess(file);
if (r)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// create a new bitmap, coz the old one must be done for...
_bitmap = new BitmapImage();
// And get that bitmap sucked in from stream.
await _bitmap.SetSourceAsync(fileStream);
}
}
}
catch (Exception e)
{
_bitmap = null;
}
}
return _bitmap;
}
BitmapImage _bitmap;
I cache the resulting bitmap until I dispose of this MyViewDataContext.
I am now most concerned about memory. This one worries me:
How to dispose BitmapImage cache?
So, as a tech debt, I am going to address the potential mem leaks later, once this whole thing is on the test bench and I can take a look at its runtime behavior...
To access the folders and libraries represented by the properties of this class, specify the corresponding capabilities in your app manifest. For example, to access KnownFolders.PicturesLibrary, specify the Pictures Library capability in the app manifest.
Hope this will help
KnowFolders

Send bitmap parameter to another xaml page

In Windows Phone 8.1 , i have a ListView. My list is populated with an ObservableColection of Pictures. In class Pictures i have pictureName , and bitmapImage.
In ListView_Item_Click , i want to click a Picture and send it to another xaml page.
BitmapImage img = new BitmapImage();
img = ((Picture)e.ClickedItem).Image;//imi selectez imaginea care doresc!!
var image = new Image();
image.Source = img;
Frame.Navigate(typeof(Page2), image); in mainpage.xaml.cs
I wouldn't pass BitmapImage as a parameter of Frame.Navigate - it's not serializable and there will be a problem with SuspensionManager or Resuming/Suspending events.
The solution depends on your images - where to they come from - if it's a file, then you can just pass a path to that file and then in OnNavigated (for example), set the ImageSource from file.
Other method may be to set BitmapImage in target page, before it's navigated to - for example use static property:
public class TargetPage : Page, INotifyPropertyChanged
{
private static BitmapImage bmpImage;
public static BitmapImage BmpImage
{
get { return bmpImage; }
set { bmpImage = value; RaisePropertyChanged("BmpImage"); }
}
// rest of the code
Then you can just set the image before navigating:
TargetPage.BmpImage = img;
Frame.Navigate(typeof(TargetPage));
Also you should remember about Suspending and Resuming events and the case when your app is being terminated while it's Suspended. In every case you should somehow remember the source of the image - using SuspensionManager, PageState, Settings or other method.

Resources