Skip to content Skip to sidebar Skip to footer

Draw a Filled Circle in Java

I have a JPanel with a Grid Layout. In the cells of the grid I can put different elements (for example JButtons). There is no problems with that. Simply at present I want to put a filled circumvolve in some of the cells. I also would similar to relate an ActionListener with these circles. In more details, if I click the circle it disappears from the current prison cell and appears in another ane. How can I practice it in Java? I am using Swing.

Accepted Answer

            public void paintComponent(Graphics g) {    super.paintComponent(g);    Graphics2D g2d = (Graphics2D)g;    // Assume x, y, and diameter are instance variables.    Ellipse2D.Double circle = new Ellipse2D.Double(x, y, bore, diameter);    g2d.fill(circle);    ... }                      

Here are some docs nearly paintComponent (link).

You should override that method in your JPanel and practise something like to the code snippet higher up.

In your ActionListener you lot should specify ten, y, diameter and telephone call repaint().


Alternate Solution:

You probably demand to practice something like :

            Paint red = new Paint();  red.setColor(android.graphics.Color.Cherry); cherry-red.setStyle(Paint.Way.FILL);                      

And use this color for your path, instead of your ARGB. Brand sure the final point of your path ends on the first one, it makes sense also.

Tell me if it works please !


Yous probably need to practise something like :

            Paint ruby = new Pigment();  red.setColor(android.graphics.Color.Red); red.setStyle(Paint.Style.FILL);                      

And use this color for your path, instead of your ARGB. Make sure the last point of your path ends on the kickoff 1, it makes sense also.

Tell me if information technology works please !


The SwingWorker'due south API documentation offers this hint:

The doInBackground() method is chosen
on this thread. This is where all
background activities should happen.
To notify PropertyChangeListeners
about leap backdrop changes utilise the
firePropertyChange and
getPropertyChangeSupport() methods. By
default there are two bound properties
available: land and progress.

MainWorker can implement PropertyChangeListener. It can and then register itself with its PropertyChangeSupport:

            getPropertyChangeSupport().addPropertyChangeListener( this );                      

MainWorker can supply its PropertyChangeSupport object to every MyTask object information technology creates.

            new MyTask( ..., this.getPropertyChangeSupport() );                      

A MyTask object can so notify its MainWorker of progress or belongings updates past using PropertyChangeSupport.firePropertyChange methods.

MainWorker, and so notified, can then utilise SwingUtilities.invokeLater or SwingUtilities.invokeAndWait to update the Swing components via the EDT.

            protected Void doInBackground() {     terminal int TASK_COUNT = 10;     getPropertyChangeSupport().addPropertyChangeListener(this);     CountDownLatch latch = new CountDownLatch( TASK_COUNT ); // java.util.concurrent     Collection<Thread> threads = new HashSet<Thread>();     for (int i = 0; i < TASK_COUNT; i++) {         MyTask chore = new MyTask( ..., latch, this.getPropertyChangeSupport() ) );         threads.add( new Thread( task ) );     }     for (Thread thread: threads) {         thread.get-go();     }     latch.await();     return null; }                      

I tin can think of two approaches. The first is to generate a Shape that represents the foursquare outter edge and the rounded inner edge.

The 2d would be to use a AlphaComposite to generate a masked result.

            public class TestMask {      public static void main(String[] args) {         new TestMask();     }      public TestMask() {         EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 endeavor {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                 }                  JFrame frame = new JFrame(Testing);                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.setLayout(new BorderLayout());                 frame.add(new MaskedPane());                 frame.pack();                 frame.setLocationRelativeTo(zero);                 frame.setVisible(true);             }          });     }      public course MaskedPane extends JPanel {          public MaskedPane() {             setBackground(Color.RED);         }          @Override         public Dimension getPreferredSize() {             render new Dimension(200, 200);         }          @Override         protected void paintComponent(Graphics g) {             super.paintComponent(g);              BufferedImage outter = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);             Graphics2D g2d = outter.createGraphics();             g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             g2d.setColor(Colour.BLACK);             g2d.fillRect(0, 0, getWidth(), getHeight());             g2d.dispose();             BufferedImage inner = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);             g2d = inner.createGraphics();             g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             g2d.setColor(Color.Blackness);             g2d.fillRoundRect(10, 10, getWidth() - 20, getHeight() - xx, twenty, xx);             g2d.dispose();              BufferedImage masked = applyMask(outter, inner, AlphaComposite.DST_OUT);             m.drawImage(masked, 0, 0, this);          }          public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) {             BufferedImage maskedImage = null;             if (sourceImage != nix) {                  int width = maskImage.getWidth();                 int peak = maskImage.getHeight();                  maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);                 Graphics2D mg = maskedImage.createGraphics();                  int 10 = (width - sourceImage.getWidth()) / 2;                 int y = (height - sourceImage.getHeight()) / 2;                  mg.drawImage(sourceImage, x, y, null);                 mg.setComposite(AlphaComposite.getInstance(method));                 mg.drawImage(maskImage, 0, 0, null);                 mg.dispose();             }              return maskedImage;         }          public BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage) {             return (BufferedImage) applyMask(sourceImage, maskImage, AlphaComposite.DST_IN);         }     } }                      

