How to center a component on a row containing multiple components with MiGLayout

北城余情 提交于 2019-12-04 01:39:21
Mikael Grev

Can it be something like this you are looking for?

Cheers!

public static void main(String[] args)
{
    JFrame frame = new JFrame();

    JPanel panel = new JPanel(new MigLayout("debug"));
    panel.add(new JLabel("Label Title"), "x2 min(b1.x - unrel, (container.w+pref)/2)");
    panel.add(new JButton("Close Button"), "id b1, pushx, alignx right");
    panel.add(new JButton("Main Menu Button"), "alignx right");

    frame.add(panel);
    frame.setSize(800, 200);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

You can use the JXLayer and put the buttons in the glasspane.

JButton closeButton = new JButton("Close");
JButton mainMenuButton = new JButton("Menu");
JLabel labelTitle = new JLabel("Application");

JPanel panel = new JPanel();
panel.setLayout(new MigLayout(new LC().fillX()));
panel.add(labelTitle, new CC().alignX("center").spanX());

JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new MigLayout(new LC().fillX()));
buttonPanel.add(closeButton, new CC().alignX("right").split());
buttonPanel.add(mainMenuButton, new CC().alignX("right"));
buttonPanel.setOpaque(false);

JXLayer<JPanel> mainPanel = new JXLayer<JPanel>();
mainPanel.setView(panel);
mainPanel.setGlassPane(buttonPanel);

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(mainPanel);
frame.setSize(400, 600);
frame.setVisible(true); 
BenCole

When creating your JPanel, use the following MigLayout initializer:
new MigLayout("","[]push[center]push[]","")

If you don't know about constraints, check here: MigLayout Whitepaper

This is assuming you don't have anything else in this JPanel...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!