Reputation: 33
So I am trying to create a simple program that prints out a rectangle but I am having this problem and I don't know how to fix it. Here is my code:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class GraphicsEditor extends JPanel{
public void drawShape(Graphics g) {
super.drawShape(g);
g.setColor(Color.BLUE);
g.drawRect(100, 100, 120, 150);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
GraphicsEditor ga = new GraphicsEditor();
frame.setSize(1280, 720);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(ga);
}
}
The error is when I am trying to add the super
in here:
public void drawShape(Graphics g) {
super.drawShape(g);
g.setColor(Color.BLUE);
g.drawRect(100, 100, 120, 150);
}
Upvotes: 1
Views: 900
Reputation: 168825
A JPanel
has no drawShape(Graphics)
method, so calling the 'super' method makes no sense. When you think you're overriding a method, be sure to add the @Override
notation to get a compiler warning when the method is incorrectly spelled, uses the wrong arguments, or is just entirely non-existent (as is the case here).
The correct way to go about this is to override the paintComponent
method, call the (existing) super method, then immediately call the drawShape
method with the Graphics
instance provided to the paintComponent
method.
This is the result when the GUI is shrunk down:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class GraphicsEditor extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawShape(g);
}
// @Override // does NOT override an existing method!
public void drawShape(Graphics g) {
//super.drawShape(g);
g.setColor(Color.BLUE);
g.drawRect(100, 100, 120, 150);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
GraphicsEditor ga = new GraphicsEditor();
frame.setSize(280, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(ga);
}
}
Upvotes: 1