如何在矩形中创建矩形?

时间:2011-11-26 06:46:45

标签: java swing drawrect graphics2d paintcomponent

在我的paintComponent中,我有drawRect,它绘制一个矩形。但是,我想让矩形的轮廓更粗,但我不知道如何。所以我想在现有的矩形内部制作另一个矩形。我尝试了另一个drawRect,但矩形不在中心。

感谢那些有帮助的人!

1 个答案:

答案 0 :(得分:4)

g2d.setStroke(new BasicStroke(6));

传递给Swing组件的paintComponent(Graphics)方法的参数实际上应该是Graphics2D实例。它可以投射到一个。

请参阅此示例,其中3个笔划是分层的。

Stroke It

import javax.swing.*;
import java.awt.*;

class StrokeIt {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                StrokePanel sp = new StrokePanel();
                sp.setPreferredSize(new Dimension(400,100));
                sp.setBackground(Color.BLUE);
                JOptionPane.showMessageDialog(null, sp);
            }
        });
    }
}

class StrokePanel extends JPanel {

    int pad = 12;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;

        g2d.setColor(Color.RED);
        g2d.setStroke(new BasicStroke(10));
        g2d.drawRect( 0+pad, 0+pad,
            getWidth()-(2*pad), getHeight()-(2*pad) );

        g2d.setColor(Color.YELLOW);
        g2d.setStroke(new BasicStroke(6));
        g2d.drawRect( 0+pad, 0+pad,
            getWidth()-(2*pad), getHeight()-(2*pad) );

        g2d.setColor(Color.ORANGE);
        g2d.setStroke(new BasicStroke(2));
        g2d.drawRect( 0+pad, 0+pad,
            getWidth()-(2*pad), getHeight()-(2*pad) );
    }
}