如何调整输入面板和游戏面板的大小,以便它可以占据整个框架? inputpanel.setsize() 不起作用,另一个问题是游戏面板不会显示其背景图像。
我所做的是将一个主面板添加到框架中,其中包含另外两个面板:输入面板和游戏面板。两个面板都显示有边框,但尺寸非常小,我需要它们适合屏幕
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()
通常用于空布局(我强烈反对)。对于布局管理器,它们由 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
}
}
旁白:
/*在paintComponent()中处理*/
- null 检查不能替代空的 catch block 。frame.setVisible()
应该是添加所有组件后执行的最后一件事
更新
正如 @MadProgrammer 向我指出的,您希望面板随框架调整大小。为此,您需要使用不同的布局管理器。 不会尊重面板首选大小的两个是 GridLayout
或 BorderLayout
。这些将“拉伸(stretch)您的组件以适应”。因此,请选择其中之一或两者的组合,因为您有嵌套面板。但您还应该保留覆盖的 getPreferredSize()
和 pack()
您的框架,这将根据您的首选尺寸为您提供框架的初始尺寸
关于java - JPanel 添加背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25419041/