如何使用swing绘制虚线gridlayout单元格边框?

时间:2009-09-18 09:22:43

标签: swing

当我向gridlayout.eg声明行和列时:3x2(3行和2列)。我必须得到这些行和列的骨架视图。就像一个虚线矩形。我们如何通过使用来实现这一点摇摆?

问候 马堂

2 个答案:

答案 0 :(得分:0)

为gridlayout中的每个组件添加Border

答案 1 :(得分:0)

对JPanel进行子类化以在paintChildren()中绘制网格。您添加到此面板的任何组件都将显示此网格。例如:

public class DebugPanel extends JPanel {

    @Override
    protected void paintChildren(Graphics g) {
        super.paintChildren(g);
        g.setColor(Color.GRAY);
        // dashed stroke
        BasicStroke stroke = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, 1,new float[]{5},0);
        ((Graphics2D)g).setStroke(stroke);      
        drawComponentGrid(this,g);
    }

    /**
     * Drawn vertical and horizontal guides for a containers child 
     * components
     */
    private static void drawComponentGrid(Container c, Graphics g) {
        for(int i=0;i<c.getComponentCount();++i) {
            Rectangle r = c.getComponent(i).getBounds();
            int x = r.x;
            // vertical line at left edge of component
            g.drawLine(x,0,x,c.getHeight());
            x+= r.width;
            // vertical line at right edge of component
            g.drawLine(x,0,x,c.getHeight());

            // horizontal line at top of component
            int y = r.y;
            g.drawLine(0,y,c.getWidth(),y);
            // horizontal line at bottom of component
            y+= r.height;
            g.drawLine(0,y,c.getWidth(),y);
        }
    }
}