Reputation:
I'm now studying Head First Java book. And I've encountered an example that shows how to override paintComponent in order to draw a random color circle over black color rectangle having width and height of the whole JPanel.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.fillRect(0, 0, this.getWidth(), this.getHeight());
int red = (int)(Math.random() * 255);
int green = (int)(Math.random() * 255);
int blue = (int)(Math.random() * 255);
Color randomColor = new Color(red, green, blue);
g.setColor(randomColor);
g.fillOval(70, 70, 100, 100);
}
}
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui3 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
But I am not achieving the expected results: nothing is painted on the panel.
What am I doing wrong? How to make this work?
Upvotes: 0
Views: 524
Reputation: 46
You need two additions in main method for this to work. You have to instantiate the MyDrawPanel() class and then add it to the frame.
MyDrawPanel p = new MyDrawPanel();
and
frame.add(p);
So the main method should be:
public static void main(String[] args) {
JFrame frame = new JFrame();
MyDrawPanel p = new MyDrawPanel();
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
Upvotes: 0