Display a set of images inside Netbeans JFrame - java

I know how to display the images in separate JFrames.
public static void displayImage(BufferedImage img) {
JFrame f = new JFrame();
f.add(new JLabel(new ImageIcon(img)));
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
But I want a method to display all the images in a single JFrame(or in a suitable element), So I can shift between the images using two buttons("Next" and "Previous").

actually you don't need a multiple frame for this.you don't need even multiple jpanels .just a single jlable is sufficient .
all you need to do is change image of jlable when button press .
1) put your images in a directory and give a name .names should have pattern
example
C:\Users\Madhawa.se\Desktop\images\i1.jpg
C:\Users\Madhawa.se\Desktop\images\i2.jpg
C:\Users\Madhawa.se\Desktop\images\i3.jpg
C:\Users\Madhawa.se\Desktop\images\i4.jpg
C:\Users\Madhawa.se\Desktop\images\i5.jpg
2) declare a int variable as global
int i=0;
3) increase i by one when click next button and add appropriate image to label
i++;
ImageIcon imgThisImg = new ImageIcon("C:\\Users\\Madhawa.se\\Desktop\\images\\i"+i+".jpg");
jLabel1.setIcon(imgThisImg);
4) decrease i by one when click previous button and add appropriate image to label
i--;
ImageIcon imgThisImg = new ImageIcon("C:\\Users\\Madhawa.se\\Desktop\\images\\i"+i+".jpg");
jLabel1.setIcon(imgThisImg);
you can declare also String array which holds image paths .if your image names want to be arbitrary names .and then you can get image same way.
and also you should have a logic to correctly cycle images.you should restrict i to image quantity .otherwise image doesn't exist for i after i exceeded
output>>

Related

JLabel containing an ImageIcon won't repaint

