Java:如何将 JLabel 移动到 JPanel 的中心?

标签 java swing user-interface jframe jpanel

所以在我的 GUI 中,我有一个作为边框布局的 JFrame。北部和西部有一个菜单栏和一些 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 中影响组件对齐的方法。

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

关于Java:如何将 JLabel 移动到 JPanel 的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19674319/

相关文章:

java - 在java中的特定位置将项目添加到空列表

java - 在这种情况下如何声明 Java Comparable

java - 向 Jtable 添加一个监听器,该监听器在填充表时仅调用一次

java - 使用 OpenStreetMaps JMapViewer 移动 map 标记

java - GIF 基于每台计算机的速度?

java - 我怎样才能让 JPanel 在窗口滚动时自动更新?

java - 循环使用不同参数的方法调用

java - findViewById() 在包含的布局上返回 null?

c# - 业务对象变化时自动刷新UI

.net - 如何构建类似 Visual Studio 的 UI?