Results 1 to 2 of 2
  1. #1
    wikemol is offline Member
    Join Date
    Jan 2012
    Posts
    3
    Rep Power
    0

    Default Why won't this rectangle display in my JFrame?

    Why won't this rectangle appear on the content pane when I run the file?

    Main Class:

    package drawing;

    import javax.swing.JFrame;

    public class Main {

    public static void main(String[] args){
    JFrame frame = new JFrame();
    MyDrawPanel rect = new MyDrawPanel();

    frame.getContentPane().add(rect);

    frame.setVisible(true);
    frame.setSize(300, 300);


    }

    }



    MyDrawPanel class:


    package drawing;

    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;

    class MyDrawPanel extends JPanel{


    public void paintComponents(Graphics g){
    g.setColor(Color.orange);
    g.fillRect(20, 50, 100, 100);



    }


    }

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    6

    Default Re: Why won't this rectangle display in my JFrame?

    The method to override should be paintComponent() (without the "s").

    When overriding a method your code should be:

    Java Code:
    @Override
    public void paintComponent(Graphics g)
    This way you will get a compile error if you have a typing mistake like this.

    Also, your code works because you are adding the panel to the center of the frame, but it will not work if you add it to the NORTH of the BorderLayout. When doing custom painting you need to:

    a) invoke super.paintComponent(...) at the start of the method
    b) override the getPreferredSize() method to return the preferred size of the panel so the layout manager can do its job.

Similar Threads

  1. Second JFrame won't display as I intend
    By elnbado in forum AWT / Swing
    Replies: 0
    Last Post: 03-08-2011, 12:45 PM
  2. Display output in Jframe or JPanel
    By rammurugesan in forum AWT / Swing
    Replies: 12
    Last Post: 04-14-2009, 01:45 PM
  3. can display image in JFrame?
    By xCLARAx in forum AWT / Swing
    Replies: 14
    Last Post: 04-03-2009, 07:02 PM
  4. Right-clicking a rectangle on a JFrame to remove it
    By busdude in forum New To Java
    Replies: 4
    Last Post: 02-20-2009, 02:44 AM
  5. Unable to display JDialog from JFrame
    By jv5 in forum NetBeans
    Replies: 2
    Last Post: 02-04-2009, 04:33 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •