[英]How to add image to JFrame as background and still add other components to it?
[英]How to add a background image without removing components from screen? Java
我想在不刪除添加到屏幕上的當前組件的情況下,以圖像作為JFrame的背景。
我可以在屏幕上顯示圖像,但是一旦添加,按鈕就會從屏幕上消失。
我當前的代碼將圖像放到屏幕上,但刪除了按鈕。 執行此操作的行標有注釋。
任何幫助/建議將不勝感激! -提前致謝
package game;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MainMenu extends JFrame{
public MainMenu() {
super("TEST");
}
public static void createGUI()
{
MainMenu frame = new MainMenu();
frame.setSize(300,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/**
* This is the line that is giving me issues
**/
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Austin\\Pictures\\Landscape.jpg")));
panel(frame);
frame.setVisible(true);
}
public static void panel(MainMenu frame)
{
JPanel panel = new JPanel(new GridBagLayout());
frame.add(panel);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(4,4,4,4);
panel.add(Buttons.singlePlayerButton(), c);
c.gridx = 0;
c.gridy = 1;
panel.add(Buttons.twoPlayerButton(), c);
c.gridx = 0;
c.gridy = 2;
panel.add(Buttons.exitButton(), c);
}
public static void runGUI()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createGUI();
}
});
}
}
JFrame.add()
是JFrame.getContentPane().add()
的快捷方式。 這意味着通過調用frame.add(panel);
您將設置一次JFrame
的內容窗格,然后再調用frame.setContentPane(new JLabel(...));
您將丟棄舊的內容窗格,並用剛剛創建的新JLabel
替換它。
執行所需操作的更好方法是創建一個新類,該類是JPanel
的子類,然后重寫其paintComponent()
方法,以便將圖像直接繪制在面板的背景上。 將所有按鈕等添加到自定義JPanel
子類的新實例。
這已經在堆棧溢出的其他一些地方進行了描述:
嘗試更改“ frame.add(panel);” 添加到面板方法中的退出按鈕后的位置。 我不知道這是否可行,但是您在添加按鈕之前先添加了面板。 對我來說似乎有點奇怪,但也許是正確的。
打招呼
*編輯我認為在將面板添加到框架之后也應該可以添加按鈕,但我不確定
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.