The image cannot update other components (MVC)

2019-02-27 16:57发布

import java.awt.event.ActionListener;
import java.util.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.AdjustmentEvent;

I have several other frames (two are just punching numbers in, and another is also a scrollbar). I can use other components to update this view (this basically displays a box of image based on the temperature scale). Similarly, I can update other components from this view.

However (edited), the bar does move, but the image stays the same.... Can anyone see a bug? I appreciate any inputs into this/ Thank you!

1条回答
该账号已被封号
2楼-- · 2019-02-27 17:18

Because you're replacing the label, you need to remove() the component and validate() the Container. Alternatively, just replace the icon.

Addendum: I think the latter approach is preferable. Lacking your images and remaining code, let's start from this example: initialize the label and slider:

final JLabel label = new JLabel(pig);
final JSlider slider = new JSlider();

Then in the listener, use setIcon():

@Override
public void stateChanged(ChangeEvent e) {
    if (slider.getValue() < 50) {
        label.setIcon(pig);
    } else {
        label.setIcon(dog);
    }
}
查看更多
登录 后发表回答