This discussion is archived
1 Reply Latest reply: Jan 14, 2013 2:33 AM by EJP RSS

Question on code in swing?

983190 Newbie
Currently Being Moderated
Hey guys, I'm really new to Java. I was working on a bit of code to simply put up an oval and a rectangle in swing/awt. I was wondering if you guys could explain the concept of getContentPane().add(new MyComp()); I really don't get it. I will give you guys the code, and in it I put comments where i dont get stuff. Also, another question is, is the Paint Method called implicitly at run time? How is paint called? Does AWT simply call it? Thanks guys, heres the code;

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

class Rect {
     public static void main(String[] args) {
          Rect draw = new Rect(); /*This simply instantiates the object, so that the constructor comes in, right? *\
     }

     public Rect() {  //here we set up the constructor to make our window
          JFrame frame = new JFrame("Drawing with Alph!");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new MyComp()); //What does get Contentpane() do? I know it's a method, but what's its use?
          frame.setSize(500, 500);
          frame.setVisible(true);
     }

     public class MyComp extends JComponent { /*This is what I don't understand; the JComponent part. I understand the code block within it, however. *\ What does JComponent do?
          public void paint(Graphics mw) { /*Why is the Graphics class within the parameter here? Is this an object? Super confused on this *\
               int length = 200;
               int width = 130;
               mw.setColor(Color.red);
               mw.drawRect(20, 30, length, width);
               mw.fillRect(20, 30, length, width);
               mw.setColor(Color.red);
               mw.drawOval(250, 100, length, width);
               mw.setColor(Color.cyan);
               mw.fillOval(249, 99, length, width);
          }
     }
}

If you guys can help me out with those questions, I will be one of the happiest people ever. Thank you so much, and have a great day!
  • 1. Re: Question on code in swing?
    EJP Guru
    Currently Being Moderated
    another question is, is the Paint Method called implicitly at run time? How is paint called? Does AWT simply call it?
    I've already answered that question in a previous thread of yours. If you didn't understand, you should have said so in that thread, rather than just repeating yourself ad nauseam.

    You are just wasting your own time and that of other people by this piecemeal approach to learning, forum question by forum question, and I've already told you so in another prior thread. I cannot imagine anything more inefficient. I also recommended you to get a book, and to read the Java Language Tutorial. When you've done that, you should read the Java Swing Tutorial.

    Locking this thread.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points