Self painted component

Hi All,
I've tried to make a self component to draw a card. The code like this:
public class Pg extends JComponent
    int text =0 ;
    int angle =0;
    int W = 58;
    int H = 74;
    int mw = 58-2;
    int mh = 74-2;
    int ed = 14;
    public Pg (int num)
        this.text = num;
        this.setSize(W, H);
        this.setDoubleBuffered(true);
        this.setOpaque(true);
    public void paintComponent (Graphics g)
       super.paintComponent(g);
       g.setColor(Color.white);
       g.fillRect(0,0, W,H);
       g.setColor(Color.BLACK);
       //int d = g.getFont();
       g.drawString(Integer.toString(text), mw/2,mh/2);
       drawPG(g);
    private void drawPG(Graphics g)
        if(angle == 0)
            g.drawLine(0, 0, W - ed, 0);
            g.drawLine(0, 0, 0, H);
            g.drawLine(0, H, W, H);
            g.drawLine(W, ed, W, H);
            g.drawLine(W - ed, 0, W, ed);
            g.drawLine(W - ed, 0, W - ed, ed);
            g.drawLine(W - ed, ed, W, ed);
        else if(angle == 90)
    }The drawPG() actually draws lines to become a rectangle shape, and I would like to draw the rectange and text in different rotation, any method I can do so ?

well,
I just tried the following implementation, but in some rotation, the line drawing is not straight-line. am I right? or need futher implementation.?
   public void paintComponent (Graphics g)
       super.paintComponent(g);
       Graphics2D g2d = (Graphics2D) g;
       drawPG2(g2d);
    private void drawPG2(Graphics2D g)
        if(angle == 0)
            g.translate(0, 0);
            g.rotate(0);
        else if(angle == 90)
            g.translate(H, 0);
            g.rotate(1.570796327F);
        else if(angle == 180)
            g.translate(W, H);
            g.rotate(3.141592654F);
        else if (angle == 270) {
            g.translate(0, W);
            g.rotate(4.71238898F);
        g.drawLine(0, 0, W - ed, 0);
        g.drawLine(0, 0, 0, H);
        g.drawLine(0, H, W, H);
        g.drawLine(W, ed, W, H);
        g.drawLine(W - ed, 0, W, ed);
        g.drawLine(W - ed, 0, W - ed, ed);
        g.drawLine(W - ed, ed, W, ed);
    }

Similar Messages

  • Help... how to make self-paint control

    Dear All.
    I really hope can find some helps from here as I'm a beginner in Java.
    I'm making a project , in a dialog which must contains some self-paint controls. Just like a sheet contains some cards located in from column to row. e.g 4 column, 2 row of cards.
    It must able to select, to change the text, to change color etc..
    I have no idea how to do. Could anyone give me some hints and example? what control should I extends for?
    Many thanks for help..

    I have to make a dialog, that allow user to order the cards.
    e.g. I will have 4 col x 2row cards.
    each card shows a string and some data.
    when user select the card, the background color or this card will be highlighed. etc.
    user also able to re-arrange the card order , rotation etc...

  • Paint component inside JPanel

    Hi guys,
    I will start with the original problem and get to the only option that seems possible before hardcoding everything.
    I need to draw something like a binary tree. Jtree doesn't fall into binary because it does not have the root in the center. <1;2;6;8;9>, where 6 is the root, and 1,2 are its left child's children and 8,9 are right child's children. Since I couldn't find any possible solution of customizing JTree to draw it in binary format, I am left with the following option that is a step towards hardcoding.
    Create a subclass of JPanel and paint inside it. The full hardcode method would be to draw everything right here, ie the lines and the boxes.
    But since I need to listen to box selections using mouse, I was hoping to draw the boxes using JPanel/JLabel and override their paint() method.
    So is there a way to paint components(JLabel/JPanel and lines) into a painted component (JPanel)? Note, the container JPanel is not using any layout. everything is being drawn using paint method.

    You are probably going to want to create smaller objects that handle their own painting. For example... Create an extension of JComponent that handles painting a single node. Then create the JPanel to add those to. You can even go as far as writing your own LayoutManager to handle laying the Components out in your binary layout. This is really the most effective way to do it, especially if you want to be able to detect clicks and what not. You can just add MouseListener's to the individual components than.
    Hope this helps,
    Josh Castagno
    http://www.jdc-software.com

  • Paint component scope issues

    hi i have 2 classes one is my main and the other is the paint class with void paintcomponent() inside
    how do i pass the x variable inside main class so i can use it inside the Map class
    i know you can use scope e.g. Map map = new Map(x,y); but then i have to use a constructor with
    its own repaint(); method inside but it does not work.
    i was thinking of overloading a constructor aswell so inside one constructor is nothing and in the other with the (x, y) has
    the repaint method inside but that doesn't work either.
    main class
    public class Main
    public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);
    class MainFrame extends JFrame
    private int x;
    private int y;
    // map class with paint component
    Map map = new Map(x,y);
    public MainFrame(){
    this.add(map);
    }paint class
    public class Map extends JPanel {
    private int x;
    private int y;
    public Map(){}
    public Map(int x, int y){
    this.x = x;
    this.y = y;
    repaint();
        @Override
        public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }this does not work, any ideas?
    Edited by: nicchick on Nov 25, 2008 1:00 AM

    um that wasnt exactly what i was looking for i have a better example
    what im trying to do is pass/scope private varibles from the main class to the map class
    but since you use repaint(); to call the paintcomponent override method theres no way to scope varibles like
    x and y to panel?
    this example shows what im trying to do with a mouselistener
    main
    public class Main
    public static void main(String[] args) {
    MainFrame frame = new MainFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setVisible(true);
    class MainFrame extends JFrame
    private int x;
    private int y;
    // map class with paint component
    Map map = new Map();
    // handler
    HandlerMotion handler = new HandlerMotion();
    public MainFrame(){
    this.add(map);
    map.addMouseMotionListener(handler);
         private class HandlerMotion implements MouseMotionListener
            public void mouseDragged(MouseEvent e) {
            public void mouseMoved(MouseEvent e) {
            x = e.getX();
            y = e.getY();
            new Map(x,y);
            repaint();
    }map
    public class Map extends JPanel {
        private int x;
        private int y;
        public Map(){}
        public Map(int x, int y)
        this.x = x;
        this.y = y;
        System.out.println("this is map" + x);
        System.out.println("this is map" + y);
        repaint();
        @Override
        public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawLine(0, 0, x, y);
        System.out.println("this is panel" + x);
        System.out.println("this is panel" + y);
    }

  • Paint Component

    Hi all
    i have four classes plot , plot3d, plotsurface and test
    plot is derived from JPanel and plot3d and plotsurface extend plot class
    i am trying to do a very simple operation . just making a tool bar with 2 buttons to switch between plots .
    the 2 plot classes plot3d and plotsurface just draw a line on the screen
    problem is that when the user clicks one button it doesnot show up on the screen but when the window is resized it does call paint component of the corresponding class
    can Any one explain why this is happening......
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public abstract class plot extends JPanel {
    plot()
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plot3d extends plot {
    plot3d(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(200,200,320,320);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plotsurface extends plot {
    plotsurface(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(120,120,140,140);
    package test;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics2D.*;
    import java.applet.*;
    public class Test extends javax.swing.JApplet {
    private Container container;
    public Rectangle rect;
    JPanel toolBar;
    JButton contourButton;
    JButton surfaceButton;
    JPanel toolPanel;
    public Graphics g;
    public test.plot3d graph3D;
    public test.plotsurface graphSurface;
    private int plotType=0;
    private void graph3D(Graphics2D g2)
    graph3D=new plot3d(false);
    public void graphSurface(Graphics2D g2)
              graphSurface=new plotsurface(false);
    private void changeplottoContour()
    if(plotType==0)
    return;
    plotType=0;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graphSurface=null;
    System.gc();
    graph3D(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graph3D,BorderLayout.CENTER);
    private void changeplottoSurface()
    if(plotType==1)
    return;
    plotType=1;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graph3D=null;
    System.gc();
    graphSurface(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graphSurface,BorderLayout.CENTER);
    private void surfaceButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoSurface();
         repaint();
    private void contourButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoContour();
         repaint();
    public void init()
         container=getContentPane();
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    Rectangle r1= new Rectangle();
    rect=new Rectangle();
    //r1=container.getBounds();
    toolPanel= new JPanel(new BorderLayout());
    toolBar = new JPanel();
    contourButton = new JButton("Contour");
    toolBar.add(contourButton);
    contourButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    contourButtonActionPerformed(evt);
    surfaceButton = new JButton("Surface Plot");
    toolBar.add(surfaceButton);
    surfaceButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    surfaceButtonActionPerformed(evt);
    toolBar.setBackground(Color.white);
    toolPanel.add(toolBar,BorderLayout.NORTH);
    container.add(toolPanel,BorderLayout.NORTH);
    Rectangle r2= toolPanel.getBounds();
    Dimension appletSize = this.getSize();
    int appletHeight= appletSize.height;
    int appletWidth= appletSize.width;
              rect.setBounds(0,(int)r2.getHeight(),appletWidth,appletHeight-(int)r2.getHeight());
    plotType=0;
         graph3D(g2);
         container.add(graph3D,BorderLayout.CENTER);

    in your button action listeneres (e.g. contourButtonActionPerformed()) don't only call repaint(), but update(this.getGraphics());
    this should help in most cases. other refreshing methods are:
    java -Dsun.java2d.noddraw=true HelloWorld
    java.awt.Component.repaint()
    java.awt.Component.update(Graphics) (e.g. c.update(c.getGraphics());)
    java.awt.Component.validate()
    javax.swing.JComponent.revalidate()
    javax.swing.JComponent.updateUI()
    javax.swing.SwingUtilities.updateComponentTreeUI(java.awt.Component)

  • Object Graphics deleted on paint component

    Hello everybody!
    I have a question about the object graphics when paint a component in it. I'm trying to paint a component in a image, and after show it in the screen.
    The problem is that in order to make it possible, I have to put the function that paint the image inside the code paint() of the principal class.
    With this code in one class named: Program:
    public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D) g.create();      
                gt = new GraphicT(view);   <-HERE IS THE PROBLEM
                g2.setColor(getBackground());
                g2.fillRect(0,0,getWidth(),getHeight());                               
                g2.drawImage(gt.getImage(), 0, 0, this);
    ...and with this other in other named: GraphicT:
    private JComponent view;
    private Image image;
    private Graphics gaux;
    public GraphicT(JComponent view){
            this.view = view;
            this.image = new BufferedImage (view.getWidth(),view.getHeight(),BufferedImage.TYPE_INT_BGR);
            gaux = image.createGraphics();
          //  gaux=image.getGraphics();
            this.view.paint(gaux);       
    public BufferedImage getImage(){              
            return this.image;
    ...I don't want to do it because each time that Program paint , create the image (object) in GraphicT. I want to create the image only one time, I mean to put the class GraphicT inside the Program like a object private. But if I do this, program doesn't paint anything.
    Do you know why about this behaviour?
    Thanks everybody
    Edited by: ginnkk on Feb 5, 2009 3:15 AM

    So you want to paint a component to an image and display the image. The reason it works if you put it in the paint() method is becasuse by that time the component has already been made displayable, approprietly sized, and consequently can be painted.
    If all you are doing is painting an ordinary JComponent, then it's the approprietly sized part that matters.
    Dimension prefSize = myJComponent.getPreferredSize();
    myJComponent.setSize(prefSize.width,prefSize.height);
    myJComponent.doLayout();
    GraphicT gt = new GraphicT(myJComponent);This is more or less the code required to paint the component outside the paint method right after the JComponent has been constructed.

  • Paint from a paint(Component) method? Is it possible?

    Hi all
    Here's my deal: I'd like to make a Paint (http://java.sun.com/javase/6/docs/api/java/awt/Paint.html) out of a component or even better, just something with a paint(Graphics) method. I looked into implementing my own Paint, but it looks very foreboding, esp the requirement to be able to get the Raster in the PaintContext object which I think I'd have to implement too.
    Any advice?

    Here's my attempt at it...
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.awt.PaintContext;
    import java.awt.Rectangle;
    import java.awt.RenderingHints;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.awt.image.ColorModel;
    import java.awt.image.Raster;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import java.lang.reflect.Method;
    public class ImagePaint implements Paint {
        Object paintable;
        Method paintMethod;
        BufferedImage paint;
        public ImagePaint(Object paintable) {
            this.paintable = paintable;
            try{
                paintMethod =
                        paintable.getClass().getMethod("paint",Graphics.class);
            }catch(java.lang.NoSuchMethodException e) {
                throw new IllegalArgumentException("Paintable object does " +
                        "not have paint method!");
        public java.awt.PaintContext createContext(ColorModel cm,
                                                   Rectangle deviceBounds,
                                                   Rectangle2D userBounds,
                                                   AffineTransform xform,
                                                   RenderingHints hints) {
            /*the bounds being passed to this method is the bounding rectangle
             *of the shape being filled or drawn*/
           paint = new BufferedImage(deviceBounds.width,
                                     deviceBounds.height,
                                     BufferedImage.TYPE_3BYTE_BGR);
               /*note: if translucent/transparent colors are used in the
                *paintable object's "paint" method then the BufferedImage
                *type will need to be different*/
            Graphics2D g = paint.createGraphics();
                /*set the clip size so the paintable object knows the
                 *size of the image/shape they are dealing with*/
            g.setClip(0,0,paint.getWidth(),paint.getHeight());
            //call on the paintable object to ask how to fill in/draw the shape
            try {
                paintMethod.invoke(paintable, g);
            } catch (Exception e) {
                throw new RuntimeException(
                   "Could not invoke paint method on: " +
                        paintable.getClass(), e);
            return new ImagePaintContext(xform,
                                         (int) userBounds.getMinX(),
                                         (int) userBounds.getMinY());
        public int getTransparency() {
            /*Technically the transparency returned should be whatever colors are
             *used in the paintable object's "paint" method.  Since I'm just
             *drawing an opaque cross with this aplication, I'll return opaque.*/
            return java.awt.Transparency.OPAQUE;
        public class ImagePaintContext implements PaintContext {
            AffineTransform deviceToUser;
            /*the upper left x and y coordinate of the where the shape is (in
             *user space)*/
            int minX, minY;
            public ImagePaintContext(AffineTransform xform, int xCoor,
                                                            int yCoor){
                try{
                    deviceToUser = xform.createInverse();
                }catch(java.awt.geom.NoninvertibleTransformException e) {}
                minX = xCoor;
                minY = yCoor;
            public Raster getRaster(int x, int y, int w, int h) {
                /*find the point on the image that the device (x,y) coordinate
                 *refers to*/
                java.awt.geom.Point2D tmp =
                        new java.awt.geom.Point2D.Double(x,y);
                if(deviceToUser != null) {
                    deviceToUser.transform(tmp,tmp);
                }else{
                    tmp.setLocation(0,0);
                tmp.setLocation(tmp.getX()-minX,tmp.getY()-minY);
                /*return the important portion of the image/raster in the
                 * coordinate space of the device.*/
                return paint.getRaster().createChild((int) tmp.getX(),
                                                     (int) tmp.getY(),
                                                     w,h,x,y,null);
            public ColorModel getColorModel() {
                return paint.getColorModel();
            public void dispose() {
                paint = null;
        public static void main(String[] args) {
            /*as of java 1.6.10 d3d is enabled by default.  The fillRect
             * commands are significantly slower with d3d.  I think this is
             * a known bug.  Also, with d3d enabled I get all sort
             * weird painting artificats for this particular demonstration*/
            System.setProperty("sun.java2d.d3d","false");
            final ImagePaint paint = new ImagePaint(new Object() {
                public void paint(Graphics g) {
                    Rectangle r = g.getClipBounds();
                    g.setColor(Color.white);
                    g.fillRect(r.x,r.y,r.width,r.height);
                    //draw a red cross
                    g.setColor(Color.red);
                    g.fillRect(r.width/2-20,0,40,r.height);
                    g.fillRect(0,r.height/2-20,r.width,40);
                    g.dispose();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent p = new JComponent() {
                public void paintComponent(Graphics g) {
                    Graphics2D g2d = (Graphics2D) g;
                    g2d.setPaint(paint);
                    g2d.fillOval(getWidth()/3,getHeight()/3,
                                 getWidth()/3,getHeight()/3);
                    g2d.dispose();
            p.setPreferredSize(new Dimension(500,500));
            f.setContentPane(p);
            f.pack();
            f.setVisible(true);
    }I don't think the unresponsiveness from larger areas is necessarily due to your code. For all of my GUI applications, resizing an
    already large frame tends to be prety sucky while resizing an already small frame tends to be pretty smooth.

  • Paint Component using scaled Graphics with TiledImage

    Hello,
    I am in the process of adding minor image manipulation in an application I created. I have paint overridden on the component that displays the image and in that component I am scaling the graphics to a representation of the image at 300 dpi versus the screen resolution. The image is a TiledImage which gave me pretty good performance benefits when I was painting at screen resolution. Now I want to know if there is something I can do to the tiles to get the performance benefit back. I understand this
    may not be possible because the entire image displays at once with the scaled graphics instance.
    Here is a copy of my paint method:
    public void paintComponent(Graphics gc) {
              Graphics2D g = (Graphics2D) gc;
              g.scale(scale, scale);
              Rectangle rect = this.getBounds();
              rect.width *= (1/scale);
              rect.height *= (1/scale);
              if ((viewerWidth != rect.width) || (viewerHeight != rect.height)) {
                   viewerWidth = rect.width;
                   viewerHeight = rect.height;
              setDoubleBuffered(false);
              g.setColor(Color.BLACK);
              g.fillRect(0, 0, viewerWidth, viewerHeight);
              if (displayImage == null)     return;
              int ti = 0, tj = 0;
              Rectangle bounds = new Rectangle(0, 0, rect.width, rect.height);
              bounds.translate(-panX, -panY);
              int leftIndex = displayImage.XToTileX(bounds.x);
              if (leftIndex < ImageManip.getMinTileIndexX())
                   leftIndex = ImageManip.getMinTileIndexX();
              if (leftIndex > ImageManip.getMaxTileIndexX())
                   leftIndex = ImageManip.getMaxTileIndexX();
              int rightIndex = displayImage.XToTileX(bounds.x + bounds.width - 1);
              if (rightIndex < ImageManip.getMinTileIndexX())
                   rightIndex = ImageManip.getMinTileIndexX();
              if (rightIndex > ImageManip.getMaxTileIndexX())
                   rightIndex = ImageManip.getMaxTileIndexX();
              int topIndex = displayImage.YToTileY(bounds.y);
              if (topIndex < ImageManip.getMinTileIndexY())
                   topIndex = ImageManip.getMinTileIndexY();
              if (topIndex > ImageManip.getMaxTileIndexY())
                   topIndex = ImageManip.getMaxTileIndexY();
              int bottomIndex = displayImage.YToTileY(bounds.y + bounds.height - 1);
              if (bottomIndex < ImageManip.getMinTileIndexY())
                   bottomIndex = ImageManip.getMinTileIndexY();
              if (bottomIndex > ImageManip.getMaxTileIndexY())
                   bottomIndex = ImageManip.getMaxTileIndexY();
              for (tj = topIndex; tj <= bottomIndex; tj++) {
                   for (ti = leftIndex; ti <= rightIndex; ti++) {
                        Raster tile = displayImage.getTile(ti, tj);
                        DataBuffer dataBuffer = tile.getDataBuffer();
                        WritableRaster wr = Raster.createWritableRaster(sampleModel,
                                  dataBuffer, new Point(0, 0));
                        BufferedImage bi = new BufferedImage(colorModel, wr,
                                  colorModel.isAlphaPremultiplied(), null);
                        if (bi == null) continue;
                        int xInTile = displayImage.tileXToX(ti);
                        int yInTile = displayImage.tileYToY(tj);
                        atx = AffineTransform.getTranslateInstance(
                                  xInTile + panX, yInTile + panY);
                        g.drawRenderedImage(bi, atx);
              imageDrawn = true;
              if (cropOn) {
                   Rectangle cropRect = getDimensions();
                   if (cropRect == null) return;
                   g.setColor(Color.BLACK);
                   g.drawRect(cropRect.x, cropRect.y, cropRect.width, cropRect.height);
                   g.setComposite(makeComposite(0.5f));
                   g.fillRect(0, 0, cropRect.x, cropRect.y);
                   g.fillRect(cropRect.x, 0, viewerWidth - cropRect.x, cropRect.y);
                   g.fillRect(0, cropRect.y, cropRect.x, viewerHeight - cropRect.y);
                   g.fillRect(cropRect.x + cropRect.width, cropRect.y,
                             viewerWidth - cropRect.x, viewerHeight - cropRect.y);
                   g.fillRect(cropRect.x, cropRect.y + cropRect.height, cropRect.width,
                             viewerHeight - cropRect.y);
              g.dispose();
              if (((double)GarbageCollection.getFreeMem() /
                        (double)GarbageCollection.getRuntimeMem()) > 0.7d) {
                   System.out.println("Memory Usage: " +
                             (int)(((double)GarbageCollection.getFreeMem() /
                             (double)GarbageCollection.getRuntimeMem()) * 100) + "%");
                   System.out.println("Requesting garbage collection.");
                   GarbageCollection.runGc();
              setDoubleBuffered(true);
    Thank you in advance for support

    I moved the sizing out of the paint method and put in a component listener. I am still getting approx. the
    same performance. Possibly because I am trying to do too much. I have a mouse listener that allows
    the user to pan the image. I also have crop, rotate, shear, and flip methods. The main problem I think
    is when I change graphics to scale at (72d / 300d) which puts the display comparable to 300 dpi.
    My main reason for this was to allow zooming for the user. Am I overtasking the graphics object by
    doing this?

  • Paint component without frame

    Hallo!
    Do anybody know how to paint a component without using a frame?
    I have a panel with some components, where i do some custom painting.
    What I want to do is: Create an image from my panel to store it on the harddisk as gif or jpeg.
    How can I paint my panel without using a frame like this:
    JFrame f = new JFrame();
    MyPanel p = new MyPanel();
    f.setContentPane(p);
    f.setSize(...);
    ----> i dont want this ...
    f.show;
    I also used SwingUtilities:
    Graphics2D g2D = new Graphics2D();
    SwingUtitlities.paintComponent(g2D, f, p, 0, 0, width, height));
    If I only use:
    MyPanel p = new MyPanel();
    p.revalidate();
    p.repaint();
    I can not catch an image from the panel, it is always only gray.

    If I understand well, you want to paint a component that is not visible ?
    You can use a BufferedImage for example :
    int width = 300; // for example
    int height = 200; // for example
    BufferedImage buffImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = buffImage.createGraphics();
    panel.setBounds(0,0,width,height);
    panel.paint(graphics);
    graphics.dispose();
    Now the panel is painted on the image.
    Denis

  • How to fill polygon without using paint component ?

    hello,
    i have a class called "public class Arrow2DRhombus implements Shape" with the following constructor:
    public Arrow2DRhombus(Point2D begin, Point2D end) {
            this.x1 = begin.getX();
            this.y1 = begin.getY();
            this.x2 = end.getX();
            this.y2 = end.getY();
            this.initArrow();the code for .initArrow():
    private void initArrow(){
            int length = (int) Math.sqrt(Math.pow(Math.abs(x1-x2),2) +
                           Math.pow(Math.abs(y1-y2),2));
            length=length-19;
    Polygon poly = new Polygon();
            poly.addPoint((int) x1,(int) y1);
            poly.addPoint((int) x1+ length,(int) y1);
              poly.addPoint((int) x1+ length+10,(int) y1+5);
              poly.addPoint((int) x1+ length+20,(int) y1);
              poly.addPoint((int) x1+ length+10,(int) y1-5);
              poly.addPoint((int) x1+ length,(int) y1);
            double rad = this.calcAngle((float) this.x1,(float) this.y1,(float) this.x2,(float) this.y2);
            AffineTransform tx = AffineTransform.getRotateInstance(rad,x1,y1);
            this.arrow = tx.createTransformedShape((Shape)poly);
        }is there a way i can fill the polygon "poly" with the code above .
    i know that i can fill a polygon using when using paintcomponent(Graphics g)
    but here how can i do it.
    10x

    I don't really understand the question. "Filling" a shape implies (to me) that you have a Graphics Object and are doing custom painting. So you would do this:
    a) in the paintComponent() method of a component
    b) in the paintIcon method of an Icon
    c) by painting onto a BufferedImage
    I'm sure there are other ways, but I don't think you just "fill" a Shape object.

  • Repaint() doesnt call paint component

    Hi all
    i need to call a paintComponent method() so i use repaint();
    but it doesnt work.
    trigger's in mouse pressed, calls pageflip method, then in a pageflip method calls paintComponent
    here's part of my code
    addMouseListener(new MouseAdapter() {                                   
                    public void mousePressed(MouseEvent e) {                   
                        if (boEvent==true){
                            System.out.println("mouse Pressed");
                            iMoux=e.getX();iMouy=e.getY();
                            if (iMoux>=(di.width/2)){
                                 boSaveReverse = false;
                                 PageFlip(0, 0, e.getX(), e.getY(), false, false, false, true);
                            else {
                                boSaveReverse = true;
                                PageFlip(0, 0, e.getX(), e.getY(), false, true, false, true);
                            boClicked=false;                                                   
    public void PageFlip(int a, int b, int c, int d, boolean boe,
                                 boolean bof, boolean bog, boolean boh){                      
                int bookx = a;int booky = b;int iMoux =c;int iMouy = d;
                boolean boClicked = boe;boolean boReverse = bof;
                boolean boZoom    = bog;boolean boDraw = boh;
                repaint();    //here repaint didint call paintComponent?       
            }did i do something wrong here?
    Thx in advance

    did i do something wrong here?Who knows? To get better help sooner, post a SSCCE that clearly demonstrates your problem.
    luck, db

  • Painting JComponent on BufferedImage

    Hi!
    My problem concerns painting component derived from JComponent class onto a BufferedImage.To be more precise I've got a JPanel onto which I draw a BufferedImage and then I add my component to the panel. Everything is OK when the component is opaqued but when it is not it doesn't show at all (BufferedImage displays every time). I've been playing with types of BufferedImage (BufferedImage.TYPE_INT_ARGB etc.),double buffering of my component and the panel but with no result. I've also discovered that it's meaningless whether I paint component before drawing Image or after. Here's a piece of code that should help in better understanding what's on my mind:
    public class A extends JPanel {
        public void paint(Graphics g) {
            removeAll();
            g.drawImage(bi,0,0,null); //bi - BufferedImage
            TrojkatnyButton t = new TrojkatnyButton();
            t.setSize(20,20);
            t.setLocation(30,30);
            add(t);
            t.setVisible(true);
            t.repaint();
    public class TrojkatnyButton extends JComponent {
        public boolean isOpaque() {
            return false;
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.ORANGE);
            g.fillOval(0, 0, getWidth(), getHeight());
    }Thanks in advance for answers!

    strannik wrote:
    public class A extends JPanel {
    public void paint(Graphics g) {
    removeAll();
    g.drawImage(bi,0,0,null); //bi - BufferedImage
    TrojkatnyButton t = new TrojkatnyButton();
    t.setSize(20,20);
    t.setLocation(30,30);
    add(t);
    t.setVisible(true);
    t.repaint();
    In this code you are adding a component to another component from within a paint method, and this is something you should never do. Remember that the logic part of the program should not be placed into the paint portion of the program. I'd fix this first and then see if this fixes your problem. If not, I recommend that you post an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    [http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
    Again, if the code is compilable and runnable more people will be able to help you.
    Best of luck.
    edit: also, since you are coding in Swing, you should not override paint at all 99% of the time. You are far better off overriding paintComponent of your JPanels and other JComponents. Also, don't forget to call super.paintComponent(g) as the first line of your paintComponent override.
    HTH.
    Edited by: Encephalopathic on Jan 3, 2009 6:52 AM

  • Paint()  problems

    i was messing around and created a program that inside a JFrame there is a crosshair image that follows your mouse pointer and if you click the mouse, it leaves a red dot on that spot. The problem is that in order for the crosshair image not to create a trail of itself, i call repaint() from mouseMoved() to refill the entire background each time you move the mouse (fill rectangle of size of JFrame to background color in paint()). This works except it makes it so that when you click to leave a dot, those get erased as soon as you try to move the mouse. i thought about only refilling the small area where the crosshair last was before it moved instead of the entire JFrame but this could cause issues if you move the mouse over a spot that already has a red dot there (it will be erased). Cant think of a solution to this.

    In wsing the code that drow the content on the screne should be placed in the paintComponent method and in your mouseMove just save the coordinates where you should drow the image in to a variable and call repaint.
    The paintComponent should read the coordinates from the variables and do the drowing. To clean up of old drowing just call super.paintComponent from paint component before do any drowing

  • GUI In screen Painter not working .plz help me.

    I have Installed SAP ABAP trail version 7.01 .
    I have Installed The GUI 6.40 forntend.
    It is working fine, BY using this I can connect to system, do pogrraming .
    But when click on layout button of any screen it show a msg " No response from some file .exe ( like ginit.exe I am not remembering the name exactly) and then it shows line edditor instead of graphical editor.
    And I want graphical editor.
    While Installing GUI there were lot of check boxes where there but I hecked the check box for GUI only beacuse I was not knowing anything about the rest, do I need to reintall it and selecte some more check box to fix the problem.
    I really dont know what should do, If anyone have any suggestion please let me know.
    Good answers will be appriciated.
    Thank you in advance.

    Hi, When you install the SAPGUI you can choose the GUI component. Check you have selected the 'Screen Painter* in the Installation. No need to uninstall the SAPGUI. Just Re-install the GUI with the Screen Painter component. It will solve your problem. Thks.
    Rgds,
    Jey

  • Changing Swing Component L&F

    Hey
    I am programming a game that takes place in the Middle Age, and to protect the player's suspension of disbelief, I'd like the few Swing components I use to look like they are pieces of wood.
    I use a JScrollPane to scroll on the game's 2D viewport. I was thinking of getting the Graphics of the JScrollBars and repaint them, but it is not performance efficient.
    Does anybody know how I could put my own pictures instead of the default tabs?
    Thanks, Guillaume

    This is a sample of a self painted JScrollBar
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    class TinySp extends JScrollBar
    public TinySp()
         super.setUI(new myCustomScrollBarUI());
         setPreferredSize(new Dimension(9,1));
         setOpaque(false);
    class myCustomScrollBarUI extends BasicScrollBarUI
    public void configureScrollBarColors()
         super.configureScrollBarColors();
    public Dimension getMaximumThumbSize()
         return(new Dimension(3,10));
    protected void paintTrack(Graphics g, JComponent c, Rectangle trec)
         g.setColor(Color.lightGray);
         g.fillRect(trec.width/2,trec.y,1,trec.height);
    protected void paintThumb(Graphics g, JComponent c, Rectangle trec)
         g.setColor(Color.blue);
         g.fillRect(3,trec.y,3,trec.height);
    protected JButton createDecreaseButton(int orientation)
         AbstractButton a1 = new myButton(1);
         return((JButton)a1);
    protected JButton createIncreaseButton(int orientation)
         AbstractButton a2 = new myButton(0);
         return((JButton)a2);
    class myButton extends JButton
         int d = 0;
    public myButton(int i)
         super();
         d = i;
         setOpaque(false);
         setPreferredSize(new Dimension(9,9));
         setBorderPainted(false);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);          
         g2.setColor(Color.black);
         if (d == 1)
              g2.drawLine(4,1,1,6);
              g2.drawLine(4,1,7,6);
              g2.setColor(Color.lightGray);
              g2.fillRect(4,7,1,5);
         else
              g2.drawLine(4,getHeight()-2,1,getHeight()-7);
              g2.drawLine(4,getHeight()-2,7,getHeight()-7);
              g2.setColor(Color.lightGray);
              g2.fillRect(4,getHeight()-12,1,5);
         g2.dispose();
    Noah

Maybe you are looking for

  • BSIS showing wrong entries

    Hello, At my company, they run the MR11 to check for GR/IR variances and then clear these variances using the F.13 transaction. Finally, the F.19 transaction is run to check for PO's having the GR/IR variance. There are some old PO's of 2005/2006 whi

  • Getting results from LDB (Logical Database)

    Hi All, I have a requirement where i need to pass LDB results to external application. It can be any LDB. Like in SE36 we put the LDB name and execute and final results are shown in ALV. I dont need it to display in ALV but from my custom program, ne

  • Question about customer line item clearing

    Hello everyone, There is one question here. Since from the result of FBL5N in SAP, the total amount of AR is zero, but the cleared /Open symbol still show these items are open. Itu2019s very strange because these should be shown as cleared items as t

  • FIle Adapter Receiver - Content Conversion

    I have a xml file as below that I am trying to convert to a simple csv file. All I get is a blank csv file at the ouptput. I tried different setting for the file conversion in the reveiver file adapter. No luck yet. I could write to an output XML fil

  • Trying to mount OSX 10.4.7

    While updating this am from 10.4.6 to 10.4.7 and trying to mount 10.4.7 PPC Patch.pkg received message there was an error in the pkg. to wit: Application Launch failure The applicatin "(null)" could not be launched because of a shared library error: