I am new to the java swing library and am trying to create my own components. In this case I have a Circle class extending the JComponent class. However, when trying to add an instance of the Circle class to my JPanel, the circle isn’t displaying (only the JPanel).
I am aware that drawing directly to the JPanel with the Graphics class would be simpler, but I want to be able to create my own visuals class.
This is my code:
import javax.swing.;
import java.awt.;
public class Main{
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel myPanel = new JPanel();
myPanel.setBackground(Color.CYAN);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myPanel.add(new Circle());
frame.add(myPanel);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class Circle extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(50, 50, 100, 100);
}
}
When running this code, only the cyan background of the JPanel is appearing. Is the JPanel covering the red circle? Have I overriden the paintComponent method incorectly?
Nikos Mitsopoulos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.