gpt4 book ai didi

java - BoxLayout 中的 JLabel 和 JButton 中心

转载 作者:行者123 更新时间:2023-12-01 10:13:28 24 4
gpt4 key购买 nike

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

这里有一些照片:

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

最佳答案

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

或者,您可以使用外部布局管理器之一,例如 MigLayout,在我看来,它更易于使用。

关于java - BoxLayout 中的 JLabel 和 JButton 中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36037251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com