Display image based on GUI selection after converting to .jar - java

I created a GUI program in Java, and I have a class with a method and switch statement that'll display an image in a new JFrame depending on the button that is clicked. The code in general is clunky and doesn't have any error-handling (I initially did it for an assignment and I'm building on it myself now), but I wanted to know if there's any way to load the images without hard coding their location. Right now, the images are in the root directory so NetBeans can access it without hard coding, but is there any way to have it display the images once I convert it to a .jar file without hard coding the file location, especially since I want to be able to use it on different computers? I've included the method below.
Thanks!
/* method to display images of 3D shapes using switch cases and a new JFrame
depending on which shape button is selected */
public void displayOutput(int x) {
JFrame f = new JFrame();
f.setBounds(200, 200, 850, 600);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationRelativeTo(null);
ImageIcon icon = new ImageIcon("");
switch(x) {
case 1:
icon = new ImageIcon("sphere.png");
break;
case 2:
icon = new ImageIcon("cube.jpg");
break;
case 3:
icon = new ImageIcon("cone.png");
break;
case 4:
icon = new ImageIcon("cylinder.png");
break;
case 5:
icon = new ImageIcon("torus.png");
break;
}
JLabel image = new JLabel(icon);
f.add(image);
f.setVisible(true);
}

You could embed the images inside the JAR file. Put them inside the source root folder (If it is maven/gradle project, the location would be src/main/resources/images where images folder will be copied to your JAR file on build), then load them like this:
var resourceURL = Thread.currentThread().getContextClassLoader().getResource("/images/sphere.png");
var imageIcon = new ImageIcon(resourceURL);

Related

How to change a code of putting image within a label from desktop to project file

So I have this code It's work when the image at my desktop, I added the image at src file put I couldn't convert it can you tell me what is the problem? this the code it set the image to fit the label too:
public void ScalImage() {
ImageIcon image = new ImageIcon("C:\\Users\\HP\\Desktop\\ath3.png");
Image img = image.getImage();
Image imgScale = img.getScaledInstance(jLabel2.getWidth(), jLabel2.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaliedicon = new ImageIcon(imgScale);
jLabel2.setIcon(scaliedicon);
}
I tried to say: ImageIcon image = new ImageIcon("ath3.png");
didn't work
So I have solved it I wrote like that
ImageIcon image = new ImageIcon(getClass().getResource("ath3.png"));
It's work for me. I wish I'm right

Display image on a Java button

xstButton.setIcon(new ImageIcon("D://icon-tender-check-press.png"));
I am using this line of code to display an image on a Java button.
I cannot see the desired image on the button, need help!!!
You could try it like this:
Image image = ImageIO.read(getClass().getResource("D://icon-tender-check-press.png"));
button.setIcon(new ImageIcon(image));
But i would suggest to create a Folder in your project to store images:
Image image = ImageIO.read(getClass().getResource("images/icon-tender-check-press.png"));
button.setIcon(new ImageIcon(image));
Although i am not exactly sure what your question is
Probably file "D://icon-tender-check-press.png" doesn't exists or is not a valid image.
Check it exists first.
File f = new File("D://icon-tender-check-press.png");
if(f.exists() && !f.isDirectory()) {
System.out.println("File exists");
}

java jLabel image does not update

I'm creating a feedback label that displays the picture that the user has chosen in a file dialog.
The moment when a picture file is selected, the label will update itself into that image of which the user has clicked.
The first time when the picture is chosen it works fine, however when another picture is chosen for the 2nd time onwards, it remains as the first picture.
Codes:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//browse button
FileDialog fd = new FileDialog(this, "Choose a file", FileDialog.LOAD);
fd.setDirectory("C:\\");
fd.setFile("*.jpg"); // jpg files only
fd.setVisible(true);
String filename = fd.getFile();
if (filename == null) {
System.out.println("You cancelled the choice");
} else {
savePicture("temp"); // save it in temp.jpg. This overwrites any existing picture.
ImageIcon imgThisImg = null;
imgThisImg = new ImageIcon(absfilePath+ "/temp.jpg");
jLabel7.setIcon(null);
jLabel7.setIcon(imgThisImg);
jLabel7.revalidate();
jLabel7.repaint();
}
During debugging, the moment after savePicture() function is executed, the directory picture is updated. Therefore it's not an issue with overwritting the file. The file is overwritten correctly, why does it still display the previous image? Is there a cache or something that i need to clear?
Thanks.
Using ImageIO to the read file works best. Can be achieved using the following line.
jLabel7.setIcon(new JLabel(new ImageIcon(ImageIO.read(new File("C:\\Users\\Cameron Gillespie\\Documents\\NetBeansProjects\\OnlineCabsClient\\src\\images\\taxiBackground.png")))));
You are taking the label then setting the icon. Creating a new label and ImageIcon. Then using ImageIO to read the file. Reading the image and printing it to the label.

updating JLabel image, dynamic via selection

So basically im creating a GUI that allows the user to select a file, this file is check to be a .wav file. Then this file's data is graphed through JFreechart.
This graph or image created by Jfreechart i want to put into the JFrame.
The problem is that the code:
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
must be created & declared in the method where i create the JFrame ( must be added to the frame )
thus i cannot dynamically update the image to new created graphs, depending on what file the user selects. ( on selection of a new file, via button a new graph image is created )
is there a way to force
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
to update to the new image ( in the same direcotry, with the same name )
or is there a way using Mapping to set the image name ("blah.jpg") dynamically with a counter?
here is my SSCCE
public class gui extends JFrame {
ImageIcon myIcon1 = new ImageIcon("C:/location/chart1.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
gui() {
// create Pane + contents & listeners...
JPanel content = new JPanel();
JPanel southContent = new JPanel();
content.setLayout(new FlowLayout());
content.add(open_File);
// Jfreechart graph image -- not visible until selected
graphLabel1.setVisible(false);
// this is the graph image being added to the panel
southContent.add(graphLabel1);
southContent.setLayout(new FlowLayout());
// add action listeners to buttons
open_File.addActionListener(new OpenAction());
// set Pane allignments & size...
this.setContentPane(content);
this.add(southContent, BorderLayout.SOUTH);
this.setTitle("Count Words");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1100, 720);
this.setLocationRelativeTo(null);
}
// opening selected file directory.
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
/// gets user selection ( file ) and procesess .wav data into array
/// loops through array creating X series for JfreeChart
// Add the series "series" to data set "dataset"
dataset.addSeries(series);
// create the graph
JFreeChart chart = ChartFactory.createXYLineChart(
".Wav files", // Graph Title
"Bytes", // X axis name
"Frequency", // Y axis name
dataset, // Dataset
PlotOrientation.VERTICAL, // Plot orientation
true, // Show Legend
true, // tooltips
false // generate URLs?
);
try {
ChartUtilities.saveChartAsJPEG(
new File("C:/location/chart1.jpg"), chart, 1000, 600);
} catch (IOException e) {
System.err.println("Error occured: " + e + "");
}
// !!!!! this is where i need to set the ImageIcon added to the
// panel in "gui" to this new created Graph image ("chart1.jpg")
// as above
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// sets the image label itself to visible as a new image has been
// added ot it
graphLabel1.setVisible(true);
}
}
}
Just add the JLabel to its container as you usually do. Then, once you created the image and you have an instance of an ImageIcon, just call the setIcon() method for the JLabel.
Using something like this should allow displaying both images of the waveform, as well as new images of the waveform.
try {
//ChartUtilities.saveChartAsJPEG(
// new File("C:/location/chart1.jpg"), chart, 1000, 600);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChartUtilities.saveChartAsPNG(baos, chart, 1000, 600);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BufferedImage image = ImageIO.read(bais);
// !!!!! this is where we need to set the ImageIcon..
graphLabel1.setIcon(new ImageIcon(image));
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error occured: " + e + "");
}
OTOH you might look to increasing the memory size and generate the entire waveform in one pass, then display the label in a scroll pane.
Thanks to Dan and Andrew Thompson, i have a working product.
I used a counting variable to count teach time the "OpenAction" button was selected.
i then used this variable to make dynamic names for each image i created through JFreechart.
Thus i used .setIcon to reset the icon image to each new created image with a new name.
.setIcon does not seem to work if you are trying to reset the label to a Image icon that has the same name as the previously selected Image icon.
the finished code segment looks like:
ImageIcon myIcon1 = new ImageIcon("C:/location/chart"+CounterVariable+".png");
graphLabel1.setIcon(myIcon1);
for example this will create charts;
chart1
chart2
chart3
and so forth.

Issue regarding dynamically loading Images in loop using Java Swing

public String[] imagesArray = {Images.firstImage, Images.secondImage};
String imagesPath = "/testproject/images/";
for(int i = 0; i<imagesArray.length; i++) {
URL imageURL = this.getClass().getResource(imagesPath+imagesArray[i]);
ImageIcon orignalImageIcon = new ImageIcon(imageURL);
Image newImage = orignalImageIcon.getImage().getScaledInstance(100, 90, java.awt.Image.SCALE_SMOOTH);
ImageIcon newImageIcon = new ImageIcon(newImage);
JButton receiptButton = new JButton(newImageIcon);
receiptButton.setBorder((new EmptyBorder(0,0,0,0)));
toolBar.add(receiptButton);
add(toolBar);
}
Images not shown in my design layout?
The problem is most likely the asynchronous loading nature of using an ImageIcon to load the original images.
If that is the problem:
There is an easy way to test it. Add the orignalImageIcon to the button and see if they all appear.
There is an easy way to fix it. Load the images using ImageIO.read(URL) - a method that will block until the image is completely loaded.

Categories