2016-05-01 4 views
1

でのJLabelとのJButtonを中央にどのように困難なレベルBoxLayout

コードの

Screen shot

次の数行でシンプルなメニューを作成するコンストラクタです。あなたがscreenshoot上で見ることができるボタンを追加addButtons()

super(); 

setMinimumSize(new Dimension(600, 300)); 

setMaximumSize(new Dimension(600, 300)); 

setPreferredSize(new Dimension(600, 300)); 

setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); 

addButtons(); 

方法:

add(Box.createVerticalGlue()); 

addLabel("<html>Current level <b>" + Game.instance() 
             .getLevelString() + 
     "</b></html>"); 

add(Box.createVerticalGlue()); 

addButton("Easy"); 

add(Box.createVerticalGlue()); 

addButton("Normal"); 

add(Box.createVerticalGlue()); 

addButton("Hard"); 

add(Box.createVerticalGlue()); 

addButton("Back"); 

add(Box.createVerticalGlue()); 

方法addButton()

private void addButton(String text) 
{ 
    JButton button = new JButton(text); 
    button.setAlignmentX(JButton.CENTER_ALIGNMENT); 
    button.setFocusable(false); 

    add(button); 
} 

そしてaddLabel()

private void addLabel(String text) 
{ 
    JLabel label = new JLabel(text, JLabel.CENTER); 

    add(label); 
} 

私はすべての要素をどのように中心に合わせるかを知らない。それは私にとっては問題です。追加の問題は、JLabelの難しいレベルのテキストを簡単な「現在のレベルEASY」に変更することができます。その後、JButtonsは多くのピクセルを右に動かしているのですが、その理由はわかりません。

答えて

2

public JLabel(String text, int horizontalAlignment)の2番目のパラメータは、ラベルのテキスト位置を決定するためのものです。 JLabelコンポーネントのアライメントをsetAlignmentXメソッドで設定する必要があります。

private void addLabel(String text) { 
    JLabel label = new JLabel(text, JLabel.CENTER); 
    label.setAlignmentX(JLabel.CENTER_ALIGNMENT); 
    add(label); 
} 

編集:

あなたの第二の問題は奇妙です。なぜこのようなことが起こっているのか分かりませんが、ボタンの2番目のパネルを作成すると問題が解決すると思います。コンストラクタ使用境界レイアウトで

super(); 

//set size 

setLayout(new BorderLayout()); 

addButtons(); 
addButtons()

方法:

//you can use empty border if you want add some insets to the top 
//for example: setBorder(new EmptyBorder(5, 0, 0, 0)); 

addLabel("<html>Current level <b>" + Game.instance() 
            .getLevelString() + 
    "</b></html>"); 

JPanel buttonPanel = new JPanel(); 
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.PAGE_AXIS)); 

buttonPanel.add(Box.createVerticalGlue()); 

buttonPanel.add(createButton("Easy")); 

buttonPanel.add(Box.createVerticalGlue()); 

//Add all buttons 

add(buttonPanel, BorderLayout.CENTER); 
createButton()

方法

private JButton createButton(String text) 
{ 
    JButton button = new JButton(text); 
    button.setAlignmentX(JButton.CENTER_ALIGNMENT); 
    button.setFocusable(false); 

    return button; 
} 

addLabel()方法

private void addLabel(String text) 
{ 
    JLabel label = new JLabel(text, JLabel.CENTER); 
    add(label, BorderLayout.NORTH); 
} 
+0

これは機能していますが、レベル(および 'JLabel'のテキスト)を変更すると、ボタンによってピクセルが右端に移動します。 – ventaquil

+0

@ventaquil私の編集をご覧ください。 – rdonuk

+0

それは働いています、ありがとう:) – ventaquil

関連する問題