我想放置背景图片和卡片,使得他们总是垂直和水平居中,即使在调整JFrame中。
然后,您需要使用面板上的布局管理器。布局管理器负责重做布局。
如何将两个JPanels添加到中心的JFrame中?
您可以尝试使用OverlayLayout进行此操作。我认为基本的代码如下:
JPanel contentPane = new JPanel(new GrigBagLayo9ut());
frame.add(contentPane, BorderLayout.CENTER);
JPanel overlay = new JPanel()
overlay.setLayout(new OverlayLayout(overlay));
contentPane.add(overlay, new GridBagConstraints()); // this should center the overlay panel
overlay.add(yourCardPanel); // you care panel must use a suitable layout
overlay.add(new JLabel()); // use a JLabel for the background not a custom panel
我还需要其他的JPanel添加到JFrame在南方边境,为一个JFrame的内容窗格
的默认布局管理器是BorderLayout的。我们已经将游戏面板添加到中心,因此只需将您的其他面板添加到南方。
如果OverlayLayout不能按照您想要的方式工作,那么您将需要嵌套面板。类似:
JPanel center = new JPanel(new GridBagLayout());
frame.add(center, BorderLayout.CENTER);
JLabel background = new JLabel(...);
background.setLayoutManager(new GridBagLayout());
center.add(background, new GridBagConstraints());
background.add(yourCardPanel, new GridBagConstraints());
编辑:
使用嵌套板:
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutCenter extends JPanel
{
public GridBagLayoutCenter()
{
setLayout(new BorderLayout());
JLabel background = new JLabel(new ImageIcon("mong.jpg"));
background.setLayout(new GridBagLayout());
add(background, BorderLayout.CENTER);
JPanel tiles = new JPanel();
tiles.setPreferredSize(new Dimension(200, 200));
tiles.setBackground(Color.RED);
background.add(tiles, new GridBagConstraints());
add(new JLabel("SOUTH"), BorderLayout.SOUTH);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("GridBagLayoutCenter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GridBagLayoutCenter());
frame.setSize(400, 400);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
的 “砖” 面板的优选尺寸不应该被硬编码。大小应由您的自定义布局管理器根据您添加到面板的切片来确定。大小不应该随着瓷砖被移除而改变。
1)Java GUI可能需要在多种平台上工作,使用不同的屏幕分辨率并使用不同的PLAF。因此,它们不利于组件的准确放置。为了组织强大的图形用户界面,请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[空格]的布局填充和边框(http: //stackoverflow.com/q/17874717/418556)。 2)为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 –