boxlayout和page-y轴:不起作用,为什么?

时间:2012-02-08 05:53:11

标签: java swing layout

有谁知道为什么我的窗口内容没有放在中心?
内容只是进入左上角,无论我做了什么修改:我都找不到原因......
我想在页面-Y轴上使用一个简单的BoxLayout:

package myview;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.io.IOException;

import javax.swing.*;

import Model.Words;

public class MyWindow extends JFrame {
    JLabel myWord = new JLabel();

    public MyWindow(){
        this.setSize(500, 300);
        this.setVisible(true);
        this.setLocationRelativeTo(null);

        JPanel listPane = new JPanel();
        listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
        //listPane.setAlignmentX(Component.CENTER_ALIGNMENT);

        Words words = new Words();
        this.myWord.setText(words.getWord());
        listPane.add(myWord);
        JLabel myWord2 = new JLabel("test");
        listPane.add(myWord2);
        this.setContentPane(listPane);
        //, BorderLayout.CENTER
        //buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    }

    public static void main (String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyWindow mywindow = new MyWindow();
                mywindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                mywindow.setVisible(true);
            }
        });

    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可能希望在Box.createVerticalGlue中的组件之前和之后添加BoxLayout

此外,我还使用Box.createVerticalBox作为容器。