简体   繁体   English

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

[英]Java how to add image as background in layout

I have a class that uses a CardLayout which has two cards that have a button on them. 我有一个使用CardLayout的类,它有两张卡片,上面有一个按钮。 What I would like to be able to do is put an image that would act like a background such as a desktop background in Windows. 我希望能够做的是放置一个像背景一样的图像,例如Windows中的桌面背景。 The program eventually will have several different cards and I'd like to be able to put different backgrounds on each card. 该程序最终将有几张不同的卡片,我希望能够在每张卡片上放置不同的背景。 I've tried many suggestions posed in other similar questions on this site as well as whatever I can find through googling it, but I just can't seem to get it to work. 我已尝试过在本网站上提出的其他类似问题中提出的许多建议,以及通过Google搜索我能找到的任何建议,但我似乎无法让它发挥作用。 I understand that with the CardLayout I can't put a panel on top of a panel, so putting an image on a JPanel wouldn't work. 我知道使用CardLayout我不能将面板放在面板上,因此将图像放在JPanel上是行不通的。 So my question is, based off the code posted below, is there a better way for me to setup my layout so that it works better, and also, how should I approach displaying the image so that it is in the background of the buttons? 所以我的问题是,根据下面发布的代码,我有更好的方法来设置我的布局,以便它更好地工作,而且,我应该如何处理显示图像,使其在按钮的背景中? Any help would be greatly appreciated. 任何帮助将不胜感激。

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

        }
    });     
}   
}

You need to override the method paintComponent(Graphics g) of JPanel and use drawImage() on the Graphics object g as in this example . 您需要重写方法paintComponent(Graphics g)JPanel的和使用drawImage()图形对象g如在本实施例中


Also, check these two examples by @trashgod : 另外,请通过@trashgod检查这两个示例:

  1. example . 例子
  2. example . 例子

@Eng.Fouad's answer is well chosen, but the image probably dominates the layout. @ Eng.Fouad的答案很好,但图像可能在布局中占主导地位。 You might want to override getPreferredSize() as shown below. 您可能希望覆盖getPreferredSize() ,如下所示。 Then you can just pack() the window, and the size will be right. 然后你可以pack()窗口,大小将是正确的。 See also Loading Images Using getResource . 另请参阅使用getResource加载图像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM