PaintComponent() - Problem

Hi,
I have a tabbed pane with custom JPanels on each pane. Each of these custom panels has it's own paintComponent() - method to display custom graphics.
Problem: Sometimes hidden JPanels are also painted, so that they are displayed on a the wrong pane. After selecting another pane and then the original one, everythings alright again.
What can I do?

ah, no,
i have to use the isShown() method before painting anything.

Similar Messages

  • SwingUtilities.paintComponent - problems with painting childs of components

    Maybe this question was mention already but i cant find any answer...
    Thats what could be found in API about method paintComponent in SwingUtilities:
    Paints a component c on an arbitrary graphics g in the specified rectangle, specifying the rectangle's upper left corner and size. The component is reparented to a private container (whose parent becomes p) which prevents c.validate() and c.repaint() calls from propagating up the tree. The intermediate container has no other effect.
    The component should either descend from JComponent or be another kind of lightweight component. A lightweight component is one whose "lightweight" property (returned by the Component isLightweight method) is true. If the Component is not lightweight, bad things map happen: crashes, exceptions, painting problems...
    So this method perfectly works for simple Java components like JButton / JCheckbox e.t.c.
    But there are problems with painting JScrollBar / JScrollPane (only background of this component appears).
    I tried to understand why this happens and i think the answer is that it has child components that does not draw at all using SwingUtilities.paintComponent()
    (JScrollBar got at least 2 childs - 2 buttons on its both sides for scroll)
    Only parent component appears on graphics - and thats why i see only gray background of scrollbar
    So is there any way to draw something like panel with a few components on it if i have some Graphics2D to paint on and component itself?
    Simple example with JScrollPane:
    JScrollPane pane = new JScrollPane(new JLabel("TEST"));
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    SwingUtilities.paintComponent(g2d, pane, new JPanel(), 0, 0, 200, 200);Edited by: mgarin on Aug 11, 2008 7:48 AM

    Well the thing you advised could work... but this wont be effective, because i call repaint of the area, where Components painted, very often..
    So it will lag like hell when i make 10-20 repaints in a second... (for e.g. when i drag anything i need mass repainting of the area)
    Isnt there any more optimal way to do painting of the sub-components?
    As i understand when any component (even complicated with childs) paints in swing - its paint method calls its child components paint() to show them... can this thing be reproduced to paint such components as JScrollPane?

  • 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

  • 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

  • Redraw order problems with paintComponent

    hi,
    i've got this test code below which is simply meant to overlay the scrolling transparent text "HELLO" a few times on top of a normal component
    my problem is that the image in the panel, is seemingly being redrawn after the text, when it should be drawn as part of the call to super.paintComponent(g)
    is having a thread calling repaint() every few milliseconds is the right way to be doing this in the first place??
    any help really appreciated,
    asjf
    ps. pls ignore the dodgy positioning of text, and calculations of widths etc :)
    import javax.swing.*;
    import java.awt.*;
    import java.net.URL;
    class AnimTest extends JPanel {
       Font myFont;
       Color myColor;
       int x=0;
       AnimTest(URL u){
          super(new BorderLayout(8,8));
          add(new JLabel("Demo text: ajsk sdjfkl dsjfks jd aisuda siu"), BorderLayout.CENTER);
          add(new JLabel(new ImageIcon(u)), BorderLayout.EAST);
          setOpaque(true);
          setBackground(Color.white);  
          myColor = new Color(255,0,0,128);
          myFont = new Font("Dialog",Font.BOLD,14);
          new Thread(new Runnable(){
             public void run() {
                try {
                   while(true) {
                      repaint();
                      Thread.sleep(25);
                      x++;
                }catch(InterruptedException e) {
                   e.printStackTrace();
          }).start();
       public void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.setColor(myColor);
          g.setFont(myFont);
          int width = 3*(getWidth()/2);
          int mid = getHeight()/2 + 10; // sort out later
          for(int i=0; i<width; i+=width/5)
             g.drawString("HELLO",((x+i) % width)-(width/5),mid);
       public static void main(String [] arg) throws Exception {
          URL demo = new URL("http://java.sun.com/images/duke.gif");
          JFrame frame = new JFrame("AnimTest");
          frame.getContentPane().add(new AnimTest(demo));
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.show();
    }

    hi, thanks for the reply. I am not drawing the image myself, but am expecting it to be done as part of the redraw of my classes superclass
    public void paintComponent(Graphics g) {
       super.paintComponent(g);i was expecting the call to super.paintComponent(g) to draw the contents of the JPanel that I've added (which it does do). The strange this is that the image attached to the JPanel is drawn on top the string that I paint after super.paintComponent(g) has completed. Am not sure how this could possibly happen without some complicated postponing of .drawImage coming into play??
    thanks,
    asjf

  • Problem in paintComponent()

    i have a java class Post which is called from another java class.The Post class extends a JPanel. The constructor of this class is called. But the paintComponent() method is not called....This problem is ocurring in some of the computers only....and no exception is getting generated...why is it so??
    public void paintComponent(Graphics g)
                super.paintComponent(g);
                        g2 = (Graphics2D)g;
            }

    i have many more functions which are called inside this paintComponent()...but the problem is that the first function itself is not getting called....and the biggest problem is that my entire code is working absolutely fine on my computer....but it is not working at all on some of the computers although i used the same setup of jdk1.5.1....why is it not working on some computers???
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.TreeMap;
    import java.util.Set;
    import java.util.Map;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.*;
    import java.awt.event.*;
    public class Post extends JPanel
         JFrame jf;
         Graphics2D g2;
            Document dom;
         Element root;
    Post()
         jf = new JFrame();     
         Toolkit kit = Toolkit.getDefaultToolkit();
         Dimension screenSize = kit.getScreenSize();
         int screenWidth = screenSize.width;
         int screenHeight = screenSize.height;
         this.setBorder(BorderFactory.createLineBorder (Color.blue, 2));
               this.setBackground(Color.WHITE);
         this.setLayout(null);
         jf.setBounds(0, 0, screenWidth, screenHeight-29);
         jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         jf.setTitle("Generated Class Diagram");
         jf.setVisible(true);
         jf.setMenuBar(mbar);
         jf.add(this);
         Dimension d=jf.getSize();
         System.out.println("wid :" +d.width);
         System.out.println(" hei :" +d.height);
         public void paintComponent(Graphics g)
                super.paintComponent(g);
                        g2 = (Graphics2D)g;
                createDomRootElement();
    void createDomRootElement()
            File docFile = new File("..\\uml\\xml file\\classdiagram.xml");   //
            try {
                DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                dom= db.parse(docFile);
                  } catch (java.io.IOException e)
                System.out.println("Can't find the file");
                } catch (Exception e)
                System.out.print("Problem parsing the file.");
               root = dom.getDocumentElement();
    }

  • PaintComponent method problems...

    Hi, I am developing an game application ( just for fun ) and I have a huge problem with paintComponent method. I Have a class ImagePanel that extends JPanel class. The ImagePanel class overrides the paintComponent method and paintChildren method ( since i have added components inside the JPanel also these must be painted ). The ImagePanel is instantied in my main class IntroView which extends JFrame where it's added. Now when the IntroPanel is created i have noticed that the paintComponent and paintChildren method is called all over again . I Have a soundclip playing in background in it's own thread and this continously paintComponent method call causes the sound clip to break off in few seconds. I Have tried to use JLabel instead of JPanel, but then the image is not shown( alltougth the methods are called only once ). I Have also tried next code to get rid of continous paintComponent call
    ...from ImagePanel class
    ImagePanel extends JPanel.....
    public final void paintComponent( Graphics g )
    if( firstTime )
    super.paintComponent( g );
    g.drawImage( myImage, 0, 0, this );
    firstTime = false;
    public final void paintChildrens( Graphics g )
    if( paintChildren )
    super.paintChildren( g );
    add( startLabel );
    add( optionsLabel );
    paintChildren = false;
    public boolean isOpaque()
    return true;
    Now the paintComponent and paintChildren is called only once. There is still a "little problem" since the paintComponent doesen't paint the image, it paints only the background( I think g.drawImage(...) didint have time to paint the image? ). Also the labels added in paintChildren method are not shown. Sounds paly now just fine.This situation makes me grazy. Please consult me with this problem.....i can surely send also the whole source if needed. There is no effect if I change isOpaque to true or false.

    Hi,
    Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

  • Problems with basic Java JPanel animation using paintcomponent

    okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
    public void paintComponent(Graphics g){
    Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
    Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
    if (!backgroundIsDrawn){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, xi, y, this);
    backgroundIsDrawn=true;
    else
    for (int i=xi; i<500; i++){
    g.drawImage(simpleBG, 0, 0, this);
    g.drawImage(mMan, i, y, this);
    try{
    Thread.sleep(10);
    } catch(Exception ex){System.out.println("damn");}
    The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
    any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

    fysicsandpholds1014 wrote:
    even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
    and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
    I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
    Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class AnimationDemo2 extends JPanel {
      // use a publicly available sprite for this example
      private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
                "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
      private static final int SIDE = 600;
      private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
      // timer delay: equivalent to the Thread.sleep time
      private static final int TIMER_DELAY = 20;
      // how far to move in x dimension with each loop of timer
      public static final int DELTA_X = 1;
      // holds our sprite image
      private BufferedImage img = null;
      // the images x & y locations
      private int imageX = 0;
      private int imageY = SIDE/2;
      public AnimationDemo2() {
        setPreferredSize(APP_SIZE);
        try {
          // first get our image
          URL url = new URL(SPRITE_PATH);
          img = ImageIO.read(url);
          imageY -= 3*img.getHeight()/4;
        } catch (Exception e) { // shame on me for combining exceptions :(
          e.printStackTrace();
          System.exit(1); // exit if fails
        // create and start the Swing Timer
        new Timer(TIMER_DELAY, new TimerListener()).start();
      // all paintComponent does is paint -- nothing else
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        int w = getWidth();
        int h = getHeight();
        g.fillRect(0, h/2, w, h);
        if (img != null) {
          g.drawImage(img, imageX, imageY, this);
      private class TimerListener implements ActionListener {
        // is called every TIMER_DELAY ms
        public void actionPerformed(ActionEvent e) {
          imageX += DELTA_X;
          if (imageX > getWidth()) {
            imageX = 0;
          // ask JVM to paint this JPanel
          AnimationDemo2.this.repaint();
      // code to place our JPanel into a JFrame and show it
      private static void createAndShowUI() {
        JFrame frame = new JFrame("Animation Demo");
        frame.getContentPane().add(new AnimationDemo2());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      // call Swing code in a thread-safe manner
      public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowUI();
    }

  • Is that a problem of SwingUtilities.paintComponent() method ?

    Hello Everyone,
    I have succeeded to write the HTML contents of jeditorpane to buffered image. But the output image shows everything except the Radio Buttons,Text Boxes and Buttons on that HTML page. Please suggest me where might be the problem.
    Compare two images,
    1> one which is displayed on a jframe, which displays Radio button, Text Box, Submit Button.
    2> another one which is created on C: drive, named as out.jpg. This image doesn't have Radio button, Text Box, Submit Button.
    Note: I don't want to display an image anywhere. Not on even JFrame. [ I have implemented the code for displaying just to show you the difference in images]
    Thanks and Regards.
    import java.awt.image.BufferedImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.awt.*;
    import java.net.MalformedURLException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.JEditorPane;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class HTMLPageToImage
            static class Kit extends HTMLEditorKit
                public Kit() {
                public Document createDefaultDocument()
                    HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
                    doc.setTokenThreshold(Integer.MAX_VALUE);
                    doc.setAsynchronousLoadPriority(-1);
                    return doc;
               public ViewFactory getViewFactory() {
                    return new SynchronousImageViewFactory(super.getViewFactory());
                static class SynchronousImageViewFactory implements ViewFactory {
                    ViewFactory impl;
                    SynchronousImageViewFactory(ViewFactory impl) {
                        this.impl = impl;
                    public View create(Element elem) {
                        View v = impl.create(elem);
                        if((v != null) && (v instanceof ImageView)) {
                            ((ImageView)v).setLoadsSynchronously(true);
                        return v;
        public static BufferedImage getCapturedImage(String filePath, int width, int height)
            JEditorPane jep = new JEditorPane();
            Kit kit = new Kit();
            //String str = "file:" + filePath;
            String str = "http://" + filePath;
            URL url;
            try {
                url = new URL(str);
                try {
                    jep.setEditorKit(kit);
                    jep.setEditable(false);
                    jep.setContentType("text/html");
                    jep.setPage(url);
                    System.out.println("jep size : " + jep.getPreferredSize());
                    width = jep.getPreferredSize().width;
                    height = jep.getPreferredSize().height;
                        //--- Just to show that Radio Buttons, Text Box, Submit Buttons are displayed properly ----
                        JPanel p = new JPanel();
                        p.setVisible(true);
                        p.setSize(width,height);
                        p.add(jep);
                        JFrame f = new JFrame();
                        f.setSize(1024,768);
                        f.setVisible(true);
                        f.add(p);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D bufferedImageGraphics2D = bufferedImage.createGraphics();
            Container c = new Container();
            SwingUtilities.paintComponent(bufferedImageGraphics2D, jep, c, 0, 0, width, height);
            bufferedImageGraphics2D.dispose();
            return bufferedImage;
        public static void main(String[] args) throws FileNotFoundException,IOException
            //BufferedImage image = HTMLPageToImage.getCapturedImage("E:\\Texture\\my.html", 1024, 768);
            BufferedImage image = HTMLPageToImage.getCapturedImage("www.google.com", 1024, 768);
            com.sun.image.codec.jpeg.JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(new FileOutputStream("c:\\out.jpg"));
            enc.encode(image);
            System.out.println("See the image out.jpg created on C: drive ! ");
    }Edited by: nikhil_shravane on Jun 27, 2008 6:42 AM
    Edited by: nikhil_shravane on Jun 27, 2008 7:34 AM
    Edited by: nikhil_shravane on Jun 27, 2008 8:12 AM

    Hi Again, TextBox, TextArea and buttons are visible only when I place the jeditorpane with an HTML on a JPanel and JFrame before writing the captured image on a buffered Image. But when I directly captures the image from jeditorpane without placing it on JPanel and JFrame, the captured image doesn't show the TextBox, TextArea and Buttons. I want to capture the HTML image and write it directly to buffered Image. For that I don't want to open JPanel and JFrame. I can write the captured HTML from jeditorpane directly to the buffered image, but that image doesnt have tha TextBox, TextArea, Buttons and Tables. Following is the method which writes the captured HTML from jeditorpane directly to the buffered image.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    * @author Nikhil Shravane
    public class WebImage {
        JEditorPane jep;
        Container c;
        BufferedImage bufferedImage ;
        Graphics2D bufferedImageGraphics2D;
        Object object;
        Kit kit;
         WebImage()     {
             object = new Object();
        static class Kit extends HTMLEditorKit {
                // Override createDefaultDocument to force synchronous loading
                public Document createDefaultDocument() {
                        HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
                        doc.setTokenThreshold(Integer.MAX_VALUE);
                        doc.setAsynchronousLoadPriority(-1);
                        return doc;
        public synchronized BufferedImage getCapturedImage(String src, int width, int height)    {
            jep = new JEditorPane();
            kit = new Kit();
            jep.setEditorKit(kit);
            jep.setEditable(false);
            jep.setMargin(new Insets(0,0,0,0));
            synchronized(object)        {
                try {
                    jep.setPage(src);
                } catch (IOException ex) {
                    ex.printStackTrace();
                height = width;//  * jep.getPreferredSize().height / jep.getPreferredSize().width;
                bufferedImage = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_RGB);
                bufferedImageGraphics2D = bufferedImage.createGraphics();
                c = new Container();
                SwingUtilities.paintComponent(bufferedImageGraphics2D, jep, c, 0, 0, (int)width, (int)height);
                bufferedImageGraphics2D.dispose();
            JLabel label = new JLabel(new ImageIcon(bufferedImage));
            JOptionPane.showMessageDialog(null, label, "clipped image",
                                              JOptionPane.PLAIN_MESSAGE);
            return bufferedImage;
        public static void main(String[] args) {
            WebImage webImage = new WebImage();
                BufferedImage image = webImage.getCapturedImage("http://www.google.com/", 640, 480);
                //BufferedImage image = webImage.getCapturedImage("file:\\E:\\Texture\\my.html", 640, 480);
                // you can write this buffered image anywhere...
    }Above code will capture the HTML image and write it to buffered image and returns the buffered image.
    Please Suggest me the way, so that I can see the Buttons, TextBox, TextArea, Tables etc.
    Thanks and Regards,
    Nikhil

  • Problem after over riding paintComponent() method

    I am over riding the paintComponent() method for a button to show the text in 2 lines. But when I invoke setEnabled(false) on the button, the button is getting disabled but the text is not.
    Could any one please let me know how to do that.
    The code for the paintComponent() method is pasted for reference
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    int w = getWidth();
    int h = getHeight();
    FontMetrics fm = g.getFontMetrics();
    int textw1 = fm.stringWidth(text1);
    int textw2 = fm.stringWidth(text2);
    FontRenderContext context = g2.getFontRenderContext();
    LineMetrics lm = getFont().getLineMetrics(text1, context);
    int texth = (int)lm.getHeight();
    prefHeight = texth;
    int x1 = (w - textw1) / 2;
    int x2 = (w - textw2) / 2;
    int th = (texth * 2);
    int dh = ((h - th) / 2);
    int y1 = dh + texth - 3;
    int y2 = y1 + texth;
    // Draw texts
    g.setColor(getForeground());
    g.drawString(text1, x1, y1);
    g.drawString(text2, x2, y2);
    regards,
    shantanu

    Hi,
    Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

  • Problem with overridding JButton paintComponent

    I have written an extension of JButton that simply paints an octagon on the button:
    package myPackage;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Polygon;
    import javax.swing.JFrame;
    import java.io.Serializable;
    public class MyButton extends JButton implements Serializable {
    public MyButton() {
    super();
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int[] xPoints = new int[9];
    int[] yPoints = new int[9];
    int endX, beginX, endY, beginY;
    super.paintComponent(g);
    int w = getSize().width;
    int h = getSize().height;
    // get the smaller of the two
    int min = (w > h ? h : w);
    System.out.println(w + ", " + h + ", " + min + ", " + getLocation());
    beginX = getLocation().x + (w - min) / 2;
    endX = beginX + min;
    beginY = getLocation().y + (h - min) / 2;
    endY = beginY + min;
    System.out.println(beginX + ", " + beginY + ", " + endX + ", " + endY);
    // Set the proper points to draw a 8 sided polygon
    // These formulas are based on where a point should be
    // proportionally relitive to the starting point (x1,y1)
    // and the ending point (x,y)
    xPoints[0] = (endX - beginX) / 4 + beginX;
    xPoints[1] = (endX - beginX) * 3 / 4 + beginX;
    xPoints[2] = endX;
    xPoints[3] = endX;
    xPoints[4] = (endX - beginX) * 3 / 4 + beginX;
    xPoints[5] = (endX - beginX) / 4 + beginX;
    xPoints[6] = beginX;
    xPoints[7] = beginX;
    xPoints[8] = (endX - beginX) / 4 + beginX;
    yPoints[0] = beginY;
    yPoints[1] = beginY;
    yPoints[2] = (endY - beginY) / 4 + beginY;
    yPoints[3] = (endY - beginY) * 3 / 4 + beginY;
    yPoints[4] = endY;
    yPoints[5] = endY;
    yPoints[6] = (endY - beginY) * 3 / 4 + beginY;
    yPoints[7] = (endY - beginY) / 4 + beginY;
    yPoints[8] = beginY;
    Polygon p = new Polygon(xPoints, yPoints, 8);
    g.setColor(Color.RED);
    g.fillPolygon(p);
    public static void main(String args[]) {
    JFrame jf = new JFrame("Stop Button");
    // change false to true to see it in a JPanel
    if (false) {
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    jp.add(new MyButton(), BorderLayout.NORTH);
    jf.add(jp);
    } else {
    jf.add(new MyButton());
    jf.setSize(new Dimension(100, 100));
    jf.setVisible(true);
    This works fine ... until I reference it from a larger program. I used Netbeans 6.1 GUI builder for a more complicated structure. When I run the larger app ... the button is blank. Here's the main part of the code that the builder generated:
    javax.swing.GroupLayout topPanelLayout = new javax.swing.GroupLayout(topPanel);
    topPanel.setLayout(topPanelLayout);
    topPanelLayout.setHorizontalGroup(
    topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(topPanelLayout.createSequentialGroup()
    .addContainerGap()
    .addGroup(topPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addGroup(topPanelLayout.createSequentialGroup()
    .addComponent(stopButton, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) <---------------------
    .addComponent(tickerField))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(srButton)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(channelButton)
    .addGap(14, 14, 14)
    .addComponent(measurementPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addContainerGap())
    I'm using JDK 1.6, and don't have a lot of experience chasing down Swing problems. Could you please make some suggestions as to what I'm doing wrong?? The print statements show me that the paintComponent method is being reached when I move the mouse over the button, but nothing gets drawn!!!
    Thanks in advance for any help you can provide.
    Dwight

    Here's some of your code,
    if (false) {
          JPanel jp = new JPanel();
          jp.setLayout(new BorderLayout());
          jp.add(new MyButton(), BorderLayout.NORTH);
          jf.add(jp);
    } else {
         jf.add(new MyButton());
    jf.setSize(new Dimension(100, 100));In both cases your button is being added to a container using BorderLayout. When the container resizes so to does the button. That's why this works,
    public MyButton() {
         super();
    public void paintComponent(Graphics g) {
         int w = getSize().width;
         int h = getSize().height;
    }Initially MyButton has zero size, but when the frame's size is set the BorderLayout will change the size of MyButton.
    However, with a more complicated GUI and GroupLayout the button may not necessarily change size when the frame's size is set. It may remain at its preferred size - which is zero or close to it (since it has no text or icon). So now all of a sudden getWidth() and getHeight() return zero (or close to it). You need to set an appropriate preferred size
    public MyButton() {
         super();
         setPreferredSize(...);  //<--- add a line like this
    }

  • Problem while encoding JPEG image from JFrame paintComponent in a servlet

    Hello!
    I m developing webapplication in which I made one servlet that calls JFrame developed by me, and then encoding into JPEG image to send response on client browser. I m working on NetBeans 5.5 and the same code runs well. But my hosting server is Linux and I m getting the following error:
    java.awt.HeadlessException:
    No X11 DISPLAY variable was set, but this program performed an operation which requires it.
         java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159)
         java.awt.Window.<init>(Window.java:406)
         java.awt.Frame.<init>(Frame.java:402)
         java.awt.Frame.<init>(Frame.java:367)
         javax.swing.JFrame.<init>(JFrame.java:163)
         pinkConfigBeans.pinkInfo.pinkModel.pinkChartsLib.PinkChartFrame.<init>(PinkChartFrame.java:36)
         pinkConfigBeans.pinkController.showLastDayRevenueChart.processRequest(showLastDayRevenueChart.java:77)
         pinkConfigBeans.pinkController.showLastDayRevenueChart.doGet(showLastDayRevenueChart.java:107)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.25 logs.
    I m building the application in NetBeans and when runs then it runs well, even while browsing from LAN. But when I place the web folder creted under buil directory of NetBeans in the Tomcat on Linux, then it gives above error.
    Under given is the servlet code raising exception
    response.setContentType("image/jpeg"); // Assign correct content-type
    ServletOutputStream out = response.getOutputStream();
    /* TODO GUI output on JFrame */
    PinkChartFrame pinkChartFrame;
    pinkChartFrame = new PinkChartFrame(ssnGUIAttrInfo.getXjFrame(), ssnGUIAttrInfo.getYjFrame(), headingText, xCordText, yCordText, totalRevenueDataList);
    pinkChartFrame.setTitle("[::]AMS MIS[::] Monthly Revenue Chart");
    pinkChartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    //pinkChartFrame.setVisible(true);
    //pinkChartFrame.plotDataGUI();
    int width = 760;
    int height = 460;
    try {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    pinkChartFrame.pinkChartJPanel.paintComponent(g2);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(image);
    } catch (ImageFormatException ex) {
    ex.printStackTrace();
    response.sendRedirect("index.jsp");
    } catch (IOException ex) {
    ex.printStackTrace();
    response.sendRedirect("index.jsp");
    out.flush();
    Do resolve anybody!
    Edited by: pinkVag on Oct 15, 2007 10:19 PM

    >
    I m developing webapplication in which I made one servlet that calls JFrame developed by me, and then encoding into JPEG image to send response on client browser. I m working on NetBeans 5.5 and the same code runs well. But my hosting server is Linux and I m getting the following error:
    java.awt.HeadlessException: >That makes sense. It is saying that you cannot open a JFrame in an environment (the server) that does not support GUIs!
    To make this so it will work on the server, it will need to be recoded so that it uses the command line only - no GUI.
    What is it exactly that PinkChartFrame is generated an image of? What does it do? (OK probably 'generate a chart') But what APIs does it use (JFreeChart or such)?

  • Drawing with paintComponent(Graphics g) problem?

    hey, i just recently learnt from a response to previous posts not to put logic type stuff like if statements in the paintComponent method, but how do i get around the issue of drawing something different based on a boolean expression?
    i want to be able to do something like,
    paintComponent(Graphics g) {
          if(drawCircle == true) {
              g.drawCircle(....)
         }else{
              g.drawRectangle(......)
    }Yes, i know i shouldn't do that as i said i've been told NEVER to do this, but how do i work around this issue?
    thanks

    hey, i just recently learnt from a response to previous posts not to put logic type stuff like if statements in the paintComponent method, but how do i get around the issue of drawing something different based on a boolean expression?If you refer to that [my reply in your former thread|http://forums.sun.com/thread.jspa?messageID=10929900#10929900] , note that I warned you against putting business logic (+if (player.hasCollectedAllDiamonds()&&timer.hasNotTimedOut()&&allEnnemies.areDead()) { game.setState(FINISHED);}+) into your paintComponent(...) method, I didn't ask you to ban logic altogether (+if (player.hasCollectedAllDiamonds()) { Graphics.setColor(Color.GREEN); }+)
    EDIT: Oh, how pretentious I was; obviously you merely refer to [this Encephalopathic's post|http://forums.sun.com/thread.jspa?messageID=10929668#10929668], who warns against program logic in paint code; same misunderstanding though, he certainly only meant that the paintXXx's job is not to determine whether the game is over, only to render the game state (whichever it is, it has been determined somewhere else, not in painting code).

  • PaintComponent(Graphics g) problem

    hi, guys:
    Can someone tell me why my code is not work in paintComponent(Graphics g)
    below are my code:
    protected void paintComponent(Graphics g)
         g.drawLine(0, 0, 100, 100); //this line work
    this.getGraphics().drawLine(0,0,100,100); //this is not work
    I know I should use auto passed "Graphics g", however, I don't understand why this.getGraphics() can't do the same work. It should return the same Graphics object which I expected.
    Thanks for help.

    I just posted my code below (Applet), hope helpful.
    package mypackage;
    import java.applet.Applet;
    import java.awt.*;
    import javax.swing.*;
    class CatchTheCreaturePanel extends JPanel
         private Creature[] creature;
         public CatchTheCreaturePanel()
              this.setPreferredSize(new Dimension(400,300));          
         public void paintComponent(Graphics g)
              g.drawLine(50, 70, 100, 100); //work
              this.getGraphics().drawLine(0, 0, 100, 100); //not work
    public class Jmyass extends JApplet {
         private CatchTheCreaturePanel the_panel;
         public Jmyass() {
              super();
         public void init() {
              the_panel=new CatchTheCreaturePanel();
         public void start() {
              this.getContentPane().add(the_panel);          
    }

  • PaintComponent()  and jave.lang.OutOfMemoryError problem

    I have a paintComponent() method that in it , I paint the GraphicsContexts with a big BufferedImage
    here is the code:
    void doPaint(){ //do some painting on the buffer
    buffer = new BufferedImage(waveForm.viewPortDim.width,waveForm.viewPortDim.height,
    BufferedImage.TYPE_4BYTE_ABGR_PRE);
    waveForm.xPanel.paintEcgBuffer(buffer);
    public void paintComponent(Graphics g){
    //super.paintComponent(g);//??
    Graphics2D g2 = (Graphics2D)g;
    try{            
    g2.drawImage(buffer,0,0,this);
    }catch(OutOfMemoryError e){
    e.printStackTrace();
    System.out.println("error "+e.getMessage());
    I use doPaint() to do some painting over the buffer but i get jave.lang.OutOfMemoryError when i try to do
    g2.drawImage(buffer,0,0,this);
    Is there a limit on the height or width of the GraphicsContexts?
    The dimension of the bufeer can be about 1400x2800 or 1400x5500.
    What can I do?
    Thank you in advance.
    Yair.

    I don't know the answer to this question, but it may help you out to examine it.
    Is it possible that your graphics card is running out of the memory to display this large image?
    You may want to just display what the screen is displaying, so clip the rest beforehand, which would lead to a smaller buffered image.

Maybe you are looking for

  • Follow-up: beasys.User vs. theory.Customer

    Hi, In one of the previous postings there was mentioned that Personalization server and Commerce Server do have user management functionality overlap. Indeed it would have been nice to have a single point of user info persistence and management. The

  • ITunes in the Enterprise

    Our CIO is pushing us to open iTunes to all employees. Why should we NOT do this?

  • Docs for plug-in error codes?

    Hi, I have deployed the plug-in in iPlanet 4.1sp8 and it is proxying requests to WLS6.0sp2 Where can I find details of any errors generated by the plug-in. For example in the error shown below, where can I find the definition of "os error=146" ? [27/

  • Cannot get SSH thru DynDNS to work with Leopard

    Hi everyone, OK, I have been digging around online for a long time trying to find a clear answer to my problem, and I can't find it anywhere so I figured I would just start a new thread and see if I could get some help. I have an iMac connected wirel

  • Showing Size of Email Message While Composing

    With OS 10.4.11, the bottom of a message window would show the size of an email message I was composing. This is important when attachments may be too large to be transmitted. With OS 10.6.1, I do not see this feature. Does it still exist and, if so,