Overriding paint() method...

i have a number of JComponents which I am displaying within a JPanel.
Each JComponent holds a GIF image. Therefore, i overrode the paint(Graphics g) method of my JComponent Subclass.
Now i need to connect each JComponent with lines. I had to do this within the JPanel, so i added the following to the paint method of the JComponent:
public void paint(Graphics g) {
  //code here to display JComponent with image
  //then:
  JPanel panel = this.getParent();
  panel.getGraphics().drawLine(this.xCoordinate, this.yCoordinate, myJComponent2.getXCoordinate(), myJComponent2.getYCoordinate());
}The JPanel displays correctly when i run it. But as soon as i resize the JFrame which holds the JPanel (for example, maximise the window):
- The images of the JComponents within the JPanel remain visible
- BUT the lines i drew disappear.
Any ideas why the lines are disappeaing?
How can it be solved?
thanks

further, I would strongly argue that trying to draw on other components from the paint method of another component is a bad bad bad idea.
Calling setPreferredSize in the paint methods is also not something you should do either.
The paint method is for painting in that component only. Setting size and location and doing other layout things in the paint methods is not the appropriate place for those things.
If you want to draw on the panel, then draw on the panel in the panel, not in some child component. If you want to assign a default preferred size, do so in the constructor.

Similar Messages

  • Overriding paint method hides my status bar icons

    Hi All,
                I use setStatus on MainScreen to add some image ButtonFields to my status bar.
                It shows up fine.
                But when I override paint method , it hides all the icons I added using setStatus.
               Any clue on this ? Thnx in advance.
              Here is my paint method:
    protected void paint(Graphics graphics) {
    super.paint(graphics);
    Bitmap image = ImageUtility.loadBitMap("header2.jpg");
    graphics.drawBitmap(0, 0, 500, image.getHeight(), image, 0, 0);
    for(int i =0; i < 5; i++ ){
    fieldList.drawListRow(fieldList, graphics, i, 50 + (i*50), 20);
    protected void paint(Graphics graphics) {         
             Bitmap image = ImageUtility.loadBitMap("header2.jpg");
             graphics.drawBitmap(0, 0, 500, image.getHeight(), image, 0, 0); for(int i =0; i < 5; i++ ){           fieldList.drawListRow(fieldList, graphics, i, 50 + (i*50), 20);
    Aranya

    Try Calling super.paint at the start or at the end ... it should do the trick

  • Paint() method is in infinite loop when focus is set to JTextPane

    Hi All,
    I am creating one JScrollPane, JPanel and JTextPane. JPanel is added to JScrollPane and JTextPane is added to JPanel. If I override paint() method in JPanel, its in infinite loop. I don't know why it is behaving like this. Can anyone solve my problem. Since, I am doing so much drawings in paint() method, its getting to slow.
    Here is the code what I wrote.
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestTextPane1 extends JFrame {
         JPanel panel;
         JScrollPane pane;
         public TestTextPane1() {
              panel = new JPanel(new BorderLayout()) {
                   public void paint(Graphics g) {
                        super.paint(g);
                        System.out.println("inside paint");
              JTextPane textPane = new JTextPane();
              panel.add(textPane);
              pane = new JScrollPane(panel);
              getContentPane().add(pane);
              setSize(300, 200);
              setVisible(true);
         public static void main(String [] args) {
              new TestTextPane1();
    Any help will be useful for me.
    Regards
    Kishore.

    What are you trying to do? You are adding the textPane to the panel and then overriding the paint() method. The textPane will never be painted if you do this.
    In Swing, you should override the paintComponent() method, not the paint() method. See the Swing tutorial on Painting:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to read the "Working With Graphics" link at the bottom.

  • Working in a jFrame - overriding paint

    Hey guys, currently I'm programming a game in Java.
    I use a JFrame with a CustomJPanel.
    In my CutomJPanel i override the Paint method.
    This is working well, i have something about 200FPS, but it's still simple.
    Today I read a Article about JavaFX and saw it has GPU Support.
    So if i use a CustomJFXPanel in my JFrame instead, are I just getting the advantage of GPU-Support by it?
    Or do i lose the benefits be overriding the Paint Method?

    This question cannot be answered in a simple yes/no way. It depends on the kind of graphics operation that you want to perform. In some areas JavaFX is slower than good old AWT. So it depends.

  • Override scrollpane methods?

    problem: I create a time series line graph in a buffered image that has a variable width, sometimes the width is in the millions of pixels and the resulting buffered image is too large to fit into memory, even if I increase the available memory with the -Xmx1024m option. I then place the a fore mentioned buffered image into a scrollpane for viewing.
    I would like to draw only the portion of the graph that is viewable and override the scrollpane methods to redraw the image based on an x position over the total width, but I haven't found anything in the API on overriding the scrollbar or the arrow buttons. Has anyone tried this, or seen and example of how to do it?
    I am aware of products such as JFreeChart and PtolemyPlot, however I don't think either is a good fit for the project and I don't have any use for their capabilities. I am open to any other suggestions on how to accomplish this goal.
    Thanks,
    Peter

    You can try to use JScrollPane by placing a custom component extending JComponent inside the scroll pane and setting it's preferred size to the required size.
    Override paintComponent method of this component and get the view rectangle from the viewport and paint only the visible area.
    If this doesn't work you might need to use JScrollBar and write the logic yourself in this case.

  • Invoking paint method in Java3D

    I have some example programs in using Java3D but none of them paints 'directly' on the canvas3D.
    if i have a class that extends a Canvas3D how would i call the paint method, can i use this method to draw a 2D polygon on my canvas? (because i wanted to have 3D and 2D objects mixed).
    how would i do this? are the points in terms of x, y, z?
    can anyone help me with this?
    thanks in advance

    I've been trying to do this myself, snd it's a right pain in the arse.
    To actually paint on the Canvas3D, when you override postRender(), you do all your stuff but it doesn't work until you call flush(). However, when I tied it (just drawing a simple rectange), my app slowed from 20fps to 2, which is a bit too much of a performance hit for my liking.
    The J3D Repository overlay is fairly easy to set up, but for some reason the polygon it draws on is about 1 unit away from where you add it, so for a 1st person thing like I'm doing, it dissapears when you get too near a wall. In the end, i have just created my own by putting a texture on a cube just in front of the viewport.

  • How to use paint method to draw in many componets.

    Hi!
    I have code like this:
    public class MainPanel extends JPanel{
       JPanel p1;
       JPanel p2;
       public MainPanel(){
           super(new BorderLayout());
           p1 = new JPanel();
           p2 = new JPanel();
           add(p1 , BorderLayout.Center);
           add(p2 , BorderLayout. West);
           setVisible(true);
    @Override
        protected void paintComponent(Graphics g) {
           g.setColor(Color.red);
           g.fillrect(10,10,10,10);
    }This code is onle an example. Supose, this code will paint black rectangle on "main panel" to which p1 and p2 are added. What should i do to be able to paint this rectangle on p1 or p2 without creating separate classes in which i will override paintComponents() method for p1 and p2. I would like to avoid creating separete classes for each panels. Is there any way to do that using one paint Components method. Thanks in advance for all respone.

    (where's Darryl when you need him?)Erm, Pete, since when did I become an expert lol?
    Lost my hard disk, its been hiccuping for a couple of weeks now. I'm running on an old 20 GB PATA with a 5GB c drive. No IDE, no offline Javadoc. I'll get a HDD in the morning, but I hope I can spin up the old disk at least once and recover the last week's "work" ... just fun stuff actually.
    Why does this code draw rectangles just for split second?repaint() (and consequently paint(), paintComponent() and other painting methods) may be called by the system any time it is detected that the component needs to be repainted. Since you do not have a override for paintComponent, it will perform its default painting and paint the entire component, wiping out your rectangle.
    For persistent drawing on a JPanel or JComponent I know only one way: override paintComponent. If you need to avoid this, you could go with morgalr's suggestion to use JLabel.
    For this you would draw the triangle/rectangle/whatever to a BufferedImage, then call label.setIcon with a new ImageIcon constructed from the BufferedImage.
    Also, avoid obtaining a Graphics reference via getGraphics. During the lifetime of a visible component, various different Graphics references may be passed into the paintComponent method, so the reference you obtain may not be current. getGraphics can also return null.
    luck, db

  • JEditorPane's paint method problem (urgent)

    Hi all, I have JEditorPane that displays HTML formatted text.
    My task requirement is to display a compay logo as static backgdound in this jeditorPane
    (The logo must be displayed always in the center nevermind the text scrolling)...
    So I overrided JEditorPane's paint method like that:
    public void paint(Graphics g) {
          super.paint(g);
          int scrolled_down = (int) ( (JViewport)this.getParent()).getViewPosition().
              getY();
          Rectangle visibleRectangle = new Rectangle();
          int width = visibleRectangle.getBounds().width;
          int height = visibleRectangle.getBounds().height;
          ImageIcon logo = IconFactory.getInstance().getIngLogoPaleIcon();
          g.drawImage(logo.getImage(), (width - logo.getIconWidth()) / 2,
                      scrolled_down + (height - logo.getIconHeight()) / 2, this);
        }But the problem is that I drow the logo over the some part of the text and the text is not visible.
    If I call super.paint(Graphics) mehtod after I drow the logo, the logo is overpainted and is not visible.
    (This logo is very pale transparent gif image).
    So my question is how can I achieve the effect this logo to be behind the text displayed in JEditorPane
    (I tried if it's possible to use CSS body attributes for static background image,but as I expected they are not supported)
    Thanks for every help in advance

    Hi!
    myEditorPane.setOpaque(false) This allows components under the EditorPane to show through.
    Thus, add a label with the desired image into a JLayeredPane, (if using in a JDeskTopPane you have acces to its FRAME_CONTENT_LAYER).
    Add your EditorPane on top of this after setting opaque to false and viola!
    Be aware that you should use caution when choosing a forground, (font ), color as the underlying image will affect how your text appears....
    :)

  • Mixing a paint method and labels???

    Hi,
    I've got a panel which has a paint method which draws various shapes, it also has someJLabels. The problem is when i add this paint method to the class then all the JLabels disappear! If i remove it then they display as normal.
    Please can someone help
    Cath

    I think you should be overriding the paintComponent() method of the JPanel.
    Here is a link to a section in the Swing tutorial titled "Painting".
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to continue with the "Working with Graphics" link at the bottom. (This will explain why you should use paintComponent() method).

  • How to add more than one paint method

    hi everyone
    I am doing a project in which i have already created a paint method but i find that there is necessity to create one more
    paint method within the same file in which i have a paint method pls tell me how to how to add a paint method how to call the repaint method
    please its very urgent

    By even suggesting that I can gather you have a horrible design of what ever you are doing--DON'T! And go back and refactor your application so you do not need or even want such a thing to happen.
    1 - paint is for use in AWT. If you are using AWT, then very well, you are at least using the right method to override. If you are using SWING, then you are totally messed up before you even arrived at this ill conceived plan of 2 paint methods.
    2 - your paint (AWT)/paintComponent (SWING) is a system called method driven by events you haven't any control over. You need to treat it as such.
    3 - your painting method should be very tight. I will bet your's is a horrid mess: overstuffed with attempted control and logic processes.
    4 - Even if you are using active rendering, your approach to 2 painting methods is horrible at best.
    If you need help in designing your process better, then post what you have and ask for help. IMO what you are doing can only lead to ugliness.

  • Overriding paint

    Is there any way to override paint only for one instance. For example, I have an image that I want to display, but after it is displayed, I want to be able to modify it. Problem is is that whenever a window is passed over the image, it updates and calls the paint method, which erases the modifications I made to the image. Is there anyway to only override the paint method only when I want to initially display the image?
    Also how would I scale down an ImageIcon so that its smaller?
    Thanks,
    Rick

    Don't modify the original image. Create a second image, paint your original image into the second image and then modify the second image. Each time paint is called, paint the second image to screen. The second one will always have your modifications, so it's safe to paint it multiple times. If you need to change the image agian, paint your original image over the first image again (to get an new clean copy) and modify it again. That's probably the most simplest thing you could do.
    You could also convert an image to a byte array, modify the byte array and use an ImageProducer (please look up that class) to paint your byte array to the screen. If you marked it as animated, you can update the byte array as often as you want and the changes will be viewable on the next call of paint.

  • Overriding paint for customizing JButton??? Shouldn't be paintComponent?

    Hi
    Shouldn't we always override paintComponent to customize the painting of a component?
    Why MetalScrollButton in javax.swing.plaf.Metal overrides paint instead of paintComponent?
    Should I override paint if I want to write my own LnF?
    Thanks.

    As is said in the online doc about paint(), "This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method, as always. A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent."
    That means you can override paint(), , but in this case you'll have to draw the border yourself... and if you have a composite custom component (a panel containing labels, for example), you will have to call the label's paintComponent() methods by yourself...
    Hope this helped,
    Regards

  • Defining the size of swing object which has overriden paint method

    Hi All!
    I have a text and I want to visualize it by my own. I use font type in the drawing which affects the painting size of the component. Before drawing I need to know the size of this component. because I want to handle mouseevents and other stuffs which need the bound size of this component. Therefore I have to set the bounds . But the size will be known at the drawing ... :(
    How can I define the exact size of this component before the drawing?
    eha

    Generally, you should override getMinimumSize() and getPreferredSize(), and let the layout manager set the size of your component. With this approach, you should be prepared for the case where your component is not given its minimum or preferred size, but some other size.
    To calculate the size that you require, you'll need to use a similar strategy to what's in your paint method. For example, you may need to calculate the width and height of your string (using the current font), within getMinimumSize() and getPreferredSize().

  • How is paint() method invoked?

    Hi
    I know this may be a silly question but I am not able to understand this concept. I have gone through some concepts of Graphics in Java and some example programs but I am not able to understand what invokes Paint(Graphics g) method. As I dont get this, I am not able to write a program where if I press a Draw button, it draws a line.
    I also went through the following link "http://java.sun.com/docs/books/tutorial/2d/overview/index.html" but I did not get my answer.
    Please help me.
    lakki

    Swing determines when a component needs to be repainted. It has a class called the RepaintManager which manages this. You can force the repainting of a component by using the repaint() method.
    You should never override the paint() method. Custom painting should be done by overriding the paintComponent() method in Swing. Read the Swing tutorial on "Custom Painting":
    http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

  • Is not abstract and does not override abstract method actionPerformed

    I dont how to corr. Please help!! and thank you very much!!
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class test extends JFrame implements ActionListener, ItemListener
              private CenterPanel centerPanel;
              private QuestionPanel questionPanel;
              private ButtonPanel buttonPanel;
              private ResponsePanel responsePanel;
              private JButton b1,b2,b3,b4,b5;               //Create five references to Jbutton instances
         private JTextField t1,t2,t3,t4,t5;          //Create five references to JTextField instances
              private JLabel label1;                    //Create one references to JLabel instances
              private JRadioButton q1,q2,q3;               //Create three references to JRadioButton instances
              private ButtonGroup radioGroup;               //Create one references to Button Group instances
              private int que1[] = new int[5];           //Create int[4] Array
              private int que2[] = new int[5];
              private int que3[] = new int[5];
              private String temp1, temp2, temp3, temp4, temp5, temp6, temp7, temp8, temp9, temp10,
                        temp11, temp12, temp13, temp14, temp15;
    public test (String header)
              super(header);
              Container container = getContentPane();
              label1 = new JLabel ("PLease click on your response to ");     
              q1 = new JRadioButton("I understand most of the content of this subject",true);
              add(q1);
              q2 = new JRadioButton("I see the relevance of the subject to my degree",false);
              add(q2);
              q3 = new JRadioButton("The workload in this subject is appropriate",false);
              add(q3);
              radioGroup = new ButtonGroup();               //JRadioButton belong to ButtonGroup
              radioGroup.add(q1);
              radioGroup.add(q2);
              radioGroup.add(q3);
              JPanel buttonPanel = new JPanel();
              JPanel responsePanel = new JPanel();
              JPanel questionPanel = new JPanel();
              JPanel centerPanel = new JPanel();
              b1 = new JButton ("Strongly DISAGREE");          //Instantiate JButton with text
              b1.addActionListener (this);               //Register JButtons to receive events
              b2 = new JButton ("DISAGREE");
              b2.addActionListener (this);
              b3 = new JButton ("Neither AGREE or DISAGREE");
              b3.addActionListener (this);
              b4 = new JButton ("AGREE");
              b4.addActionListener (this);
              b5 = new JButton ("Strongly AGREE");
              b5.addActionListener (this);
              buttonPanel.setLayout(new GridLayout(5,1));
              buttonPanel.add(b1);
              buttonPanel.add(b2);
              buttonPanel.add(b3);
              buttonPanel.add(b4);
              buttonPanel.add(b5);
              t1 = new JTextField ("0",3);               //JTextField contains empty string
              t2 = new JTextField ("0",3);
              t3 = new JTextField ("0",3);
              t4 = new JTextField ("0",3);
              t5 = new JTextField ("0",3);
              t1.setEditable( false );
              t2.setEditable( false );
              t3.setEditable( false );
              t4.setEditable( false );
              t5.setEditable( false );
              responsePanel.setLayout(new GridLayout(5,1));
              responsePanel.add(t1);
              responsePanel.add(t2);
              responsePanel.add(t3);
              responsePanel.add(t4);
              responsePanel.add(t5);
              questionPanel.setLayout(new GridLayout(4,1));
              questionPanel.add(label1);
              questionPanel.add(q1);
              questionPanel.add(q2);
              questionPanel.add(q3);
              centerPanel.add(buttonPanel,BorderLayout.CENTER);
              centerPanel.add(responsePanel,BorderLayout.EAST);
              container.add(centerPanel,BorderLayout.WEST);
              container.add(questionPanel,BorderLayout.NORTH);
              q1.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que1[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp1 = String.valueOf(que1[0]);
              t1.setText(temp1);
              else if (e.getSource() == b2)     {
                   que1[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp2 = String.valueOf(que1[1]);
              t2.setText(temp2);
              else if (e.getSource() == b3)     {
                   que1[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp3 = String.valueOf(que1[2]);
              t3.setText(temp3);
              else if (e.getSource() == b4)     {
                   que1[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp4 = String.valueOf(que1[3]);
              t4.setText(temp4);
              else if (e.getSource() == b5)     {
                   que1[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp5 = String.valueOf(que1[4]);
              t5.setText(temp5);
    } //end action performed
              q2.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que2[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp6 = String.valueOf(que2[0]);
              t1.setText(temp1);
              else if (e.getSource() == b2)     {
                   que2[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp7 = String.valueOf(que2[1]);
              t2.setText(temp7);
              else if (e.getSource() == b3)     {
                   que2[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp8 = String.valueOf(que2[2]);
              t3.setText(temp8);
              else if (e.getSource() == b4)     {
                   que2[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp9 = String.valueOf(que2[3]);
              t4.setText(temp9);
              else if (e.getSource() == b5)     {
                   que2[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp10 = String.valueOf(que2[4]);
              t5.setText(temp10);
    } //end action performed
              q3.addActionListener(
                   new ActionListener(){
              public void actionPerformed( ActionEvent e )          
    {                                        //actionPerformed of all registered listeners
              if (e.getSource() == b1) {
                   que3[0] = Integer.parseInt(t1.getText()) + 1;
                   String temp11 = String.valueOf(que3[0]);
              t1.setText(temp11);
              else if (e.getSource() == b2)     {
                   que3[1] = Integer.parseInt(t2.getText()) + 1;
                   String temp12 = String.valueOf(que3[1]);
              t2.setText(temp12);
              else if (e.getSource() == b3)     {
                   que3[2] = Integer.parseInt(t3.getText()) + 1;
                   String temp13 = String.valueOf(que3[2]);
              t3.setText(temp13);
              else if (e.getSource() == b4)     {
                   que3[3] = Integer.parseInt(t4.getText()) + 1;
                   String temp14 = String.valueOf(que3[3]);
              t4.setText(temp14);
              else if (e.getSource() == b5)     {
                   que3[4] = Integer.parseInt(t5.getText()) + 1;
                   String temp15 = String.valueOf(que3[4]);
              t5.setText(temp15);
    } //end action performed
    }//end constructor test
    public void itemStateChanged(ItemEvent item) {
    //int state = item.getStateChange();
    //if (q1 == item.SELECTED)
              public class ButtonPanel extends JPanel
                   public ButtonPanel()
              public class CenterPanel extends JPanel
                   public CenterPanel()
              public class QuestionPanel extends JPanel
                   public QuestionPanel()
              public class ResponsePanel extends JPanel
                   public ResponsePanel()
    public static void main(String [] args)
         test surveyFrame = new test("Student Survey") ;
         surveyFrame.setSize( 500,300 );
         surveyFrame.setVisible(true);
         surveyFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
         }//end main
    }//end class test

    is not abstract and does not override abstract method actionPerformed
    Oh, I see that the title of your post is an error message? Ok. Well, the test class is declared as implementing an ActionListener. That means the test class must have an actionPerformed() method. Your test class apparently does not.
    It does not appear that the test class needs to implement ActionListener. You are using annonymous classes as listeners.

Maybe you are looking for

  • HP Officejet 4632 won't scan

    Printer screen says "printing alignment page" which doesn't go away even after turning off printer and computer and rebooting.  Tried to scan from program but says cannot communicate with computer.  Ran scan doctor and said driver error.  Uninstalled

  • Compressing .mov files out of Final Cut

    I'm trying to export some Final Cut projects into .mov files but I need them to be compressed to 10mb or less. How do I do that in compressor? Or is there another software application that can take existing .mov files and shrink them down? Any help i

  • Creating a double page spread - gutter accommodation??

    If I split an image across two full bleed pages in an iPhoto book does the software automatically work out the overlap in the gutter or should I put that in manually when I lay out the images? Ie should I line up the images perfectly across the gutte

  • Sleeping Clients - WLC 7.6

    We are running 7.6 on our 5508-WLC.  We have a number of issues w/ 'i-clients' when they go asleep.  From what I can tell, I need to enable the 'sleeping clients' feature (not just the session and idle timeouts). On our WLANs we use Layer-2 (WPA+WPA2

  • I'm trying to restore my ipod from recovery mode

    When trying to restore my ipod touch from recovery mode, i keep getting an error message "unknown error (1611)" Please help!!!