【发布时间】:2015-02-12 17:45:57
【问题描述】:
这里是Java新手... 我正在尝试将图像添加到我的 JFrame 的背景中。我已经在那个 JFrame 上的面板中添加了按钮。当我将图像添加到 JFrame 时,我的按钮消失了。
公共类 BackPanel 扩展 JFrame {
JFrame frame = new JFrame("Blackjack Game");
ImageIcon background;
JLabel backgroundLbl;
JButton newRoundButton;
JButton endButton;
ImageIcon image;
public BackPanel(GameConsole game){
final GameConsole game1 = game;
frame.setSize(800, 600);
//frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setContentPane(new JLabel(new ImageIcon(getClass().getResource("cardBackground.jpg"))));
ImagePanel panel = new ImagePanel("cardBackground.jpg");
panel.setPreferredSize(new Dimension(800, 600));
//put frame in the middle of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
//create 2 buttons on the panel
panel.add(endButton);
panel.add(newRoundButton);
frame.getContentPane().add(panel, BorderLayout.CENTER); //add the panel to the frame
// frame.pack();
frame.setVisible(true);
}
}
我感觉它与布局有关,但是当我使用其他布局时,它似乎没有帮助,或者它也会使图像消失。
我已将文件从“cardBackground.jpg”更改为“”,以查看按钮是否位于图像下方。他们不是。
我试图扩大框架以查看按钮是否在图像旁边,但它们不在。 (无论如何这都没有意义,因为它们不在同一个面板上)。
我错过了什么?
编辑: 更新后的代码不起作用:显示按钮但没有背景图像。
import java.awt.Dimension;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BackPanel{
public BackPanel(GameConsole game){
final GameConsole game1 = game;
JFrame frame = new JFrame("Blackjack Game");
ImagePanel panel = new ImagePanel("cardBackground.jpg");
panel.setPreferredSize(new Dimension(800, 600));
//create 2 buttons on the panel
JButton newRoundButton= new JButton("Start another round");
newRoundButton.setPreferredSize(new Dimension(150, 50));
newRoundButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
game1.userTurn();
}
});
JButton endButton = new JButton("End Game");
endButton.setPreferredSize(new Dimension(150, 50));
endButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have chosen to quit.\n"
+ "Thank you for playing Blackjack.");
System.exit(0);
}
});
panel.add(endButton);
panel.add(newRoundButton);
frame.add(panel);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
【问题讨论】: