[英]JPanel adding background
如何調整輸入面板和游戲面板的大小,以便可以容納整個框架? inputpanel.setsize()無法正常工作,另一個問題是游戲面板無法顯示其背景圖像。
我所做的是在框架中添加了一個主面板,該面板包含其他2個面板,即inputpanel和gamepanel。 兩個面板都有邊框顯示,但尺寸很小,我需要它們適合屏幕
public class GameMaster {
JFrame frame = new JFrame();
JPanel gamepanel = new Gamepanel();
JPanel mainpanel = new JPanel();
JPanel inputpanel = new JPanel();
JButton button1 = new JButton("Hoy!");
public GameMaster(){
frame.setTitle("gayEdward vs Charlie's angels");
frame.setSize(800,600);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setLayout(new FlowLayout());
gamepanel.setSize(600, 600);
inputpanel.setSize(200, 600);
mainpanel.setSize(800, 600);
gamepanel.setBorder(BorderFactory.createLineBorder(Color.black));
inputpanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainpanel.setLayout(new FlowLayout());
mainpanel.add(gamepanel);
mainpanel.add(inputpanel);
frame.add(mainpanel);
}
這是Gamepanel類,其中Gamepanel應該將圖像設置為其背景
public class Gamepanel extends JPanel {
Image image;
public Gamepanel(){
try
{
image = ImageIO.read(getClass().getResourceAsStream("C:\\Users\\phg00159\\workspace\\Mp2\\pvzbg.jpg"));;
}
catch (Exception e) { /*handled in paintComponent()*/ }
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}
您需要在GamePanel
類中重寫getPreferredSize()
。 進行自定義繪畫時,應始終這樣做。 面板沒有首選尺寸,因為它沒有組件。 而且,您使用FlowLayout
的布局考慮了首選大小。 然后,只需將框架pack()
,而不是設置大小。 還要注意,組件的setSize()
通常用於null布局(我強烈反對)。 對於布局管理器,它們由preferredSize
確定
public class GamePanel extends JPanel {
private Image image;
@Override
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(this), image.getHeight(this));
// or whatever you want the size to be
}
}
在旁邊:
/*handled in paintComponent()*/
-空檢查不能替代空的catch塊。
在添加所有組件之后, frame.setVisible()
應該是您要做的最后一件事
更新
正如@MadProgrammer向我指出的那樣,您希望面板根據框架調整大小。 為此,您需要使用其他布局管理器。 不尊重您的面板的首選大小的兩個將是GridLayout
或BorderLayout
。 這些將“拉伸您的組件以適合”。 因此,請選擇其中一個,或將兩者組合,以查看您是否具有嵌套面板。 但是,您還應該保留重寫的getPreferredSize()
並仍然pack()
您的框架,這將根據您的首選尺寸為您提供框架的初始尺寸
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.