File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes need help with my code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "need help with my code" Watch "need help with my code" New topic

need help with my code

barbara rocha

Joined: Aug 08, 2007
Posts: 1
Hi.. I'm trying to do a Frame with this draw that changes it's color each time I click the button... but it's not working ... can someone help me?

Here is the code.. ( only the button shows up in the screen).

public class MyDrawPanel extends JPanel {

public void paintComponet(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,blue,green);


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

* @author babi rocha
public class SimpleGui3C extends JFrame implements ActionListener {

JFrame frame;

public static void main (String[] args) {
SimpleGui3C gui = new SimpleGui3C();

public void go() {
frame = new JFrame();

frame.setLayout(new GridLayout(2, 2));

JButton button = new JButton("Change colors!");

MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300, 300);


public void actionPerformed(ActionEvent e) {
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42959
Welcome to JavaRanch.


That's your problem - the method name is missing an "n". You may want to get in the habit of using the @Override annotation to avoid this kind of mistake.
Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

You just misspelled paintComponent

Also, the packed frame isn't large enough for the circle to show up without resizing the frame. You may want to set the frame size specifically to a larger size and leave off the pack() call, or set the minimum and preferred size of the MyDrawPanel to a value that will take the size and location of the circle into account.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
It is sorta covered in the JavaRanch Style Guide.
subject: need help with my code
It's not a secret anymore!