Drawing with Java: Applying Borders/Outlines to Shapes

旧巷老猫 提交于 2021-02-04 21:35:22

问题


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).

My code:

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
    }
}

My output:

Correct output:


回答1:


The stroke doesn't matter so much when you call fillOval but moreso when you call drawOval. So I recommend:

  • Call fillOval as you're doing
  • After each fillOval, then change Color to Color.BLACK (or whatever outline color you desire), and call drawOval.
  • 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 proper paintComponent override inside a class that extends JPanel or JComponent.


来源:https://stackoverflow.com/questions/39750386/drawing-with-java-applying-borders-outlines-to-shapes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!