在我的paintComponent中,我有drawRect,它绘制一个矩形。但是,我想让矩形的轮廓更粗,但我不知道如何。所以我想在现有的矩形内部制作另一个矩形。我尝试了另一个drawRect,但矩形不在中心。
感谢那些有帮助的人!
答案 0 :(得分:4)
g2d.setStroke(new BasicStroke(6));
传递给Swing组件的paintComponent(Graphics)
方法的参数实际上应该是Graphics2D
实例。它可以投射到一个。
请参阅此示例,其中3个笔划是分层的。
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) );
}
}