java怎么绘制网格线,我们如何在GridLayout中显示网格线?

How do we show the gridline in GridLayout? in Java?

JPanel panel = new JPanel(new GridLayout(10,10));

panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int i =0; i

panel.add(new JLabel("Label"));

}

解决方案

I would try to do it by adding borders to the components as they are added. The simple way to do it is just using BorderFactory.createLineBorder(), like this:

JPanel panel = new JPanel(new GridLayout(10,10));

panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int i =0; i

final JLabel label = new JLabel("Label");

label.setBorder(BorderFactory.createLineBorder(Color.BLACK));

panel.add(label);

}

However, that will give you thicker borders between the cells than at the edges of the panel, because the outer edges will only have a one-pixel thick border and the inside edges will have two one-pixel thick borders together. To work around that, you can use BorderFactory.createMatteBorder() to only draw one-pixel-wide borders everywhere:

final int borderWidth = 1;

final int rows = 10;

final int cols = 10;

JPanel panel = new JPanel(new GridLayout(rows, cols));

panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int row = 0; row < rows; row++) {

for (int col = 0; col < cols; col++) {

final JLabel label = new JLabel("Label");

if (row == 0) {

if (col == 0) {

// Top left corner, draw all sides

label.setBorder(BorderFactory.createLineBorder(Color.BLACK));

}

else {

// Top edge, draw all sides except left edge

label.setBorder(BorderFactory.createMatteBorder(borderWidth,

0,

borderWidth,

borderWidth,

Color.BLACK));

}

}

else {

if (col == 0) {

// Left-hand edge, draw all sides except top

label.setBorder(BorderFactory.createMatteBorder(0,

borderWidth,

borderWidth,

borderWidth,

Color.BLACK));

}

else {

// Neither top edge nor left edge, skip both top and left lines

label.setBorder(BorderFactory.createMatteBorder(0,

0,

borderWidth,

borderWidth,

Color.BLACK));

}

}

panel.add(label);

}

}

This should give you borders of width borderWidth everywhere, both between cells and along the outside edges.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值