0

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

ani
  • 181
  • 1
  • 2
  • 14
  • Don't you have to tell Java to `repaint`? – Steve May 22 '17 at 19:20
  • Tried it.Did not work – ani May 22 '17 at 19:24
  • Edit your question and show the code which initializes `jScrollPane1`, and also the code that adds it to your JFrame. – VGR May 22 '17 at 20:50
  • 1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Base your MSCVE / SSCCE on this [working example](https://stackoverflow.com/a/13463684/418556). – Andrew Thompson May 23 '17 at 01:09
  • @camickr...That question has the answer on how to add an image...Here i want to change the existing image – ani May 23 '17 at 06:30
  • ImageIcon icon = new ImageIcon(myPicture); Image image = icon.getImage(); Image newimg = image.getScaledInstance(180, 140, java.awt.Image.SCALE_SMOOTH); icon = new ImageIcon(newimg); jLabel4 = new JLabel( icon ); jLabel4.repaint(); jScrollPane1.setViewportView(jLabel4); //This solved my problem @camickr.Here my question was different – ani May 23 '17 at 07:03
  • @ani `That question has the answer on how to add an image...Here i want to change the existing image` - read the answer and comments. Also learn to read the API. There is no need to ask a question in the forum every time you have a little problem. – camickr May 23 '17 at 19:26

3 Answers3

2

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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

You need to call:

  • revalidate()
  • repaint()

See an explanation of why here Java Swing revalidate() vs repaint()

J.Kirk.
  • 943
  • 3
  • 12
  • 32
0

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.

Blasanka
  • 21,001
  • 12
  • 102
  • 104