How to center a component on a row containing mult

2019-04-05 02:01发布

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.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-05 02:45

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楼-- · 2019-04-05 02:54

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

查看更多
姐就是有狂的资本
4楼-- · 2019-04-05 02:58

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);
}
查看更多
登录 后发表回答