Java swing在ContentPane中交换ImagePanels

时间:2011-10-23 10:11:30

标签: java swing jframe repaint

我想要在JFrame中呈现一组图像。它们都是相同的大小 - 每个图像填充JFrame。我交换的是哪个是可见的,图层样式:

    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);

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);
    }
}

我尝试在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();
    }
};

根据需要显示第一张图像。点击给我白色,第二次点击同样,第三次让我回到我想要的第一张图片。如果我在白色点击之间单击框架,则会显示第2个和第3个图像,并且一旦渲染它就会按预期工作。我错过了什么?

Ack,newbs!毫无疑问,有更好的方法......

感谢

2 个答案:

答案 0 :(得分:4)

将两个面板放在CardLayout

答案 1 :(得分:4)

Images Icon作为JLabel

Swing GUI的rulles

  • JComponent(s)已经可见
  • 你想在这个/这些对象之间交换

然后你必须打电话

myLabel.setIcon(myIconn);
revalidate();
repaint();