Reputation: 53
I typed this code from the book
public class SimpleGui3C {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame("My own code");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(420,300);
frame.setVisible(true);
}}
class MyDrawPanel extends JPanel {
public void painComponent(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);
}}
Here is the original code of the book, I downloaded this code from the book's website
public class SimpleGui3C {
JFrame frame;
public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(420,300);
frame.setVisible(true);
}}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.fillRect(0,0,this.getWidth(), this.getHeight());
// make random colors to fill with
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);
}}
I checked it again and again to make sure that they're the same, and it seems that they are the same. but why the GUIs are different?
please help, thanks in advance.
Upvotes: 1
Views: 49
Reputation: 2742
In your own code, the method name is painComponent
when it should be paintComponent
.
Hint: Add @Override
to overriden methods, then the compiler will tell you about errors like this:
@Override
public void painComponent(Graphics g) {
Upvotes: 5