BoxLayout中的JLabel和JButton中心

时间:2016-03-16 13:35:41

标签: java swing layout-manager centering boxlayout

我是Java编程的新手,无法处理我的Swing问题。我无法在JPanels(BoxLayout)中获得JButtons和JLabels。

以下是一些照片:

Here Labels ar Centred, and buttons don't Here nothing is centred

代码:

        PlayerLabel.setHorizontalTextPosition(JLabel.CENTER);
        PlayerLabel.setVerticalTextPosition(JLabel.BOTTOM);
        PlayerLabel.setText("Player Level: " + CarMain.main[5]);

    AccessoriesLVL1Label.setHorizontalTextPosition(JLabel.CENTER);
    AccessoriesLVL1Label.setVerticalTextPosition(JLabel.BOTTOM);
    AccessoriesLVL1Label.setText("<html>Accessories LVL 1<br>" + "Count: " + Part.parts[1]);

JButton jbtnSellAccessoriesLv1 = new JButton("Sell");
jbtnSellAccessoriesLv1.addActionListener(this);

这就是我制作Jlabel的地方:

//升级面板

GridLayout UpgradesLayout = new GridLayout(3,3);
        JPanel UpgradesPanel = new JPanel();
        UpgradesPanel.setLayout(UpgradesLayout);

        JPanel UpgradesPanelSub = new JPanel();
        UpgradesPanelSub.setLayout(new BoxLayout(UpgradesPanelSub, BoxLayout.PAGE_AXIS));
        UpgradesPanelSub.setBorder(BorderFactory.createCompoundBorder(raisedbevel, loweredbevel));

        JPanel UpgradesPanelSub2 = new JPanel();
        UpgradesPanelSub2.setLayout(new BoxLayout(UpgradesPanelSub2, BoxLayout.PAGE_AXIS));
        UpgradesPanelSub2.setBorder(BorderFactory.createCompoundBorder(raisedbevel, loweredbevel));

        JPanel UpgradesPanelSub3 = new JPanel();
        UpgradesPanelSub3.setLayout(new BoxLayout(UpgradesPanelSub3, BoxLayout.PAGE_AXIS));
        UpgradesPanelSub3.setBorder(BorderFactory.createCompoundBorder(raisedbevel, loweredbevel));

        UpgradesPanelSub.add(Labels.PlayerLabel);
        UpgradesPanelSub.add(jbtnUpgradeLevel);
        UpgradesPanelSub2.add(Labels.GarageLabel);
        UpgradesPanelSub2.add(jbtnUpgradeGarageLevel);
        UpgradesPanelSub3.add(Labels.BoxesLVLLabel);
        UpgradesPanelSub3.add(jbtnUpgradeBoxesLevel);

        UpgradesPanel.add(new JLabel(""));
        UpgradesPanel.add(new JLabel(""));
        UpgradesPanel.add(new JLabel(""));
        UpgradesPanel.add(UpgradesPanelSub);
        UpgradesPanel.add(UpgradesPanelSub2);
        UpgradesPanel.add(UpgradesPanelSub3);
        UpgradesPanel.add(new JLabel(""));
        UpgradesPanel.add(new JLabel(""));
        UpgradesPanel.add(new JLabel(""));

1 个答案:

答案 0 :(得分:1)

关于布局问题:有关如何使用框布局的教程(查找组件&#39;对齐以使它们居中):docs.oracle.com/javase/tutorial/uiswing/layout/box html的。

或者你也可以使用像MigLayout这样的外部布局管理器,它们更容易使用IMO。