Java:将背景图像添加到框架

Java:将背景图像添加到框架,java,swing,jpanel,paintcomponent,imageicon,Java,Swing,Jpanel,Paintcomponent,Imageicon,可能重复: 我试图添加一个背景图像到我的框架,但我所做的一切都不起作用 我设计了一个老虎机,由几个面板组成,添加到容器中。现在,我正在尝试添加一个很好的背景帧 我试着用画法。但是,由于我已经在使用“绘制”方法绘制卷轴图像,因此它在背景上不起作用 我还尝试添加一个JLabel,但当我添加时,它会覆盖所有内容或被覆盖,具体取决于我如何调用它。以下是我的代码;任何帮助都将不胜感激: import javax.swing.event.*; import javax.swing.*; import j

可能重复:

我试图添加一个背景图像到我的框架,但我所做的一切都不起作用

我设计了一个老虎机,由几个面板组成,添加到容器中。现在,我正在尝试添加一个很好的背景帧

我试着用画法。但是,由于我已经在使用“绘制”方法绘制卷轴图像,因此它在背景上不起作用

我还尝试添加一个JLabel,但当我添加时,它会覆盖所有内容或被覆盖,具体取决于我如何调用它。以下是我的代码;任何帮助都将不胜感激:

import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import sun.audio.*;

public class SlotMachine extends JFrame {

    private Container c = getContentPane();

