How to dynamically change JFrame background? - java

I have small problem with changing JFrame background image. First I've added background image with JLabel and application is working good. But now I need to change it dynamically.
I've tried this code :
label = new JLabel(new ImageIcon(Toolkit.getDefaultToo... // old background image
public void changeImage(){
label.setVisible(false);
label2 = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource("weatherall.gif"))));
setContentPane(label2); // new Background image
label2.setVisible(true);
repaint();
}
switch (cmb.getSelectedItem().toString()) {
case "ISTANBUL":
x = 0;
changeImage();
//some codes......vs.vs.
break;
Also I'v tried it with timer (TimerTask) every 1 sec. Refreshing frame
Anybody have an idea about this?

Now we need to create JLabel and set it size like background(stretch it) after that just add image into the JLabel and when u want to change it just change the image from same JLabel don't try adding another JLabel,it's not working!!...thats it.
JLabel label = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().getImage(getClass().getResource(localweather))));
setContentPane(label);//when u want to change background image just replace 'localweather' another image.

Related

Java Swing Icon not appearing

I'm trying to create a piece of code that displays either a smiley face or a sad face when a button is pressed, depending on some value, but it just won't display the image. I know that it's definitely getting past the if/else statements, so I really don't know what is going wrong.
try {
if(data[2] <= ((int) ChronoUnit.DAYS.between(localDate, RTS()))*MnHrs())
{
JLabel lblSmiley = new JLabel(new ImageIcon("C:\\. . .\\smileyface.jpeg"));
panel.add(lblSmiley);
}
else
{
JLabel lblSmiley = new JLabel(new ImageIcon("C:\\ . . . \\sadeface.png));
panel.add(lblSmiley);
}
} catch (Exception e1) {
e1.printStackTrace();
}
It looks like you're loading the icon and adding a new label each time. Instead, you can add the label once and call setIcon() like they show here.
Icon smile = new ImageIcon("C:\\…\\smileyface.jpeg");
Icon sad = new ImageIcon("C:\\…\\sadeface.png");
JLabel lblSmiley = new JLabel();
…
frame.add(lblSmiley);
…
if (…) {
lblSmiley.setIcon(smile);
} else {
lblSmiley.setIcon(sad);
}
Depending on your layout, you may need to change the labels preferred size or add an empty label before you pack() the window.
Probably, it is getting in the panel, but due to dimensions of panel it might be getting placed off screen. Check by modifying the panel dimensions and placing the smiley within that.

Unable to change image in jScrollPane upon clicking next [duplicate]

This question already has an answer here:
Not able to add image in jscrollpane inside a jframe
(1 answer)
Closed 5 years ago.
I'm making a jframe where i'm adding an image that will change as i click next.I have written a code but it doesn't work.Here is the code:
i++;
ImageIcon icon = new ImageIcon(mean.get(0));
Image image = icon.getImage(); // transform it
Image newimg = image.getScaledInstance(180, 140, java.awt.Image.SCALE_SMOOTH); // scale it the smooth way
icon = new ImageIcon(newimg);
JLabel label = new JLabel( icon );
jScrollPane1= new JScrollPane( label );
Please help
The problem lies with:
jScrollPane1= new JScrollPane( label );
The field jScrollPane whose object was placed in the JFrame is set to another JScrollPane, whose object is not added in the GUI.
Store the original label in a field, say jLabel1 and set that label.
A repaint might be needed.
You need to call:
revalidate()
repaint()
See an explanation of why here Java Swing revalidate() vs repaint()
Add this to end of your code jScrollPane1. If haven't JFrame created already create one like below then add that jScrollPane1 to JFrame.
JFrame frame = new JFrame();
frame.add(jScrollPane1, BorderLayout.CENTER);
There is also set the layout as BorderLayout but you can try other layouts or without adding layout also.

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 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.

Java - delete an ImageIcon?

Is there any way to easily delete an ImageIcon completely from the screen? I can't find one anywhere.
ImageIcon image = new ImageIcon("candle.gif");
image.paintIcon(this, g, 150, 80)
For example, if I wanted to get rid of "image" later on when a button is pressed, what would be the appropriate code? (Not for the button, I know how to do that).
Don't reinvent the wheel. The easiest way to paint an Icon is to use a JLabel. The code would be something like:
ImageIcon icon = new ImageIcon(...);
JLabel label = new JLabel( icon );
panel.add( label );
If you don't want to display the icon anymore then in the ActionListener of your button you simple do:
label.setIcon( null );

Categories