Java如何在布局中添加图像作为背景

Java如何在布局中添加图像作为背景,java,swing,jpanel,paintcomponent,cardlayout,Java,Swing,Jpanel,Paintcomponent,Cardlayout,我有一个使用CardLayout的类,它有两张卡片,上面有一个按钮。我希望能够做的是放置一个像背景一样的图像,比如Windows中的桌面背景。该计划最终将有几个不同的卡,我希望能够把每个卡不同的背景。我尝试过在这个网站上的其他类似问题中提出的许多建议,以及通过谷歌搜索可以找到的任何建议,但我似乎无法让它发挥作用。我知道用CardLayout我不能把面板放在面板的顶部,所以把图像放在JPanel上是行不通的。因此,我的问题是,根据下面发布的代码,是否有更好的方法来设置布局,使其更好地工作,以及如何

我有一个使用CardLayout的类,它有两张卡片,上面有一个按钮。我希望能够做的是放置一个像背景一样的图像,比如Windows中的桌面背景。该计划最终将有几个不同的卡,我希望能够把每个卡不同的背景。我尝试过在这个网站上的其他类似问题中提出的许多建议,以及通过谷歌搜索可以找到的任何建议,但我似乎无法让它发挥作用。我知道用CardLayout我不能把面板放在面板的顶部,所以把图像放在JPanel上是行不通的。因此,我的问题是,根据下面发布的代码,是否有更好的方法来设置布局,使其更好地工作,以及如何显示图像,使其位于按钮的背景中?任何帮助都将不胜感激

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Cards implements ActionListener {    
private JPanel cards;
private JButton button1;
private JButton button2;
private Image backgroundImage;

public void addComponentToPane(Container pane) throws IOException {
    backgroundImage = ImageIO.read(new File("background.jpg"));

    //create cards
    JPanel card1 = new JPanel()
    {
        @Override
        public void paintComponent(Graphics g)
        {
            g.drawImage(backgroundImage, 0, 0, null);
        }
    };
    JPanel card2 = new JPanel();
    button1 = new JButton("Button 1");
    button2 = new JButton("Button 2");
    button1.addActionListener(this);
    button2.addActionListener(this);        
    card1.add(button1);        
    card2.add(button2);
    //create panel that contains cards
    cards = new JPanel(new CardLayout());
    cards.add(card1, "Card 1");
    cards.add(card2, "Card 2");
    pane.add(cards, BorderLayout.SOUTH);        
}

public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
}

public static void createAndShowGUI() throws IOException {
    //create and setup window
    JFrame frame = new JFrame("Frame"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    //create and setup content pane
    Cards main = new Cards();
    main.addComponentToPane(frame.getContentPane());        
    //display window
    frame.pack();
    frame.setSize(800, 600);
    frame.setResizable(false);
    frame.setVisible(true);
}

public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == button1) {
        CardLayout cl = (CardLayout) (cards.getLayout());
        cl.show(cards, "Card 2");     
    } else if (ae.getSource() == button2) {
        CardLayout cl = (CardLayout) (cards.getLayout());
        cl.show(cards, "Card 1");
    }        
}            

public static void main(String[] args) {
    //set look and feel
    try {
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }                

    //schedule job for the event dispatch thread creating and showing GUI        
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {                
                try {
                    createAndShowGUI();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }
    });     
}   
}

您需要覆盖对象
g
的方法和使用,如中所示


此外,通过以下方式检查这两个示例:


  • @Eng.Fouad的答案选择得很好,但图像可能主导了布局。您可能希望覆盖
    getPreferredSize()
    ,如下所示。然后你只需
    pack()
    窗口,大小就会合适。另见


    我会对每张卡都这样做吗,比如卡1和卡2的JPanel还是卡JPanel?@Jarod会覆盖每张卡的JPanel的paintcomont。我已经更新了上面的代码,但我得到一个错误:javax.imageio.IIOException:无法读取输入文件!你能给我一些建议吗?+1举了这么好的例子。:-)@杰罗德:对于两个小组来说,英格·福阿德的建议是有效的。对于更多,您可以考虑创建一个<代码> MyIMAPEPANEL 子类:“代码> jPosie/Cuth>,您可以使用您的每一个卡,如所建议的。@ Jarod:您可以验证名称和位置;一旦我拼写正确,你的代码就正常了。布局将需要一些注意。将分解作为一个练习进行重新分解。:-)请看一下这个,它可以让您了解项目的目录结构,还有这个示例,
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    public class Cards implements ActionListener {
    
        private JPanel cards;
        private JButton button1;
        private JButton button2;
        private Image backgroundImage;
    
        public void addComponentToPane(Container pane) {
            try {
                backgroundImage = ImageIO.read(new File("background.jpg"));
            } catch (IOException ex) {
                ex.printStackTrace(System.err);
            }
            //create cards
            JPanel card1 = new JPanel() {
    
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    g.drawImage(backgroundImage, 0, 0, null);
                }
    
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(
                        backgroundImage.getWidth(null),
                        backgroundImage.getHeight(null));
                }
            };
            JPanel card2 = new JPanel();
            button1 = new JButton("Button 1");
            button2 = new JButton("Button 2");
            button1.addActionListener(this);
            button2.addActionListener(this);
            card1.add(button1);
            card2.add(button2);
            //create panel that contains cards
            cards = new JPanel(new CardLayout());
            cards.add(card1, "Card 1");
            cards.add(card2, "Card 2");
            pane.add(cards, BorderLayout.SOUTH);
        }
    
        public void itemStateChanged(ItemEvent evt) {
            CardLayout cl = (CardLayout) (cards.getLayout());
            cl.show(cards, (String) evt.getItem());
        }
    
        public static void createAndShowGUI() {
            //create and setup window
            JFrame frame = new JFrame("Frame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //create and setup content pane
            Cards main = new Cards();
            main.addComponentToPane(frame.getContentPane());
            //display window
            frame.pack();
            frame.setVisible(true);
        }
    
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == button1) {
                CardLayout cl = (CardLayout) (cards.getLayout());
                cl.show(cards, "Card 2");
            } else if (ae.getSource() == button2) {
                CardLayout cl = (CardLayout) (cards.getLayout());
                cl.show(cards, "Card 1");
            }
        }
    
        public static void main(String[] args) {
            //schedule job for the event dispatch thread creating and showing GUI        
            EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                        createAndShowGUI();
                }
            });
        }
    }