I'm writing an application that creates a deck of cards in a random order and when a button is pressed moves the top card to the bottom and shows the new top card. (It's to simulate a Planechase deck to those familiar with Magic: the Gathering.) When the button is pressed it is properly cycling through the image files, but when I assign an image to a JLabel with an ImageIcon I can't get the JLabel to refresh with the new image. Here's the code I'm using to refresh
nextCardButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
planechase.topCardIncrement();
createCardToDisplay();
}
});
planechase is an instance of a class CardDeck which stores the randomized deck and has several methods to shuffle, change cards, etc. topCardIncrement() changes the top card to the next in the list.
private void createCardToDisplay()
{
cardToDisplay = new JLabel(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
}
createCardToDisplay assigns cardToDisplay to an image derived from the folder name of the images and the current file. cardToDisplay is placed within JPanel contentPanel which is placed within JFrame frame. I can't figure out the proper way to repaint/revalidate (I'm not quite clear on what the difference is) my GUI to reflect the updated image. I've confirmed via System.out.println calls that
planechase.getFolderName() + "\\" + planechase.displayTopCard()
is updating as it should, so I assume that the JLabel is being reassigned properly. What is the proper way to redraw this so that it reflects the new ImageIcon?
The code is ambiguous...
The first thing that jumps out at me is...
private void createCardToDisplay()
{
cardToDisplay = new JLabel(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
}
This is creating a new instance of cardToDisplay, but is it been added anywhere? Is the previous instance been removed? There's no context to be certain.
Normally, when you want to change the icon of a JLabel, you would simply call setIcon on the instance of the JLabel...
cardToDisplay.setIcon(new ImageIcon(planechase.getFolderName() + "\\" + planechase.displayTopCard()));
Because this is a bound field, it will trigger a repaint request automatically.

Java: How to nest JPanel in a GridLayout?

I want to know how to nest JPanels using a GridLayout. This is how it should look like.
I approached this problem by 2 ways so far,
using JPanels and
using JLabels,
and none of them worked (only the first panel created is shown).
Here is the code for the JPanel approach:
int x=20, y=20;
JPanel [] panels = new JPanel[3];
JLabel animal = new JLabel(new ImageIcon(getClass().getResource("Pictures/animal.gif")));
JLabel map = new JLabel(new ImageIcon(getClass().getResource("Pictures/map.gif")));
JLabel mountain = new JLabel(new ImageIcon(getClass().getResource("Pictures/mountain.gif")));
for(int i=0;i<panels.length;i++)
{
if(i>0)
{
x+=x;
y+=y;
}
panels[i] = new JPanel(new GridLayout(2,2));
panels[i].setPreferredSize(new Dimension(x,y));
if(i==0)
panels[i].add(new JPanel());
else
panels[i].add(panels[i-1]);
panels[i].add(mountain);
panels[i].add(map);
panels[i].add(animal);
}
add(panels[2]);
One option is to create a class that will represent a panel divided into the grid with the images. The only issue would be the top left quadrant which would usually contain the nested panel, at some point you want this to contain just a blank panel. So maybe something like this (barring various optimizations):
class GridPanel extends JPanel{
JLabel mountain, map, animal;
public GridPanel(JPanel panel){
super();
setLayout(new GridLayout(2, 2));
animal = new JLabel(new ImageIcon(getClass().getResource("pictures/animal.gif")));
map = new JLabel(new ImageIcon(getClass().getResource("pictures/map.gif")));
mountain = new JLabel(new ImageIcon(getClass().getResource("pictures/mountain.gif")));
add(panel);
add(mountain);
add(map);
add(animal);
}
}
Notice that it accepts the panel that is to be displayed in the top left corner of the grid. This coud then be called with the panel specified. So at the point where you want to create the main panel:
JPanel grid = new GridPanel(new JPanel()); //initial
for(int i = 1; i <= 5; i++){
grid = new GridPanel(grid);
}
add(grid);
The initial grid is created with a blank JPanel. And every subsequent grid will contain the previous one as the top left panel. You have to resize your images and such and maybe even avoid loading the images multiple times etc. But that is another question. This example shows 5 nested panels.
Just to be clear, you should use ImageIO to load the images once and reuse the images. For example You can create a BufferedImage like this in your main class:
BufferedImage mointainImg = ImageIO.read(new File("pictures/mountain.gif"));
And when you want to create the JLabel you can do this:
mountain = new JLabel(new ImageIcon(mountainImg));
And the advantage is that you can manipulate the image a bit if you want.
One issue that you have is that the images are not scaled. To scale images, use Image.getScaledInstance(). Proper scaling would at least fix the problem of the visible images being cut off. It also might cause the other images to be shown as they might just be hiding behind the visible images because they are too big.

displaying images from an array in a gui window using swing in java

I am developing a program that will populate an array with 52 images of cards from a file. I would like to display these images in a gui window. This is for a program that will select five random card images and display them in a gui window. So, right now, i am trying to develop the part of the code which will display images from an array in a window and i am at a loss as to how to display png images in a jframe. This is the code i have so far. I used a system.out.println statement so i know that the array of 52 card images is populating correctly, however, i do not know how to display them properly in a window.
String[] cardsArray = new String[52];
for (int i = 0; i < 52; i++)
{
cardsArray[i] = "C:\\Users\\mike\\Documents\\NetBeansProjects\\card shuffler\\cards\\\"+String.valueOf(i+1)+".png";
}
System.out.println(Arrays.toString(cardsArray));
additional note. I have to use a jframe to display the results in a side by side layout. I thought to use flowLayout to accomplish this, but, i a not sure how to pass in an array of images. I have no problem doing it with a single image from a file. I am using the code below as a guide.
JFrame myJFrame = new JFrame();
// create and assign a FlowLayout for myFrame
myJFrame.setLayout(new FlowLayout());
// Create a label with an image icon
JLabel jlCSCI = new JLabel(new ImageIcon("CSCI.jpg"));
// add the Label to the frame
myJFrame.add(jlCSCI); // Add thelabel to MyGridLayout
// set the title, size, location and exit behavior for the frame
myJFrame.setTitle("ImageIcon Demo");
myJFrame.setSize(240, 200);
myJFrame.setLocation(200, 100);
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// make the frame visible (activate the GUI frame)
myJFrame.setVisible(true);
I am not sure how to develop the statement that would utilize an array that i created within the program.
Maybe like this?
for (String imgName : cardsArray)
{
myJFrame.add(new JLabel(new ImageIcon(imgName)));
}
Hope this helps.
EDIT:
I simply added a JLabel with an Icon to the frame. The ImageIcon class is just an implementation of the Icon interface and it creates an icon by reading an image from file. Creating a JLabel with an Icon will display the icon instead of the text. You can also combine the text and the icon. For more info, check the documentation.

Displaying a JLabel on top of another JLabel

I have the following code:
try {
File file_background = new File(
"C:\\Users\\xxxx\\Desktop\\background.png");
ImageIcon icon_background = new ImageIcon(
ImageIO.read(file_background));
JLabel background = new JLabel(icon_background);
window.setContentPane(background);
File file_car = new File(
"C:\\Users\\xxxxxx\\Desktop\\car.png");
ImageIcon icon_car = new ImageIcon(ImageIO.read(file_car));
JLabel car = new JLabel(icon_car);
car.setVisible(true);
background.add(car);
// TODO Get car showing on top of the background label
} catch (IOException e) {
e.printStackTrace();
}
Where I'm attempting to have the car label show on TOP of the background label. But I'm only getting the background JLabel showing. I'm new to SWING so any suggestions to what steps I'm missing would be great.
..I want to move it a later stage. But right now I want it to show first :)
There are two ways,
1st.
Put JLabel car to JPanel, drawing an Image by using paintComponent, instead of JLabel background (advantage JPanel is container with proper notifications for LayoutManager).
Put JLabel car to JLabel background, but JLabel haven't implemented any LayoutManager, have to set desired.
Advantage all images in JLabel are static, with zero CPU and GPU inpact ad consumption in compare with paintComponent.
Disadvantage JLabel isn't container and with proper notifications for LayoutManager, required a few code lones moreover in compare with JLabel placed in JPanel, for movement (AbsoluteLayout) is quite good solution.
2nd.
Draw both Images by using BufferedImage and Graphics.
Add them both to a JPanel that uses OverlayLayout. It is not ok to add a JLabel to another JLabel.
This code has not gone through a compiler so take it for what it is :)
JPanel panel = new JPanel(new OverlayLayout());
panel.add(background);
panel.add(car);
Works.. Added the following to make it display:
car.setBounds(200, 200, 200, 200);
Apparently it's because by default a null layout manager is used. So setting the bounds of the label will enable it to display since the default size is 0.

How to print content of a label in java?

I have created a label and added an image to it using the seticon property.
Now I want to print that image but I am unable to do so.
I tried with .print(Graphics g) method but I dont know what is that graphics??
If someone can help me in printing the label, I would be really grateful to you.
Thanks
You don't need to print anything explicitly just try following
ImageIcon ii=new ImageIcon("PATH_TO_IMAGE_FILE");
//Create a label with your image file
JLabel label=new JLabel(ii);
//Create a window using JFrame with title ( Put image on JLabel )
JFrame frame=new JFrame("Put image on JLabel");
//Add created label into JFrame
frame.add(label);
Update as per your clarification :
Follow this , and pass label.getGraphics() to printAll() method
You should implenent Printable interface
see for example here

Categories