簡體   English   中英

Java:如何將JLabel移動到JPanel的中心?

[英]Java: How do I move a JLabel to the center of a JPanel?

所以在我的GUI中,我有一個JFrame,它是borderlayout。 有一個菜單欄,以及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);
    }
}

檢查API是否有影響組件alignment的方法。

有一些方法會影響布局管理器中組件的對齊方式,而其他方法會影響標簽本身中的文本對齊方式。

回答。 感謝大家。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM