Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

draw a circle by passing jpanel component as argument

Tags:

java

swing

jpanel

I am really confused how to draw a circle on the jpanel by passing it as an argument..

public class test extends JPanel{

        public test(JPanel jpanelcomponent) {

        }
        @Override
        protected void paintComponent(Graphics g) {
            // TODO Auto-generated method stub
            super.paintComponent(g);
            int width = getWidth()/2;
            int height = getHeight()/2;
            g.fillOval(5, 5, width, height);
        }


    }
like image 517
ranjan Avatar asked Dec 21 '12 13:12

ranjan


2 Answers

I think a better design would have you passing the Graphics object obtained from overriding paintComponent(..) of a JPanel to the class which will draw to the graphics object

Here is an example I made:

enter image description here

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Test {

    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }

    private void initComponents() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final DrawingClass dc = new DrawingClass();
        JPanel testPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics grphcs) {
                super.paintComponent(grphcs);
                Graphics2D g2d = (Graphics2D) grphcs;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                dc.draw(g2d, getWidth(), getHeight());

            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 300);
            }
        };

        frame.add(testPanel);

        frame.pack();
        frame.setVisible(true);
    }
}

class DrawingClass {

    public void draw(Graphics2D g2d, int w, int h) {
        g2d.setColor(Color.BLACK);
        g2d.fillOval(5, 5, w / 2, h / 2);
    }
}
like image 193
David Kroukamp Avatar answered Sep 28 '22 04:09

David Kroukamp


@David's answer is better, but you can try using the decorator pattern like they show here.

like image 24
Catalina Island Avatar answered Sep 28 '22 05:09

Catalina Island