I am trying to shuffle image from my folder image which I am able to do. what I have to pass the name of image but I don't want pass the name of image I just want to give the name of folder and all image should from there how can I do this
Here is my code
public class main1 extends javax.swing.JFrame {
private JLabel ecause = new JLabel();
private List<BufferedImage> list = new ArrayList<BufferedImage>();
private List<BufferedImage> shuffled;
private JLabel label = new JLabel();
private int width = 700;
private int height = 700;
private Timer timer = new Timer(4000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
public main1() {
this.getContentPane().setBackground(new java.awt.Color(153, 153, 0));
this.setUndecorated(true);
ecause.setText(" eCause List");
ecause.setBounds(0, 1278, 496, 88);
ecause.setFont(new java.awt.Font("Times New Roman", 1, 40));
ecause.setBackground(new java.awt.Color(255, 153, 0));
ecause.setOpaque(true);
this.add(ecause);
initComponents();
try {
list.add(resizeImage(ImageIO.read(new File("images\\Picture2.png"))));
list.add(resizeImage(ImageIO.read(new File("images\\Picture3.png"))));
list.add(resizeImage(ImageIO.read(new File("images\\Picture4.png"))));
list.add(resizeImage(ImageIO.read(new File("images\\Picture5.png"))));
} catch (IOException e) {
e.printStackTrace();
}
shuffled = new ArrayList<BufferedImage>(list);
Collections.shuffle(shuffled);
timer.start();
}
private BufferedImage resizeImage(BufferedImage originalImage) throws IOException {
BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
private void update() {
if (shuffled.isEmpty()) {
shuffled = new ArrayList<BufferedImage>(list);
Collections.shuffle(shuffled);
}
BufferedImage icon = shuffled.remove(0);
jLabel3.setIcon(new ImageIcon(icon));
}
}
How can I achieve my output?
You can list every file contained in the folder like this :
File[] files = new File("images/").listFiles();
Note that it will also give the subdirectories.
So instead of
list.add(resizeImage(ImageIO.read(new File("images\\Picture2.png"))));
list.add(resizeImage(ImageIO.read(new File("images\\Picture3.png"))));
list.add(resizeImage(ImageIO.read(new File("images\\Picture4.png"))));
list.add(resizeImage(ImageIO.read(new File("images\\Picture5.png"))));
You can simply loop over each files given by listFiles method. You could also use listFiles(FileFilter) in order to filter out each file that isn't an image.
I would add this as a comment but don't have the rep yet - doing
new File("images/myimage.png")
will not work if you package your code into a jar. To do this, you will need to use getResourceAsStream (http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html) and if your images folder is at your project root, you would do:
this.getClass().getResourceAsStream("/images")
The first slash here is important - it denotes the fact that you are going from the project root. If you just put "images", it would look from whatever class you put this code in (say you were in com.somepackage.blah, it would look in the blah package for your image).
Hope this helps!
Related
I've been following a tutorial to learn graphics and in one program the author uses images to make texture paints. I have copied his code however I dont know where to actually put the images for it to read. I have tried making a resources folder in eclipse and setting it as a source folder build path but this didnt work. The code is below:
EDIT:
Okay, I figured out that it is taking images from the source of the class. However, lets say I wanted to pull an image from my desktop, or some other location on my hard drive, how would i do this?
class Surface extends JPanel {
private BufferedImage slate;
private BufferedImage java;
private BufferedImage pane;
private TexturePaint slatetp;
private TexturePaint javatp;
private TexturePaint panetp;
public Surface() {
loadImages();
}
private void loadImages() {
try {
slate = ImageIO.read(new File("slate.png"));
java = ImageIO.read(new File("java.png"));
pane = ImageIO.read(new File("pane.png"));
} catch (IOException ex) {
Logger.getLogger(Surface.class.getName()).log(
Level.SEVERE, null, ex);
}
}
private void doDrawing(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));
g2d.setPaint(slatetp);
g2d.fillRect(10, 15, 90, 60);
g2d.setPaint(javatp);
g2d.fillRect(130, 15, 90, 60);
g2d.setPaint(panetp);
g2d.fillRect(250, 15, 90, 60);
g2d.dispose();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
}
This can be helpful. Or just use absolute PATH to file. linux: /home/user/... widndows: C:/Users/..
I have the following problems:
I don't know why my function, when displaying already rotated images, shows only one in as many jpanels as there were photos given.
Let me give an example: I load 4 images into hashmap. Then I put them into my rotate function and try to display them. I end up with 4 tabs of one rotated image.
When I'm trying to rotate twice using the same deegres as used previously (I'm using slider to take degrees) it doesn't rotate anymore but if I touch slider and move it, the function rotates normally.
I had no idea how to convert an Image type into File object thus I converted it into BufferedImage and then to File. I browsed through the Internet but could not find anything helpful.
My main's class piece of code:
JPanel panel_2e = new JPanel();
panel_2e.setOpaque(true);
panel_2e.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.GRAY, Color.DARK_GRAY), "Rotate options"));
panel_2e.setLayout(new BoxLayout(panel_2e,BoxLayout.Y_AXIS));
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 180);
slider.setMinorTickSpacing(10);
slider.setMajorTickSpacing(90);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setLabelTable(slider.createStandardLabels(45));
JPanel radio_buttons_rotate=new JPanel();
radio_buttons_rotate.setLayout(new BoxLayout(radio_buttons_rotate, BoxLayout.Y_AXIS));
JCheckBox cut_frame = new JCheckBox("Cut edges");
cut_frame.setSelected(true);
cut_frame.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{check = true;
System.out.println("Cut-edge mode selected");}
else
{check = false;
System.out.println("Cut-edge mode deselected");}
}
});
cut_frame.setBounds(78, 41, 60, 23);
radio_buttons_rotate.add(cut_frame);
JRadioButton black_rdbutton = new JRadioButton("Black background");
black_rdbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
black = true;
}
});
black_rdbutton.setBounds(78, 41, 60, 23);
radio_buttons_rotate.add(black_rdbutton);
JRadioButton white_rdbutton = new JRadioButton("White background");
white_rdbutton.setSelected(true);
white_rdbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
black = false;
}
});
white_rdbutton.setBounds(78, 41, 60, 23);
radio_buttons_rotate.add(white_rdbutton);
ButtonGroup group_frame_rotate = new ButtonGroup();
group_frame_rotate.add(black_rdbutton);
group_frame_rotate.add(white_rdbutton);
panel_2e.add(radio_buttons_rotate);
JLabel Rotate = new JLabel();
Rotate.setText(deg+"\u00b0");
panel_2e.add(slider);
JButton btnRotate = new JButton("Rotate");
JPanel RotatePanel=new JPanel();
RotatePanel.add(Rotate);
RotatePanel.add(btnRotate);
RotatePanel.setLayout(new FlowLayout());
btnRotate.setBounds(28, 158, 89, 23);
btnRotate.setBackground(Color.DARK_GRAY);
btnRotate.setForeground(Color.WHITE);
panel_2e.add(RotatePanel);
panel_2.add(panel_2e);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
deg=((JSlider) ce.getSource()).getValue();
Rotate.setText(deg+"\u00b0"); }
});
btnRotate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(AddDirectory.all_chosen.isEmpty())
{Object[] options = {"OK"};
int n = JOptionPane.showOptionDialog(frame,
"Please choose at least 1 image to rotate.","Empty work list",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);}
else
{RotateFunction rot = new RotateFunction(AddDirectory.all_chosen);
rot.main();
BufferedImage kk = null;
Display disp= new Display(); // invoke Display class
for(File i : all_chosen_images.values()){
try{
kk = ImageIO.read(new File(i.getAbsolutePath()));
disp.createFrame(center, i, kk); //create new frame with image
}
catch (IOException es){
es.printStackTrace();
}
}
}
}
});
And here is my rotate function:
public class RotateFunction{
HashMap<JButton,File> map;
Image spiral;
RotateFunction(HashMap<JButton,File> source_of_image)
{
map = AddDirectory.all_chosen;
}
public void main(){
int counter = 0;
if (spiral == null){
for(Map.Entry<JButton, File> entry: map.entrySet()) //////Moving through hashMap
{
try {
spiral = getImage(entry.getValue().getAbsolutePath());
counter++;
System.out.println("Path of image " + counter + " : " +entry.getValue().getAbsolutePath());
if (PhotoEdit.check == true){
rotateImage(PhotoEdit.deg, null);
System.out.println("Rotating image "+counter+" by "+PhotoEdit.deg+" degrees (edge cut)");
}
else{
rotateImage1(PhotoEdit.deg, null);
System.out.println("Rotating image "+counter+" by "+PhotoEdit.deg+" degrees (bigger frame)");
}
BufferedImage tmp = toBufferedImage(spiral);
File f;
f = new File( "image.png" );
try
{
ImageIO.write( tmp, "PNG", f );
}
catch ( IOException x )
{
// Complain if there was any problem writing
// the output file.
x.printStackTrace();
}
map.put(entry.getKey(), f);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PhotoEdit.all_chosen_images.clear();
PhotoEdit.all_chosen_images.putAll(map); //Putting HashMap with rotated images into global HashMap
System.out.println("Images have been successfully rotated");
}
}
public Image getImage(String path){
Image tempImage = null;
try
{
tempImage = Toolkit.getDefaultToolkit().getImage(path);
}
catch (Exception e)
{
System.out.println("An error occured - " + e.getMessage());
}
return tempImage;
}
////////////////////////////////////////////////////////////////////
///////////////////IMAGE ROTATION /////////////////////////////////
public void rotateImage(double degrees, ImageObserver o){
ImageIcon icon = new ImageIcon(this.spiral);
BufferedImage blankCanvas = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)blankCanvas.getGraphics();
g2.rotate(Math.toRadians(degrees), icon.getIconWidth()/2, icon.getIconHeight()/2);
g2.drawImage(this.spiral, 0, 0, o);
this.spiral = blankCanvas;
}
public void rotateImage1(double degrees, ImageObserver o){
double sin = Math.abs(Math.sin(Math.toRadians(degrees)));
double cos = Math.abs(Math.cos(Math.toRadians(degrees)));
ImageIcon icon = new ImageIcon(this.spiral);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
int neww = (int)Math.floor(w*cos+h*sin);
int newh = (int)Math.floor(h*cos+w*sin);
BufferedImage blankCanvas = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)blankCanvas.getGraphics();
g2.translate((neww-w)/2, (newh-h)/2);
g2.rotate(Math.toRadians(degrees), icon.getIconWidth()/2, icon.getIconHeight()/2);
g2.drawImage(this.spiral, 0, 0, o);
this.spiral = blankCanvas;
}
//////////////////////////////////////////////////////////////////////////
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
}
In the display function i have the following arguments - createFrame(JDekstopPane where_to_put_the_image, File img, BufferedImage image)
HashMap - all_chosen_images is the global HashMap storing all the images
Really hope for your help.
Aleksander
I am creating a GUI, and am fairly new to swing and awt. I am trying to create a gui that, upon launch, sets the background to an image, then uses a method to create a slideshow of sorts. I have attempted it, and I am not attached to the code so I am able to take both revisions and/or whole new concepts.
EDIT(9/15/13): I am having trouble with the slideshow, I cant seem to get it to work.
Here is my current code.
public class MainFrame extends JFrame{
JLabel backgroundL = null;
private JLabel bakckgroundL;
BufferedImage backimg;
Boolean busy;
double width;
double height;
public MainFrame() throws IOException {
initMainframe();
}
public void initMainframe() throws IOException {
//misc setup code, loads a default jpg as background
setTitle("Pemin's Aura");
busy = true;
String backgroundDir = "resources/frame/background.jpg";
backimg = ImageIO.read(new File(backgroundDir));
backgroundL = new JLabel(new ImageIcon(backimg));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
refreshframe();
setVisible(true);
busy = false;
}
public void adjSize() { // the attempted start of a fullscreen mode
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
width = this.getWidth();
height = this.getHeight();
setVisible(true);
}
public void setmastheadText() {//unfinished code
busy = true;
busy = false;
}
public void setbackground() {
add(backgroundL);
}
public void refreshframe() { //should refresh image?
setSize(2049, 2049);
setSize(2048, 2048);
}
public void loadingscreen() throws IOException, InterruptedException {
//this is the code in question that is faulty.
if (busy == false) {
busy = true;
String backgroundDir1 = "resources/frame/background.jpg";
String backgroundDir2 = "resources/frame/scr1.jpg";
String backgroundDir3 = "resources/frame/scr2.jpg";
BufferedImage backimg1 = ImageIO.read(new File(backgroundDir1));
BufferedImage backimg2 = ImageIO.read(new File(backgroundDir2));
BufferedImage backimg3 = ImageIO.read(new File(backgroundDir3));
backgroundL = new JLabel(new ImageIcon(backimg1));
Thread.sleep(2000);
setbackground();
setVisible(true);
backgroundL = new JLabel(new ImageIcon(backimg2));
setbackground();
setVisible(true);
Thread.sleep(2000);
bakckgroundL = new JLabel(new ImageIcon(backimg3));
setbackground();
setVisible(true);
if(backimg != null) {
backgroundL = new JLabel(new ImageIcon(backimg));;
}
}
busy = false;
}//end of loading screen
See ImageViewer for a working example of displaying images using a Swing based Timer.
See also How to use Swing Timers.
And while I'm here, another (prettier) example of animating an image. It uses this Mercator map of land masses. The image can be tiled horizontally, and therefore be scrolled left/right as needed.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;
public class WorldView {
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/P59NF.png");
final BufferedImage bi = ImageIO.read(url);
Runnable r = new Runnable() {
#Override
public void run() {
int width = 640;
int height = 316;
Graphics2D g = bi.createGraphics();
float[] floats = new float[]{0f, .4f, .55f, 1f};
Color[] colors = new Color[]{
new Color(20, 20, 20, 0),
new Color(0, 10, 20, 41),
new Color(0, 10, 20, 207),
new Color(0, 10, 20, 230),};
final LinearGradientPaint gp2 = new LinearGradientPaint(
new Point2D.Double(320f, 0f),
new Point2D.Double(0f, 0f),
floats,
colors,
MultipleGradientPaint.CycleMethod.REFLECT);
final BufferedImage canvas = new BufferedImage(
bi.getWidth(), bi.getHeight() + 60,
BufferedImage.TYPE_INT_RGB);
final JLabel animationLabel = new JLabel(new ImageIcon(canvas));
ActionListener animator = new ActionListener() {
int x = 0;
int y = 30;
#Override
public void actionPerformed(ActionEvent e) {
Graphics2D g = canvas.createGraphics();
g.setColor(new Color(55, 75, 125));
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
int offset = (x % bi.getWidth());
g.drawImage(bi, offset, y, null);
g.drawImage(bi, offset - bi.getWidth(), y, null);
g.setPaint(gp2);
g.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
g.dispose();
animationLabel.repaint();
x++;
}
};
Timer timer = new Timer(40, animator);
timer.start();
JOptionPane.showMessageDialog(null, animationLabel);
timer.stop();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Here is a version of that image with the equator added (it is 44 pixels 'south' of the center of the image).
You're calling Thread.sleep(...) and likely on the EDT or Swing event thread (full name is the Event Dispatch Thread). This thread is responsible for all Swing painting/drawing and user interactions, and so sleeping it will only serve to freeze your entire GUI. Instead you should use a Swing Timer to allow you to swap a JLabel's ImageIcon.
So, briefly:
Don't call Thread.sleep(...) on the Swing event thread (Event Dispatch Thread or EDT).
Do use a Swing Timer to do your repeating delayed actions.
Don't make and add many JLabels. Just make and add one.
Do Swap the ImageIcon that the JLabel displays by calling setIcon(...) on the label.
Better (cleaner) to write if (busy == false) { as if (!busy) {
e.g.,
ImageIcon[] icons = {...}; // filled up with your ImageIcons
if (!busy) {
int timerDelay = 2000;
new Timer(timerDelay, new ActionListener() {
private int i = 0;
public void actionPerfomed(ActionEvent e) {
myLabel.setIcon(icons(i));
i++;
if (i == icons.length) {
((Timer)e.getSource).stop();
}
};
}).start();
}
Currently i m making a java program using netbeans based on changing image in a button....
Actually my requirement is to change the Image icon of a button as i click another button (Say A).....
i came out with the following program........
// Following function is included inside the button's (Here A) ActionListener........
public void change_image()
{
if(sex==0)
{
ic=new ImageIcon("E:\\java_images\\female_profile.jpg");
sex=1;
}
else if(sex==1)
{
ic = new ImageIcon("E:\\java_images\\male_profile.png");
sex=0;
}
// To resize the image into the size of the button...
labelicon.setImage(ic.getImage().getScaledInstance(image_btn.getWidth(),image_btn.getHeight(), Image.SCALE_DEFAULT));
img_btn.setIcon(labelicon);
}
The Variables i've included are
private int sex; // 0 - female, 1 - male
private ImageIcon ic,labelicon; // variables meant for storing ImageIcons.....
private JButton img_btn; // the button at which the image is to be displayed....
Now the Weird Behaviour i observed is.......
The image gets displayed on the button click, only when i click the minimize button.
i.e when the i click the button A, the code specified in the ActionListener is getting executed. But the effect of the image change appears only when i minimize the window and again make it appear on the screen.... Can anyone tell why this is occuring and how can i remove the problem ??
All i want is to change the image the moment i click the A Button.....
Well..i haven't included for the code for creating button since they are easily done by netbeans swing GUI builder......
load Icon / ImageIcon as local variable once time, there no reason to re_loading image from ActionListener
in the API is description that Image#ScaledInstance is pretty asynchronous
otherwise you have to call
.
labelicon.getImage().flush();
img_btn.setIcon(labelicon);
EDIT
#akp wrote but..how would you resize the icon image..??
there are two or three another ways how to put Icon /ImageIcon and will be resiziable with its parent, JLabelcould be easiest of ways
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class JButtonAndIcon {
private static JLabel label = new JLabel();
private static Random random = new Random();
private static ImageIcon image1; // returns null don't worry about
private static ImageIcon image2; // returns null don't worry about
private static Timer backTtimer;
private static int HEIGHT = 300, WEIGHT = 200;
public static void main(String[] args) throws IOException {
label.setPreferredSize(new Dimension(HEIGHT, WEIGHT));
final JButton button = new JButton("Push");
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setLayout(new BorderLayout());
button.add(label);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button.getIcon() == image1) {
label.setIcon(image2);
} else {
label.setIcon(image1);
}
}
});
JFrame frame = new JFrame("Test");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
startBackground();
frame.setVisible(true);
}
private static void startBackground() {
backTtimer = new javax.swing.Timer(750, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private static Action updateBackground() {
return new AbstractAction("Background action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
public static BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}
The problem here is that you are updating the internals of an Icon. The setIcon method will think that it's the same icon that the button already has. I would recommend you to do two different Icon objects that to use to update the icon with. That will fix the problems.
Example (with two different icons):
public static void main(String[] args) throws IOException {
final ImageIcon redIcon = createImageIcon(10, 10, Color.RED);
final ImageIcon blueIcon = createImageIcon(10, 10, Color.BLUE);
final JButton button = new JButton("Push", blueIcon);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (button.getIcon() == redIcon)
button.setIcon(blueIcon);
else
button.setIcon(redIcon);
}
});
JFrame frame = new JFrame("Test");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private static ImageIcon createImageIcon(int w, int h, Color color) {
Image image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
g.setColor(color);
g.fillRect(0, 0, w, h);
g.dispose();
return new ImageIcon(image);
}
Background:
Looking at the source of AbstractButton.setIcon, you can see that it won't know about the update if the reference "isn't updated":
.....
if (defaultIcon != oldValue) {
if (defaultIcon == null || oldValue == null ||
defaultIcon.getIconWidth() != oldValue.getIconWidth() ||
defaultIcon.getIconHeight() != oldValue.getIconHeight()) {
revalidate();
}
repaint();
}
Note to #HarryJoy, you actually had a point even though you didn't know why... :) Sorry! +1 again!
//Call img_btn.revalidate() and img_btn.repaint()
Correction, setIcon should already do this. I use the hacky way of img_btn.setText("<HTML><BODY><IMG SRC=\"/path/to/img.jpg\"/></BODY</HTML>"); personally.
I'm attempting to display an image that was downloaded from a website, with the use of setIcon and a jLabel
jLabel5.setIcon(new ImageIcon("image.png"));
At the start of the program, the image doesn't exist, it gets downloaded, and after that displayed, with no problems. But if it changes, even if it downloads a newer version of the image, it will display the old one, as if it had a cache of it or something.
Does someone know why this happens? How to get a workaround with or without this method?
I have also tried to do the following to see if it could help, with no success:
jLabel5.setIcon(null);
jLabel5.setIcon(new ImageIcon("image.png"));
It would display nothing and then the same old image again.
it will display the old one, as if it had a cache of it or something.
Yep, caching is the problem. Here are a couple of options:
// This works using ImageIO
imageLabel.setIcon( new ImageIcon(ImageIO.read( new File(imageName) ) ) );
// Or you can flush the image
ImageIcon icon = new ImageIcon(imageName);
icon.getImage().flush();
imageLabel.setIcon( icon );
Have you tried to use the SwingUtilities.invokeLater() method, similar to this:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//JLabel myLabel = new JLabel("Old Text");
jLabel5.setIcon(new ImageIcon("image.png"));
}
});
Taken from here.
If the problem is about caching, try downloading the image with a query string. For example, http://abc.co.th/image.png?t=149534274 The number is obtained from System.currentTimeMillis()
for example
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.*;
public class LabelsIcon extends JFrame implements Runnable {
private static final long serialVersionUID = 1L;
private JLabel label = new JLabel();
private Random random = new Random();
private boolean runProcess = true;
public LabelsIcon() {
label.setLayout(new BorderLayout());
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));
add(label, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
new Thread(this).start();
}
#Override
public void run() {
while (runProcess) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
label.setIcon(new ImageIcon(getImage()));
}
});
try {
Thread.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
LabelsIcon t = new LabelsIcon();
}
});
}
}