Paint vs paintComponent

I'm using the below code
public void paintComponent(Graphics g)
        super.paintComponent(g);
        layeredPane.setOpaque(false);
        g = layeredPane.getGraphics();
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        g2.draw((Shape) vPoly.elementAt(0));
    }it throws the below error in "super.paintComponent(g);" :
symbol  : method paintComponent(java.awt.Graphics)
location: class javax.swing.JFrame
        super.paintComponent(g);
Note: D:\Usama\NetBeans\MTT\src\First.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 errorCould anyone please tell me why?
The repaint() method does not call the paintComponent but if I change it to paint it does (in both cases i could not use the "super.paintComponent(g);"). When I change the paintComponent method to paint the I do not get the required result.
Regards

Quit multi-posting. You where asked in your other posting to post a SSCCE.
There is no problem overiding paintComponent(). We have all done it hundreds of times. We can't help based on a few lines of code as we don't know the context of how the code is used.
So quit wasting everybodies time by creating multiple postings on the forum. Keep the questions in a single posting so everybody knows what has been suggested already.
How many time to you have to be asked to do this??????

Similar Messages

  • Are there alternative methods to "paint()" and "paintComponent()"?

    Are there any ways to draw on the screen other than using "paint()" or "paintComponent()" methods? I am asking this because I need to use active rendering for my game, and active rendering doesn't make use of paint().
    Thanx.

    component.getGraphics()
    or, if you are using BufferStrategy,
    component.getBufferStrategy().getDrawGraphics();

  • What's the difference between paint and paintComponent?

    can any body tell me the difference between paint and paintComponent?and when i should use paint and when use paintComponent?
    I know that when I use repaint,it will clear all the objects and then paint again?
    is there a method similar to repaint?
    thanks in advance!

    and when i should use paint and when use paintComponent?Simple answer:
    a) override paint() when doing custom painting on an AWT component
    b) override paintComponent() when doing custom painting on a Swing component
    Detailed answer:
    Read the article on [url http://java.sun.com/products/jfc/tsc/articles/painting/index.html]Painting in AWT and Swing.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html]Custom Painting.

  • Difference between paint() and paintcomponent()

    What's the difference between the paint(), paintComponent(), paintAll(), repaint() and update() methods? Which one is preferred when printing graphics with a printer?

    http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html
    http://java.sun.com/docs/books/tutorial/2d/printing/
    paint          ---> AWT
    paintComponent ---> Swing
    repaint(AWT)   ---> update(background) ---> paint
    repaint(Swing) ---> in paintComponent  ---> super.paintComponent(background)

  • SetForeground into paint or paintcomponent calls a paint or paintco. loop ?

    I have a custom paint method for a Jpanel.
    I want to draw a ruler that shows me the number of character 1,2,3,4,5,6,7,8,9,0,1,2 ......
    I want to see '0' (zero) in black and the other numbers in DARK_GREY .
    I dont know what happens, but If I use the .setforeground' the paint or paintcomponent is called continuosly ?
    Any idea ?
    This is the code (I have tried both paint and paintcomponent)
    public void paintComponent(Graphics g){
         Graphics2D G2 = (Graphics2D) g.create();
         FontMetrics myfontmetrics = this.getFontMetrics(getFont());
         int width = myfontmetrics.stringWidth("1");
         int height = myfontmetrics.getHeight();
         int nn=-1;
         int x=0;
                     system.out.prinln("paint");
         while (x<getWidth()){
           nn++;
         if (nn==10) {
         nn=0;
         this.setForeground(Color.black);
         G2.drawString(String.valueOf(nn), x, height);
         x+=width;      }
          else  {
          this.setForeground(Color.DARK_GRAY);
          G2.drawString(String.valueOf(nn), x, height);
          x+=width;       }
      G2.dispose();     
    }

    Don't use setForeground(). Use Graphics.setColor().

  • Choose between: paint, repaint, paintComponent

    Hi,
    I am having problem's refreshing elements that i have draw in a jpanel, which is include in a container (well .. i just can not see anything at all).
    what do i have to use : paint, repaint, paintComponent ?
    is there some good tutorial online to learn to draw whith swing ??
    or better : to learn to draw a graph from a given tree.
    thank you!
    Syl.

    Must Read !!!
    Thanks
    --j                                                                                                                                                                                                                                       

  • Paint() and paintComponent() problem

    i still dun understandce what the difference between them is ...
    Anyone could explain it to me ??
    i know it is about delegation...
    In which circumstance that i should use one of them ?

    My reference says:
    For Swing components, the paint() method also draws the border and the children of the component ...so overriding it directly is not recommended. Instead, override the paintComponent() method to do any custom drawing.
    (more or less from) Java Foundation Classes in a Nutshell ...O'Reilly

  • What is the difference between paint() and paintComponent()?

    I always confuse by them?
    Thanks

    paintComponent is the method used by Swing components to do the painting necessary for the component. If you are making a custom Swing component, it is recommended that you override paintComponent instead of paint. Non-swing AWT components do not have a paintComponent method.
    A Swing component's default paint() method partitions the painting of a component into separate phases, including painting the component itself, painting the component's border, and finally painting all its children. Overriding paintComponent in a custom Swing component only affects the drawing of the component itself without impacting these other phases of drawing.

  • Painting using paintComponent();

    hi guys, here i'm trying to paint over the JFrame which is using null layout.
    i have used paintComponent(). . . nothing is being displayed. i feel like i'm not adding the panel object to the JFrame properly.
    any idea why its not showing the message i'm trying to draw?????????????????????????
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class LoginScreen extends JFrame
         JLabel userId;
         JTextField userIdT;
         JButton userIdHelp;
         *WelcomeLogin welcome;*
         public LoginScreen()
              super("User Login Screen");
              Container surface = getContentPane();
              setSize(1024,750);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
              surface.setLayout(null);
              *welcome = new WelcomeLogin();*
    *          surface.add(welcome);*
              userId = new JLabel("User ID       :",JLabel.LEFT);
              userId.setBounds(20,50,80,20);     surface.add(userId);
              userIdT = new JTextField(40);
              userIdT.setBounds(120,50,150,20);  surface.add(userIdT);
              userIdHelp = new JButton("?");    
              userIdHelp.setBounds(290,50,50,20);surface.add(userIdHelp);
              public static void main(String[] args)
              LoginScreen login = new LoginScreen();
              login.setVisible(true);
    class WelcomeLogin extends JPanel
         public void paintComponent(Graphics g)
              super.paintComponents(g);
              g.drawString("hey hi, how are you doing!",60,100);
    }

    Null layout has it's place, and if you've never used it and don't know how it works you really ought not to be giving out advice to others.Okay, you got me there. But..
    You don't always want a LayoutManager.Could you tell me why to use it when there is GroupLayout? And a bunch of other once as well. Cant the GroupLayout do the same thing, but better?
    EDIT: For some reason I find my self to want to know about the null layout, and hence Im reading this (also on the layout manager tutorial :S). Those reasons are as good as any for me to shut my trap. I shall try and be more educated on the matters I reply onto next time.
    Edited by: prigas on Apr 22, 2009 12:43 PM

  • Problem with paintComponent, and CPU usage

    Hi,
    I had the weirdest problem when one of my JDialogs would open. Inside the JDialog, I have a JPanel, with this paintComponent method:
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Color old = g.getColor();
    g.setColor(Color.BLACK);
    g.drawString("TEXT", 150, 15);
    g.setColor(old);
    parent.repaint();
    now when this method is called, the CPU usage would be at about 99%. If i took out the line:
    parent.repaint();
    the CPU usage would drop to normal. parent is just a reference to the Jdialog that this panel lies in.
    Anyone have any ideas on why this occurs?
    Thanks!

    1) I never got a stack overflow, and i have had this in my code for quite sometime...If you called paint() or paintComponent(), I'm betting that you would see a stack overflow. The way I understand it, since you are calling repaint(), all you are doing is notifying the repaint manager that the component needs to be repainted at the next available time, not calling a paint method directly. good article on how painting is done : http://java.sun.com/products/jfc/tsc/articles/painting/index.html#mgr
    2) If this is the case, and the two keep asking eachother to paint over and over, .....
    see above answer

  • Custom painting/ graphics in a panel

    Ten Duke Dollars for whoever gives the best high level solution for my problem.
    I'm writing a small application that displays music notation on screen and lets the user move the notes vertically to the desired locations on the staves. The user can then do various kinds of analysis on each example. The analysis stuff is done, but I'm having trouble finding an approach that will work for the graphics.
    My basic approach so far is to subclass JPanel and use it to handle all the custom painting. I'm planning to add all needed JPEG's to JLabels. Some of the images (e.g. treble and bass clef images) will always be in a fixed location, while others (note images) will move vertically when the user drags them. For the lines on the staves and the measure lines, I'm planning to use g.drawLine.
    The following questions occur to me:
    1. How will I prevent the note images from hiding the lines? Will I need to make the images transparent GIFs or something? Or can I set some layering property in the JPanel to build up a layered drawing?
    2. to detect mouse events, should I attach mouse listeners to my panel, or to each label that contains a note image? (I considered using Ellipse objects for the note heads and lines for the stems, but this will not give me a high enough quality of image.)
    3. I will probably need to use absolute positioning in the panel class rather than FlowLayout or whatever, but I'm having trouble getting rid of the layout manager. Can you give me a few lines of code to do this?
    4. Is my overall approach correct? Is there a better, easier way to accomplish what I'm trying to do?
    thanks,
    Eric

    >
    The following questions occur to me:
    1. How will I prevent the note images from hiding the
    lines? Will I need to make the images transparent GIFs
    or something? Or can I set some layering property in
    the JPanel to build up a layered drawing?If you are going to use images (probably BufferedImages), their Transparency will probably be BITMASK or TRANSLUSCENT.
    2. to detect mouse events, should I attach mouse
    listeners to my panel, or to each label that contains
    a note image? (I considered using Ellipse objects for
    the note heads and lines for the stems, but this will
    not give me a high enough quality of image.)I don't think using JLabel objects is a good idea. Instead of add labels to a panel, I would define a custom JComponent that did its own painting in paintComponent.
    >
    3. I will probably need to use absolute positioning in
    the panel class rather than FlowLayout or whatever,
    but I'm having trouble getting rid of the layout
    manager. Can you give me a few lines of code to do
    this?If you follow my last comment, your component isn't being used as a container, so this is not relevant.
    >
    4. Is my overall approach correct? Is there a better,
    easier way to accomplish what I'm trying to do?
    thanks,
    EricCheck out forum Java 2D. That's where this topic belongs. You also need to learn the 2D API. Search for some text book references in that forum.
    From the Imipolex G keyboard of...
    Lazlo Jamf

  • Stuck with the paint and repaint methods

    I am supposed to create a JApplet with a button and a background color. When the button is clicked the first time a word is supposed to appear (I got that part), when the button is clicked the second time the word is supposed to appear again in a different color and in a different location on the Applet (I got that part).
    The problem is that the first name is supposed to disappear when the second word appears. So I know I have to repaint the screen when the button is clicked the second time and draw the first string in the same color as the background color to make it invisible.
    My problem is I am not sure how I can code to apply different settings each time the button is clicked. Can anyone help? Please let me know if my explanation sucks. I will try to explain better. However here is the code I have so far. I added a counter for the button just for testing purposes.
    I just need some hints on what to do and if there is a easier way than using that if statement please let me know. I probably make it harder than it is.
    Thanks in advance and Merry Christmas.
    import javax.swing.*;
       import java.awt.*;
       import java.awt.event.*;
        public class DisplayMyName extends JApplet
        implements ActionListener
          String myName = "DOG";
          String myName1 = "DOG";
          JButton moveButton = new JButton("Move It");
          Font smallFont = new Font("Arial", Font.BOLD, 12);
          Font largeFont = new Font("Lucida Sans", Font.ITALIC, 20);
          int numClicks = 0;
          JLabel label = new JLabel("Number of button clicks:" + numClicks);
           public void init()
             Container con = getContentPane();
             con.setBackground(Color.RED);
             con.setLayout( new FlowLayout() );
             con.add(moveButton);
             con.add(label);
             moveButton.addActionListener(this);
           public void paint(Graphics g)
             numClicks++;
             label.setText("Number of button clicks: " + numClicks);
             if (numClicks == 2)
             { g.setFont(smallFont);
                g.setColor(Color.BLUE);
                g.drawString(myName, 50, 100);
                   else
             if (numClicks == 3)
             { g.setFont(largeFont);
                g.setColor(Color.YELLOW);
                g.drawString(myName, 100, 200);
           public void actionPerformed(ActionEvent move)
             repaint();
       }

    You're putting your program logic in the paint method, something you should not do. For instance, try resizing your applet and see what effect that has on number of button clicks displayed. This is all a side effect of the logic being in the paint method.
    1) Don't override paint, override paintComponent.
    2) Don't draw/paint directly in the JApplet. Do this in a JPanel or JComponent, and then add this to the JApplet. In fact I'd add the button, the and the label to the JPanel and add the label to the JApplet's contentPane (which usually uses BorderLayout, so it should fill the applet).
    3) Logic needs to be outside of paint/paintComponent. the only code in the paintComponent should be the drawing/painting itself. The if statements can remain within the paintComponent method though.
    4) When calling repaint() make sure you do so on the JPanel rather than the applet itself.
    For instance where should numClicks++ go? Where should the code to change the label go? in the paint/paintComponent method? or in the button's actionlistener? which makes more sense?
    Edited by: Encephalopathic on Dec 24, 2008 9:37 AM

  • Calling a method within paint

    Greetings. I am currently writing my major project for computer science. I am just here to ask one question. I called a method from within paint which made my program spit the dummy. The method was supposed to draw a question on the screen but instead it just skipped through many questions as paint was called multiple times. Why would paint have been called multiple times?
    Thankyou

    Thanks for replying. Would you be able to explain
    that in simpler terms?Hardly possible. Paint is painting the component to the screen. Sometimes, what was painted has to be refreshed - if the window moved or was minimized, if something was dragged across it or some other reasons. Whenever that happens, pant() is called.
    By the way, if oyu use Swing, you should not override paint() but paintComponent() to draw something.
    I am studying java without
    swing. I solved the problem by adding a start button
    and putting the method call into action performed,
    but i'm just wondering why it would have mattered
    that it was in paint.Because as you pointed out, paint is called arbitrarily whenever it's needed. Furthermore, it's not the view's task to modify the data model (see MVC pattern) which it did in your case.

  • Confused about painting in Java2D

    HI, I'm trying to get a simple app - note I don't want to do this in an Applet - that displays some text on screen and then exits when a key is pressed. I don't know how to get it to paint if I just call paint() from the class constructor it complains about the parameter.
    paint(java.awt.Graphics) cannot be applied to ()
    If I try to call paint from the calling class I get the same problem.
    Do I need a JPanel and if so, what for? Where should I use paint() and not paintComponent() or vice versa and what's the difference? I've seen pieces of code which draw without a JPanel or JFrame but I don't know how those work. Here's what I've got so far:
    public class Controller
        public CallingClass
         Intro intro = new Intro();
        public static void main(String[] args)
         Controller callingClass = new CallingClass;
    import java.awt.*;
    import java.awt.Color;
    public class Intro
        public  Intro()
         paint();
        public void paint(Graphics g)
            setBackgrond(Color.black);
            g.setColor(Color.green);
            g.drawString("Blah",512,20);
            g.drawString("Blah",20,60);
            g.drawString("Blah",20,80);
            g.drawString("Blah",20,120);
            g.drawString("Blah",20,140);
            g.drawString("Blah",20,160);
            g.drawString("Blah",20,180);
            g.drawString("Press F  to start or q to quit",20,200);
        public void keyDown(Event e, int key)
            switch(key)
                case 'F':
                    //MainClass mainClass = new MainClass();   //ignore this
                    break;
                case 'Q':
                    System.exit(0);
                    break;
    }I know I sound like a noob but I'm having trouble finding this sort of information.

    I just used the keyDown()
    method so I wouldn't have to override the methods for
    the KeyListener interface.Well you should still use a KeyListener.
    I followed BinaryDigit's
    advice, but I'm still confused, do I need both a
    JFrame and JPanel to draw to the screen?You should have your Intro class extend JPanel (and override paintComponent(), not paint()). You should then use that JPanel as the content pane in a JFrame. And remember to call repaint(), not paint() or paintComponent().

  • Custom painting in JFC

    I have an app that does custom painting in a extended JWindow, however, when I add controls (an extended JButton that does custom painting) the entire window, not including any components turns gray. This happens if I use paint or paintComponent. I am starting to think that the delegate UI is causing a problem, this is because if I remove the paintComponents, I get the image as usual. Any ideas???
    A code snippet shows the gist
    class sWindow extends JWindow {
    public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.drawImage(mainform, null, 0, 0);
    paintComponents(g);
    class sButton extends JButton {
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    switch(state) {
    case DEFAULT:
    g2.drawImage(defaultImage, 0, 0, getSize().width, getSize().height, this);
    break;
    case PRESSED:
    g2.drawImage(pressedImage, 0, 0, getSize().width, getSize().height, this);
    break;
    case HIGHLIGHTED:
    g2.drawImage(hilightedImage, 0, 0, getSize().width, getSize().height, this);
    break;
    case DISABLED:
    g2.drawImage(disabledImage, 0, 0, getSize().width, getSize().height, this);
    break;
    }

    Hi,
    You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
    JRG

Maybe you are looking for