    private ImageIcon handleIcon = new ImageIcon("starWars/slot-handle.png");
    private ImageIcon quitIcon = new ImageIcon("starWars/quit2.jpg");
    private ImageIcon logoIcon = new ImageIcon("starWars/logo3.jpg");
    private ImageIcon BG = new ImageIcon("space.jpg");
    private JButton spin = new JButton("Spin", handleIcon);
    private JButton quit = new JButton("Quit", quitIcon);
    private JLabel logo = new JLabel(logoIcon);
    private JLabel bankTotal = new JLabel("Empire Total");
    private JLabel bankLabel = new JLabel("$1000.00");
    private JLabel playerLabel = new JLabel("$1000.00");
    private JLabel playerTotal = new JLabel("Rebellion Total");
    private Font newFont = new Font("DialogInput",Font.ITALIC, 25);
    private JPanel logoPanel = new JPanel(new BorderLayout());
    private JPanel moneyPanel = new JPanel(new GridLayout(1, 3, 5, 5));
    private JPanel imagePanel;
    private JPanel mainPanel = new JPanel(new BorderLayout());
    private JPanel bankPanel = new JPanel(new GridLayout(2, 1, 5, 5));
    private JPanel playerPanel = new JPanel(new GridLayout(2, 1, 5, 5));
    private JPanel panel = new JPanel(new FlowLayout());
    private SlotMachine.ReelPanel reel1 = new SlotMachine.ReelPanel();
    private SlotMachine.ReelPanel reel2 = new SlotMachine.ReelPanel();
    private SlotMachine.ReelPanel reel3 = new SlotMachine.ReelPanel();
    private AudioPlayer audioPlayer = AudioPlayer.player;
    private AudioDataStream continuousMusic;
    private AudioDataStream winMusic;
    private AudioDataStream force;
    private AudioDataStream force2;
    //private AudioDataStream intro;
    private ContinuousAudioDataStream audioLoop;
    private static final int DELAY = 1000;
    private static final double FUNDS = 1000.00;
    private static final float PRICE = 1;
    private int timerCounter = 0;
    private double bank = FUNDS;
    private double playerMoney = 1000.00;
    private Timer timer = new Timer(DELAY, new SlotMachine.TimeHandler());


public SlotMachine() {

        try {
            FileInputStream inputStream = new FileInputStream(new File("cantina4.wav"));
            AudioStream audioStream = new AudioStream(inputStream);
            AudioData audioData = audioStream.getData();
            continuousMusic = new AudioDataStream(audioData);            
            audioLoop = new ContinuousAudioDataStream(audioData);

            inputStream = new FileInputStream(new File("Cheer.wav"));
            audioStream = new AudioStream(inputStream);
            audioData = audioStream.getData();
            winMusic = new AudioDataStream(audioData);

            inputStream = new FileInputStream(new File("forceNN.wav"));
            audioStream = new AudioStream(inputStream);
            audioData = audioStream.getData();
            force = new AudioDataStream(audioData);

            inputStream = new FileInputStream(new File("force2NN.wav"));
            audioStream = new AudioStream(inputStream);
            audioData = audioStream.getData();
            force2 = new AudioDataStream(audioData);   


        } catch (Exception e) {
            e.printStackTrace();
        }

        audioPlayer.start(force);        

        // Set the font
        spin.setFont(newFont);
        quit.setFont(newFont);
        bankLabel.setFont(newFont);
        bankTotal.setFont(newFont);
        playerLabel.setFont(newFont);
        playerTotal.setFont(newFont);

        // implements start button
        spin.setVerticalTextPosition(SwingConstants.BOTTOM);
        spin.setHorizontalTextPosition(SwingConstants.CENTER);
        spin.setBackground(Color.GREEN);
        spin.setForeground(Color.WHITE);
        spin.setPreferredSize(new Dimension(100, 370));
        spin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                audioPlayer.stop(force);
                audioPlayer.stop(force2);
                timer.start();
                reel1.startAnimation();
                reel2.startAnimation();
                reel3.startAnimation();
                spin.setEnabled(false);
                audioPlayer.start(audioLoop);
            }
        });
        // implements quit button    
        quit.setBackground(Color.RED);
        quit.setForeground(Color.WHITE);
        quit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                spin.setEnabled(true);
                reel1.stopAnimation();
                reel2.stopAnimation();
                reel3.stopAnimation();
                timer.stop();
                audioPlayer.stop(continuousMusic);
                audioPlayer.stop(audioLoop);
                audioPlayer.stop(winMusic);
                timerCounter = 0;
                audioPlayer.stop(force);
                audioPlayer.start(force2);
                imagePanel.repaint(); // without this call for repaint,  if you press quit but then choose to cancel
                //  the curent image and the next image would sometimes overlap this repaint may change the images but they do not overlap.
                if (JOptionPane.showConfirmDialog(SlotMachine.this,
                        "Are you sure you want to quit?", "Quit Option",
                        JOptionPane.OK_CANCEL_OPTION) == 0) {
                    audioPlayer.start(force2);
                    System.exit(0);
                }
            }
        });
        // create image panel
        imagePanel = new JPanel(new GridLayout(1, 3, 15, 15));
        imagePanel.setBackground(Color.WHITE);
        imagePanel.add(reel1);
        imagePanel.add(reel2);
        imagePanel.add(reel3);

        // create a panel to hold bank values
        bankTotal.setForeground(Color.WHITE);
        bankLabel.setForeground(Color.WHITE);
        bankPanel.setBackground(Color.GRAY);
        bankPanel.add(bankTotal);
        bankPanel.add(bankLabel);

        // panel to hold player values
        playerTotal.setForeground(Color.WHITE);
        playerLabel.setForeground(Color.WHITE);
        playerPanel.setBackground(Color.GRAY);
        playerPanel.add(playerTotal);
        playerPanel.add(playerLabel);

        // create a panel to add bank and player panels and quit button
        //moneyPanel.setBackground(Color.BLACK);
        moneyPanel.add(bankPanel);
        moneyPanel.add(playerPanel);
        moneyPanel.add(quit);
        moneyPanel.setOpaque(false);

        // this panel adds the reel panel and spin button
        panel.setPreferredSize(new Dimension(650, 350));
        //panel.setBackground(Color.BLACK);
        panel.add(imagePanel);
        panel.add(spin);
        panel.setOpaque(false);

        // create the logo panel
        logoPanel.add(logo);
        //logoPanel.setBackground(Color.BLACK);
        logoPanel.setOpaque(false);        

        mainPanel.add(logoPanel, BorderLayout.NORTH);
        mainPanel.add(panel, BorderLayout.CENTER);
        mainPanel.add(moneyPanel, BorderLayout.SOUTH);
        mainPanel.setOpaque(false);            

        //////////////////////////////////// background ???????????????????
        /// I could just set backgroung black but i want to add a image


        add(mainPanel, BorderLayout.CENTER);

        setTitle("Slot Machine");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setSize(950, 750);
        setResizable(false);
        setLocationRelativeTo(null);                      

    }

    public static void main(String[] args) {
        new SlotMachine();
    }

    public class ReelPanel extends JPanel {

        private final static String IMAGE_NAME = "starWars/icon";
        protected ImageIcon images[];
        private int currentImage = 0;
        private final int ANIMATION_DELAY = 150;
        private final int TOTAL_IMAGES = 12;
        private int width;
        private int height;
        private Timer animationTimer = new Timer(ANIMATION_DELAY, new SlotMachine.ReelPanel.TimerHandler());
        private int index;

        public ReelPanel() {
            try {
                images = new ImageIcon[TOTAL_IMAGES];
                for (int count = 0; count < images.length; count++) {
                    images[ count] = new ImageIcon(IMAGE_NAME + (count + 1) + ".jpg");
                }

                width = images[ 1].getIconWidth();
                height = images[ 1].getIconHeight();
                currentImage = 0;
                index = 0;
                animationTimer.setInitialDelay(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void paintComponent(Graphics g) {

            super.paintComponent(g);

            images[ currentImage].paintIcon(this, g, 0, 0);

            if (animationTimer.isRunning()) {
                currentImage = (int) (Math.random() * TOTAL_IMAGES);
            }
        }

        public void startAnimation() {

            animationTimer.start();
        }

        public void stopAnimation() {
            animationTimer.stop();
        }

        public int getIndex() {
            return index;
        }

        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(width, height);
        }

        private class TimerHandler implements ActionListener {

            public void actionPerformed(ActionEvent actionEvent) {
                repaint();
                index = currentImage;
            }
        }
    }

    private class TimeHandler implements ActionListener {

        public void actionPerformed(ActionEvent actionEvent) {
            audioPlayer.stop(winMusic);
            ++timerCounter;
            if (timerCounter == 2) {
                reel1.stopAnimation();
            } else if (timerCounter == 3) {
                reel2.stopAnimation();
            } else if (timerCounter == 4) {
                reel3.stopAnimation();
                audioPlayer.stop(continuousMusic);
                audioPlayer.stop(audioLoop);
                timerCounter = 0;
                timer.stop();
                spin.setEnabled(true);
                if (reel1.getIndex() == reel2.getIndex() && reel1.getIndex() == reel3.getIndex()) {
                    if (playerMoney > 0) {
                        playerMoney += bank;
                    } else {
                        playerMoney = bank;
                    }
                    bank = FUNDS;
                    winMusic.reset();
                    audioPlayer.start(winMusic);
                } else {
                    bank += PRICE;
                    playerMoney -= PRICE;
                }

                bankLabel.setText("$" + bank + 0);
                playerLabel.setText("$" + playerMoney + 0);
                if (playerMoney <= 0) {
                    JOptionPane.showMessageDialog(SlotMachine.this,
                            "You are out of funds. GAME IS OVER", "Error", JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                }
            }
        }
    }
}
import javax.swing.event.*;
导入javax.swing.*;
导入java.awt.*;
导入java.awt.event.*;
导入java.io.*;
导入sun.audio.*;
公共类SlotMachine扩展JFrame{
私有容器c=getContentPane();
私有ImageIcon handleIcon=新的ImageIcon(“starWars/slot handle.png”);
private ImageIcon quitIcon=新的ImageIcon(“starWars/quit2.jpg”);
private ImageIcon logoIcon=新的ImageIcon(“starWars/logo3.jpg”);
私有ImageIcon BG=新的ImageIcon(“space.jpg”);
私有JButton spin=新JButton(“spin”,handleIcon);
私有JButton quit=新JButton(“quit”,quitIcon);
专用JLabel徽标=新JLabel(logoIcon);
私人JLabel BANKTOTALL=新JLabel(“帝国总计”);
私人JLabel银行标签=新JLabel($1000.00);
私人JLabel playerLabel=新JLabel($1000.00);
私人JLabel playerTotal=新JLabel(“叛乱总数”);
私有字体newFont=新字体(“DialogInput”,Font.ITALIC,25);
private JPanel logoPanel=new JPanel(new BorderLayout());
private JPanel moneyPanel=新JPanel(新网格布局(1,3,5,5));
私人JPanel imagePanel;
private JPanel mainPanel=new JPanel(new BorderLayout());
私有JPanel bankPanel=新JPanel(新网格布局(2,1,5,5));
私有JPanel playerPanel=新JPanel(新网格布局(2,1,5,5));
private JPanel panel=new JPanel(new FlowLayout());
私有SlotMachine.ReelPanel reel1=新SlotMachine.ReelPanel();
专用SlotMachine.ReelPanel reel2=新SlotMachine.ReelPanel();
专用SlotMachine.ReelPanel reel3=新SlotMachine.ReelPanel();
私人AudioPlayer=AudioPlayer.player;
私人音频数据流连续音乐;
私有音频数据流winMusic;
私人音频数据流部队;
私有音频数据流force2;
//私有音频数据流简介;
专用连续音频数据流音频环路;
专用静态最终整数延迟=1000;
私人静态最终双基金=1000.00;
私人静态最终浮动价格=1;
专用int timerCounter=0;
私人双银行=基金;
私人双人游戏费用=1000.00;
专用计时器=新计时器(延迟,新SlotMachine.TimeHandler());
公共SlotMachine(){
试一试{
FileInputStream inputStream=新的FileInputStream(新文件(“cantina4.wav”);
AudioStream AudioStream=新的AudioStream(inputStream);
AudioData AudioData=audioStream.getData();
continuousMusic=新的音频数据流(audioData);
audioLoop=新的连续音频数据流(audioData);
inputStream=新文件inputStream(新文件(“chee.wav”);
audioStream=新的audioStream(inputStream);
audioData=audioStream.getData();
winMusic=新的音频数据流(音频数据);
inputStream=新文件inputStream(新文件(“forceNN.wav”);
audioStream=新的audioStream(inputStream);
audioData=audioStream.getData();
force=新的AudioDataStream(audioData);
inputStream=新文件inputStream(新文件(“force2NN.wav”);
audioStream=新的audioStream(inputStream);
audioData=audioStream.getData();
force2=新的音频数据流(audioData);
}捕获(例外e){
e、 printStackTrace();
}
音频播放器。启动(强制);
//设置字体
spin.setFont(newFont);
quit.setFont(newFont);
bankLabel.setFont(newFont);
bankTotal.setFont(newFont);
playerLabel.setFont(newFont);
playerTotal.setFont(newFont);
//机具启动按钮
spin.setVerticalTextPosition(SwingConstants.BOTTOM);
旋转设置水平文本位置(SwingConstants.CENTER);
旋转。挫折背景(颜色。绿色);
旋转。设置前景(颜色。白色);
spin.setPreferredSize(新尺寸(100370));
spin.addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件evt){
音频播放器。停止(强制);
音频播放器。停止(强制2);
timer.start();
卷1.startAnimation();
卷2.开始动画();
卷3.开始动画();
spin.setEnabled(false);
audioPlayer.start(audioLoop);
}
});
//执行退出按钮
退出。挫折背景(颜色。红色);
设置前景(颜色为白色);
quit.addActionListener(新建ActionListener()){
已执行的公共无效操作(操作事件evt){
spin.setEnabled(true);
reel1.stopAnimation();
reel2.stopAnimation();
reel3.stopAnimation();
timer.stop();
音频播放器。停止(连续音乐);
音频播放器。停止(音频环路);
音频播放器。停止(winMusic);
时间计数器=0;
音频播放器。停止(强制);
音频播放器。启动(强制2);
imagePanel.repaint();//如果您按quit但选择取消,则不需要调用repaint
//当前图像和下一图像有时会重叠。此重新绘制可能会更改图像,但它们不会重叠
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestBackgroundImage {

    private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame(TestBackgroundImage.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
        JPanel mainPanel = new JPanel(new BorderLayout()) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
            }

        @Override
        public Dimension getPreferredSize() {
            Dimension size = super.getPreferredSize();
            size.width = Math.max(backgroundImage.getIconWidth(), size.width);
            size.height = Math.max(backgroundImage.getIconHeight(), size.height);
            return size;
        }

        };
        mainPanel.add(new JButton("A button"), BorderLayout.WEST);
        frame.add(mainPanel);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new TestBackgroundImage().initUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

}