Miglayout / setPreferredSize()和使用pack()方法的重点?

时间:2018-07-20 12:03:15

标签: java swing pack miglayout

我是Java / swing和图形界面的新手,只是想知道我做的是否正确,就对pack()方法的使用head之以鼻。我真的需要吗?到目前为止,没有它,一切看起来都很好。我想要的是根据屏幕尺寸设置的框架,也要使用MigLayout。我正在使用getPreferredSize()/ setPreferredSize()设置面板的大小。

那么,如果能够使用getPreferredSize()/ setPreferredSize()和MigLayout控制我的面板,那么pack()方法的意义何在?

import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;

public class BreakoutFrame extends JFrame{
    private int contentPanelWidth;

public BreakoutFrame(Board board, Ball ball) {
    super("Breakout");

    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    this.setLayout(new MigLayout("", "", ""));

    JPanel contentPanel = new JPanel();
    contentPanel.setLayout(new MigLayout("debug", "", ""));
    JPanel highscorePanel = new JPanel();
    highscorePanel.setLayout(new MigLayout("", "", ""));
    JPanel infoPanel = new JPanel();
    infoPanel.setLayout(new MigLayout("", "", ""));

    this.createMenu();
    this.add(infoPanel, "wrap,span 2");
    this.add(contentPanel, "pushy,growy");
    this.add(highscorePanel, "push,grow");

    //pack();

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setSize(screenSize.width, screenSize.height);

    Dimension sizeInfoPanel = infoPanel.getPreferredSize();
    sizeInfoPanel.width = screenSize.width;
    sizeInfoPanel.height = screenSize.height / 6;
    infoPanel.setPreferredSize(sizeInfoPanel);

    Dimension sizeContentPanel = contentPanel.getPreferredSize();
    sizeContentPanel.width = (int) (Math.round(screenSize.width * 0.75));
    contentPanel.setPreferredSize(sizeContentPanel);
    this.contentPanelWidth = sizeContentPanel.width;

    BreakoutComponent bc = new BreakoutComponent(board, ball, this.contentPanelWidth);
    contentPanel.add(bc, "push,grow");

    this.setResizable(false);
    this.setVisible(true);

    }

    private void createMenu() {
    final JMenuBar bar = new JMenuBar();
    final JMenu file = new JMenu("File");
    final JMenuItem close = new JMenuItem("Close");
    final JMenuItem newGame = new JMenuItem("New game");
    file.add(newGame);
    file.add(close);
    bar.add(file);
    this.setJMenuBar(bar);
    }
}

0 个答案:

没有答案