Swing/DashedLine のバックアップの現在との差分(No.8)
BasicStrokeで点線を作成
編集者:Terai Atsuhiro~
作成日:2004-10-04
更新日:2021-10-27 (水) 00:02:51
概要
破線パターンの配列からBasicStroke
を作成し、これを描画します。
概要
点線・破線を描画します。Screenshot
Advertisement
サンプルコード
#spanend
#spanadd
JLabel label = new JLabel() {
#spanend
private BasicStroke dashedStroke;
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (dashedStroke == null) {
dashedStroke = new BasicStroke(
5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10f,
getDashArray(), 0f);
}
Insets i = getInsets();
int w = getWidth();
int h = getHeight() / 2;
Graphics2D g2 = (Graphics2D) g.create();
g2.setStroke(dashedStroke);
g2.drawLine(i.left, h, w - i.right, h);
g2.dispose();
}
#spanadd
};
#spanend
#spanadd
View in GitHub: Java, Kotlinサンプルコード
JLabel label = new JLabel() { BasicStroke dashed2 = new BasicStroke(); public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; super.paintComponent(g2); if(flag) dashed2 = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, icStroke.JOIN_MITER, 10.0f, getDashArray(), 0.0f); flag = false; g2.setStroke(dashed2); g2.drawLine(5, getHeight()/2, getWidth()-10, getHeight()/2); } };
解説
上記のサンプルでは、BasicStroke
の破線属性を指定して点線をコンポーネント内に描画しています。
解説
BasicStrokeの破線属性を指定して点線を描画します。- 破線のパターンは
JTextField
にカンマ区切りで記入した数値を配列に分解し、これをBasicStroke
に渡して作成
参考リンク
- BasicStroke (Java Platform SE 8)
- Stroking and Filling Graphics Primitives (The Java™ Tutorials > 2D Graphics > Working with Geometry)