您好,我一直在关注如何将背景图像添加到JFrame的多个指南。但是,当运行我的程序时,只显示底部左侧和底部的背景图像。使用Swing将背景图像添加到JFrame
这里是我当前的代码:
private int width = 1280;
private int height = 720;
private String title = "Creation - " + Component.versionID + " Launcher";
private JPanel window = new JPanel();
private JFrame frame = new JFrame();
private JLabel name, version;
private JButton play, options, changelog, quit;
private Rectangle rPlay, rOptions, rChangelog, rQuit, rName, rVersion;
private int buttonWidth = 200;
private int buttonHeight = 80;
public Menu (Component component) {
frame.setTitle(title);
frame.setSize(new Dimension(width, height));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(component);
frame.getContentPane().add(window);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setIconImage(new ImageIcon("res/icon.png").getImage());
setLayout(new BorderLayout());
JLabel background = new JLabel(new ImageIcon("res/background.png"));
frame.add(background);
background.setLayout(new FlowLayout());
window.setLayout(null);
drawButtons();
frame.repaint();
frame.pack();
}
private void drawButtons() {
name = new JLabel("Creation");
rName = new Rectangle((width/2) - (buttonWidth/2) + 60, 20, buttonWidth, buttonHeight);
name.setBounds(rName);
window.add(name);
play = new JButton("Play");
rPlay = new Rectangle((width/2) - (buttonWidth/2), 250, buttonWidth, buttonHeight);
play.setBounds(rPlay);
window.add(play);
options = new JButton("Options");
rOptions = new Rectangle((width/2) - (buttonWidth/2), 350, buttonWidth, buttonHeight);
options.setBounds(rOptions);
window.add(options);
changelog = new JButton("View change-log");
rChangelog = new Rectangle((width/2) - (buttonWidth/2), 450, buttonWidth, buttonHeight);
changelog.setBounds(rChangelog);
window.add(changelog);
quit = new JButton("Quit");
rQuit = new Rectangle((width/2) - (buttonWidth/2), 550, buttonWidth, buttonHeight);
quit.setBounds(rQuit);
window.add(quit);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = new Component();
frame.dispose();
component.start();
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
changelog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
(正如你所看到的)我的JFrame的尺寸为1280x720。这与背景图片大小相同,所以我没有看到任何问题。如果任何人都可以帮我编辑我的代码或给我指针,我只是寻找背景图像显示在按钮后面。
* “JFrame的尺寸为1280x720,这是大小背景图像相同的” * ......不,它赢得了”不要。一个框架有装饰,这意味着应用程序可用的空间将是'frame.size - frame border insets'。而不是直接设置框架的大小,使用一个自定义组件,返回内容区的'preferredSize',并将其用作框架内容窗格...... – MadProgrammer 2013-05-02 03:23:01