Updated with Shape example

Finally had time to blindside one out…

            public course TestMask {      public static void primary(Cord[] args) {         new TestMask();     }      public TestMask() {         EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                 }                  JFrame frame = new JFrame(Testing);                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.setLayout(new BorderLayout());                 frame.add together(new ShapedPane());                 frame.pack();                 frame.setLocationRelativeTo(zip);                 frame.setVisible(true);             }         });     }      public class ShapedPane extends JPanel {          public ShapedPane() {             setBackground(Color.GREEN);         }          @Override         public Dimension getPreferredSize() {             render new Dimension(200, 200);         }          @Override         protected void paintComponent(Graphics g) {             super.paintComponent(g);              Graphics2D g2d = (Graphics2D) g.create();             g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);             g2d.setColor(Colour.Black);             g2d.fill(new RounedFrame(getWidth(), getHeight(), 10, 20));             g2d.dispose();         }     }      public class RounedFrame extends Path2D.Float {          public RounedFrame(float width, float elevation, float thickness, float radius) {              moveTo(0, 0);             lineTo(width, 0);             lineTo(width, height);             lineTo(0, acme);             lineTo(0, 0);              float innerWidth = width - thickness;             bladder innerHeight = superlative - thickness;              moveTo(thickness + radius, thickness);             lineTo(innerWidth - radius, thickness);              curveTo(innerWidth, thickness, innerWidth, thickness, innerWidth, thickness + radius);              lineTo(innerWidth, innerHeight - radius);             curveTo(innerWidth, innerHeight, innerWidth, innerHeight, innerWidth - radius, innerHeight);             lineTo(thickness + radius, innerHeight);             curveTo(thickness, innerHeight, thickness, innerHeight, thickness, innerHeight - radius);             lineTo(thickness, thickness + radius);             curveTo(thickness, thickness, thickness, thickness, thickness + radius, thickness);              closePath();              setWindingRule(WIND_EVEN_ODD);          }     } }                      

Updated

From a comment by Andrew, you could simplify the use of the shape example past using Area

You could replace the paintComponent from the to a higher place case with this one…

            @Override protected void paintComponent(Graphics g) {     super.paintComponent(one thousand);      Area area = new Area(new Rectangle(0, 0, getWidth(), getHeight()));     expanse.subtract(new Area(new RoundRectangle2D.Float(ten, 10, getWidth() - 20, getHeight() - 20, 20, twenty)));      Graphics2D g2d = (Graphics2D) g.create();     g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);     g2d.setColor(Color.BLACK);     g2d.fill(expanse);     g2d.dispose(); }                      

Which is much simpler 😀

#draw #filled #circle #Java

Provide Your Ratings:

I like meeting friends on weekends. I like to listen to music with headphones. My family is very important for me. I like to dream big. My family is very important for me.

What do you think?

haskinswholy1951.blogspot.com

Source: https://codeinfopark.com/questions/how-to-draw-a-filled-circle-in-java/

Post a Comment for "Draw a Filled Circle in Java"