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

烈酒焚心 提交于 2019-12-09 15:06:27

问题


I started using MiGLayout about a month and half ago and everything is simple and works great. There's only one issue I still have that I haven't been able to fix.

Let's say I want to have a row that has two buttons on the right-most side and a centered title, the title doesn't actually get centered when I do it this way:

("this" is a JPanel)

this.add(labelTitle, "split, span, center");
this.add(closeButton, "east");
this.add(mainMenuButton, "east");   

What happens is that "labelTitle" is centered in the remaining space available after the buttons are placed, but I actually want it to be centered relative to the whole JPanel, not just the remaining space.

What parameters could I use to get the desired effect? I know I could use absolute positioning, but I don't want to do that because it defeats the purpose of using MiGLayout in the first place in my case.


回答1:


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);
}



回答2:


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); 



回答3:


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...



来源:https://stackoverflow.com/questions/6964511/how-to-center-a-component-on-a-row-containing-multiple-components-with-miglayout

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