2016-03-16 46 views
0

我是Java編程的新手,無法處理我的Swing問題。我無法將JButton和JLabels集中到JPanel中(BoxLayout)。JLabel和JButton Center in 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("")); 
+1

爲了減少混淆,我建議你看看Java編碼約定,尤其是它建議變量和字段名稱應該以小寫字母開頭的部分(例如'upgradesPanel')。 – Thomas

+0

@Thomas是啊,對不起,我已經收到了它,但在這一刻,我不想重寫所有~10'000行,並檢查,哪裏的小信,大,我會在稍後做。但謝謝你的建議。 – Crelix

+0

@托馬斯,謝謝我找到它。作出回答,我會檢查它是否正確。 – Crelix

回答

1

至於佈局問題:有一個關於如何使用框佈局的教程(查找組件的對齊方式來居中它們):docs.oracle.com/javase/tutorial/uiswing/layout/box.html。

另外,你可以使用一個像MigLayout這樣更容易使用IMO的外部佈局管理器。