Java网格布局

https://www.cnblogs.com/aipan/p/6409522.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Java网格布局时,可以通过设置组件的水平和垂直方向上的对齐方式,将组件内容居中。具体代码如下: ``` import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class GridBagLayoutDemo extends JFrame { public GridBagLayoutDemo() { initComponents(); } private void initComponents() { setTitle("GridBagLayout Demo"); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; JLabel label1 = new JLabel("Label 1"); panel.add(label1, c); c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; JLabel label2 = new JLabel("Label 2"); panel.add(label2, c); c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; JButton button1 = new JButton("Button 1"); panel.add(button1, c); c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.CENTER; JButton button2 = new JButton("Button 2"); panel.add(button2, c); getContentPane().add(panel); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } public static void main(String[] args) { new GridBagLayoutDemo().setVisible(true); } } ``` 在上面的示例代码中,我使用了GridBagConstraints类对组件的位置、对齐方式等进行了设置。其中,设置了组件的anchor属性为CENTER,表示组件在水平和垂直方向上都居中对齐。通过这种方式,即可实现Java网格布局中组件内容居中的效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值