java jlabel位置_Java:如何将JLabel移动到JPanel的中心?

在Java GUI中,作者面临一个问题,需要将一个JLabel放置在使用BorderLayout的JFrame中央面板的中心。文章讨论了如何在不使用GridBagLayout的情况下,通过调整布局和组件定位来实现JLabel的水平和垂直居中。
摘要由CSDN通过智能技术生成

所以在我的GUI中,我有一个JFrame,它是一个borderlayout . 在北部和西部有一个菜单栏和一些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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值