Reputation: 31
Can you help me how to use the super (super.paintComponent(g);
) keyword in Java.
Can we use super keyword within the paintComponent
method in Java? What if we use super in the main method. Is it even possible?
File Drawrainbow.java
package com.company;
import javax.swing.*;
import java.awt.*;
public class DrawRainbow extends JPanel {
// define indigo and violet
private final static Color VIOLET = new Color(128,0,128);
private final static Color INDIGO = new Color(75,0,130);
//colors to use in the rainbow, starting from innermost
// the two white entries result in an empty arc in the center
private Color[] colors ={Color.WHITE, Color.WHITE, VIOLET,INDIGO,Color.BLUE,Color.GREEN,Color.YELLOW,Color.ORANGE,Color.RED};
//constructor
public DrawRainbow(){
setBackground(Color.WHITE); // set the background to while
}
// draws a rainbow using concentric arcs
public void paintComponent(Graphics g){
super.paintComponent(g);
int radius = 20; // radius of an arc
// draw the rainbow near the bottom-center
int centerX = getWidth()/2;
int centerY = getHeight() - 10;
// draws filled arcs starting with the outermost
for (int counter = colors.length; counter > 0; counter--){
// set the color for the current arc
g.setColor(colors[counter-1]);
//fill the arc from 0 to 180 degrees
g.fillArc(centerX-counter*radius,
centerY-counter*radius,
counter*radius*2,counter*radius*2,0,180);
}
}
}
File Test.java
package com.company;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
// write your code here
DrawRainbow panel = new DrawRainbow();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(400,250);
application.setVisible(true);
}
}
Upvotes: 3
Views: 389
Reputation: 140631
Here:
> super.paintComponent(g);
On your DrawRainbow
instance, you are invoking the "original" implementation of paintComponent()
as inherited from the super class of DrawRainbow
.
In other words: when you are facing the need to
@Override
a super class methodthen you use super like that.
Note: the main method is static. Static methods aren't inherited, thus there is no point in doing super.main()
(or for any other static method).
And to be precise: you can't override static methods, if at all, you can only "shadow" them.
Instead, if you would want to do that, you could say MySuperClass.main()
for example.
Upvotes: 6
Reputation: 1691
super
is mostly used to call the parent constructor but basically it just represents the parent class and can be used to access members of the parent class
Upvotes: 0