使用Java绘图:将边界/轮廓应用于形状 [英] Drawing with Java: Applying Borders/Outlines to Shapes
本文介绍了使用Java绘图:将边界/轮廓应用于形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何获取"g.setStroke(new BasicStroke(5));"设置为我创建的所有形状(在本例中为椭圆形).
I can't figure out how to get "g.setStroke(new BasicStroke(5));" to be set to all my created shapes (in this case ovals).
我的代码:
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.BasicStroke;
public class Rings
{
public static void main(String[] args)
{
DrawingPanel panel = new DrawingPanel(300, 300);
Graphics2D g = panel.getGraphics();
g.setStroke(new BasicStroke(5)); // Sets Outer Line Width of Shapes
g.setColor(new Color(255, 0, 0));
g.fillOval(50, 50, 200, 200); // Large Oval
g.setColor(new Color(200, 0, 0));
g.fillOval(100, 100, 100, 100); // Medium Oval
g.setColor(new Color(150, 0, 0));
g.fillOval(125, 125, 50, 50); // Small Oval
g.setColor(new Color(100, 0, 0));
g.fillOval(137, 137, 25, 25); // Tiny Oval
}
}
我的输出:
正确的输出:
推荐答案
当您调用fillOval时,笔触无关紧要,而当您调用 drawOval
时,笔触并不重要.所以我建议:
The stroke doesn't matter so much when you call fillOval but moreso when you call drawOval
. So I recommend:
- 在执行操作时调用
fillOval
- 在每个
fillOval
之后,将Color更改为Color.BLACK(或所需的任何轮廓颜色),然后调用drawOval
. - 查看图形,如果您最小化GUI,然后将其还原,将会发生什么情况.
- 因此,为了避免NullPointerException错误,我们建议您不要使用通过Swing组件上的
getGraphics()
调用获得的Graphics对象.这样的Graphics对象是短暂的.取而代之的是,教程和大多数其他类似的问题都会告诉您:在扩展JPanel或JComponent的类中的适当的paintComponent
中重写.
- Call
fillOval
as you're doing - After each
fillOval
, then change Color to Color.BLACK (or whatever outline color you desire), and calldrawOval
. - See what happens to your drawing if you minimize the GUI and then restore it.
- It is for this reason, and to avoid NullPointerException errors, that we don't recommend that you use a Graphics object obtained via a
getGraphics()
call on a Swing component. Such a Graphics object is short-lived. Instead do as the tutorials and most other similar questions will tell you: within a properpaintComponent
override inside a class that extends JPanel or JComponent.
这篇关于使用Java绘图:将边界/轮廓应用于形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文