[英]Java swing swapping ImagePanels in a ContentPane
I have a set of images that I want to present in a JFrame. 我有一组要在JFrame中呈现的图像。 They are all the same size - each image fills the JFrame. 它们的大小都相同-每个图像填充JFrame。 I swap between which is visible, layer style: 我在其中可见的图层样式之间交换:
f = new JFrame("xx");
f.setSize(480, 854);
contentPane = f.getContentPane();
ip1 = new ImagePanel(new File("assets/1.jpg"));
ip2 = new ImagePanel(new File("assets/2.jpg"));
ip3 = new ImagePanel(new File("assets/3.jpg"));
f.setVisible(true);
contentPane.add(ip1);
contentPane.addMouseListener(mouseListener);
An ImagePanel is: ImagePanel是:
public class ImagePanel extends JPanel {
private BufferedImage image;
@Override
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
public ImagePanel(File imageFile) {
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println("Image could not be read: " + imageFile);
}
setVisible(true);
}
}
And I try swapping between them in the MouseListener: 我尝试在MouseListener中在它们之间交换:
static MouseListener mouseListener = new MouseListener() {
private int i = 1;
@Override
public void mouseClicked(MouseEvent e) {
// logger.log(Level.INFO, e.toString());
contentPane.removeAll();
if (++i > 3) i = 1;
switch (i) {
case 1: contentPane.add(ip1); break;
case 2: contentPane.add(ip2); break;
case 3: contentPane.add(ip3); break;
}
contentPane.repaint();
}
};
The first image displays as desired. 根据需要显示第一张图像。 Click gives me white, and same on 2nd click, and third brings me back round to my first image as desired. 点击会给我带来白色,第二次点击会给我带来相同的效果,第三次点击让我回到所需的第一张图片。 If I click on the frame in between clicks on the white, the 2nd and 3rd images appear, and once rendered it works as expected. 如果我单击白色之间的两次单击之间的框架 ,则会显示第二张和第三张图像,并在渲染后按预期工作。 What am I missing? 我想念什么?
Ack, newbs! 阿克,新手! No doubt there is a much better way... 毫无疑问,还有更好的方法...
thanks 谢谢
将两个面板都放在CardLayout
。
put your Images
as Icon to the JLabel , 将您的Images
作为图标放置到JLabel上 ,
rulles for Swing GUI Swing GUI的规则
then you have to call 那你必须打电话
myLabel.setIcon(myIconn);
revalidate();
repaint();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.