我正在尝试在Java中创建一个全屏应用程序。我有三个扩展JPanel的类,我想添加它。每个都有自己的布局和组件。
我第一次尝试使用MiG Layout。我有一个扩展JFrame作为主窗口的类。此类有一个使用MiG的面板,另外三个类被添加到此面板中。现在主面板出现在左上方,我希望它出现在中心。我尝试制作一个“包装”面板,我可以使用BorderLayout集中,但这似乎不起作用。我尝试了其他一些排列,但我觉得这应该有效,我不明白为什么不是。
以下是相关代码:
public class MainWindow extends JFrame {
private final int WINDOW_WIDTH = 800; //Width
private final int WINDOW_HEIGHT = 800; //Height
//three panel objects
private final IntroPanel header;
private final InputPanel input;
private final SubmitPanel submit;
//for fullscreen
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public MainWindow() throws MalformedURLException {
//set things like size, close operation, etc
this.Build();
//Create a MiG layout
MigLayout layout = new MigLayout("wrap 3");
//panel which will hold three panels
JPanel panel = new JPanel(layout);
//initiate the three panels we need for user actions
header = new IntroPanel();
input = new InputPanel();
submit = new SubmitPanel();
panel.add(header, "span, center, gapbottom 15");
panel.add(input, "span, center, gapbottom 15");
panel.add(submit,"span, center, gapbottom 15");
this.setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
//set the windows position to the center of the screen
setLocationRelativeTo(null);
//Make the window visable
setVisible(true);
}
答案 0 :(得分:1)
this.setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
而不是BorderLayout使用GridBagLayout
:
this.setLayout(new GridBagLayout());
add(panel, new GridBagConstraints());
答案 1 :(得分:0)
避免将面板直接添加到JFrame。请改用this.setContentPane(panel)
。这样您就不需要任何额外的布局。使用MigLayout为mainPanel添加LayoutContraint填充。
public class MigLayoutTests {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new MigLayout("debug, fill", "", ""));
mainPanel.add(new JLabel("Hello World"), "align left bottom");
frame.setContentPane(mainPanel);
frame.setVisible(true);
}
}