0

所以在我的 GUI 中,我有一个 JFrame,它是一个边框布局。NORTH 和 WEST 有一个菜单栏和一些 GUI 内容。在 CENTER 中,有一个 JLabel。我希望它移动到 JPanel 的中心(水平和垂直)。我该如何正确地做到这一点?我尝试了盒子布局和网格布局。一个要求是我不能使用 gridbag 布局。

public class NewClass extends JFrame{
    public NewClass () {
        setVisible(true);
        setSize(500,500);
        setDefaultCloseOperation (EXIT_ON_CLOSE);

//menubar
        JMenuBar bar = new JMenuBar();
        JMenu editMenu = new JMenu("Edit");
        JMenuItem mItem = new JMenuItem("Cut"); // edit->cut
        editMenu.add(mItem);
        mItem = new JMenuItem("Copy"); // edit->copy
        editMenu.add(mItem);
        mItem = new JMenuItem("Paste"); // edit->paste
        editMenu.add(mItem);
        bar.add(editMenu);
        this.setJMenuBar(bar);

//north panel
        JPanel topPanel = new JPanel();
        this.add(topPanel,BorderLayout.NORTH);
        JLabel myLabel = new JLabel ("Label:") ;
        topPanel.add(myLabel);
        JButton mytopButton = new JButton ("Push Me");
        topPanel.add(mytopButton);

//left panel
        JPanel leftPanel = new JPanel();
        leftPanel.setBorder (new TitledBorder("Commands:"));
        leftPanel.setLayout (new GridLayout (10,1));
        this.add(leftPanel,BorderLayout.WEST);
        JButton myLeftButton1 = new JButton ("Button 1");
        leftPanel.add(myLeftButton1);
        JButton myLeftButton2 = new JButton ("Button 2");
        leftPanel.add(myLeftButton2);
        JButton myLeftButton3 = new JButton ("Button3");
        leftPanel.add(myLeftButton3);

//center panel
        JPanel centerPanel = new JPanel();
        this.add(centerPanel,BorderLayout.CENTER);
        JLabel mapLabel = new JLabel("Test_String"); //move this to center of JPanel
        centerPanel.add(mapLabel);
        centerPanel.setBorder (new EtchedBorder(Color.black,Color.black));
        centerPanel.setBackground (Color.white);
    }
}
4

3 回答 3

1

检查 API 中影响alignment组件的方法。

有些方法会影响布局管理器中组件的对齐方式,而其他方法会影响标签本身内文本的对齐方式。

于 2013-10-30T05:13:14.803 回答
1

首先查看JavaDocsJLabel

具体来说,JLabel#setHorizontalAlignmentJLabel#setVerticalAlignment

于 2013-10-30T05:14:16.857 回答
1

回答。感谢大家。

    JPanel centerPanel = new JPanel();
    centerPanel.setLayout (new GridLayout ()); //added
    this.add(centerPanel,BorderLayout.CENTER);
    JLabel mapLabel = new JLabel("Test_String");
    mapLabel.setHorizontalAlignment(SwingConstants.CENTER); //added
    mapLabel.setVerticalAlignment(SwingConstants.CENTER); //added
    centerPanel.add(mapLabel);
    centerPanel.setBorder (new EtchedBorder(Color.black,Color.black));
    centerPanel.setBackground (Color.white);
于 2013-10-30T05:35:53.267 回答