PaintComponent()

i had canvas(My Board) class which worked fine when i run it as an application.
but i change canvas to JPanel
and now when i run a game
when i start new game it does not display board for a second and then it will disappear.
or when i try to override (repaint() method) it draw the board but it disappaer after i resize a window,
Public class ChessGame {
JFrame a = new JFrame
Chess a =new Chess()
a.init()
a.start();
Class Chess extends JApplet
Board board;
public init()
board = new board (this);
Class Board extends JPanel
public void newgame()
int [] setup= [............]
for (int i=0; i < 120; i++)
board = setup [i];
repaint();
//for (int i=21; i < 99; i++)
//     { if (board[i]!=7)
//     paintField(i);     
i try to draw my board like that but it with dispaear if i resize my window
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawString("Loading...............",144,134);
for ( int i = 21; i < 99; i++)
if (board[i]!=7)
paintField(i);
super.paintComponent(g);     
public void paintField (int index)
//load graphic
Graphics g = getGraphics ();
//calculate x and y
int x = (index - 21) % 10;
int y = (index - 21) / 10;
//paint ground field
if ( (x+y) % 2 == 0)
g.setColor( white);
else
g.setColor( darkgreen );
g.fillRect ( x * 50, y * 50, 50, 50);
//paint piece
if (!bool)
{try {
  g.drawImage (pieces[((boardcolor [index]-1)*10)+(board[index]%10)], x * 50, y * 50, 50, 50, drawer);
catch (ArrayIndexOutOfBoundsException e) {}     
else
try {     g.drawImage (secpiece [((boardcolor [index] -1)*10)+board[index]%10], x * 50, y * 50, 50, 50, drawer);
catch (ArrayIndexOutOfBoundsException e) {}

Kinda confusing:
Public class ChessGame {
  JFrame a = new JFrame
  Chess a =new Chess()
  a.init()
  a.start();No () for the new JFrame? There is a JFrame named a and a Chess named a?
  Board board;
  public init()
    board = new board (this);
  Class Board extends JPanel
    public void newgame()
      int [] setup= [............]
      for (int i=0; i < 120; i++)
        board = setup[i] ;
      } So is the board = setup<i> a different board tham board = new board? 'cause one is a Board and the other an int??
public void paintComponent(Graphics g) {
  g.setColor(Color.red);
  g.drawString("Loading...............",144,134);
  for ( int i = 21; i < 99; i++)
    if (board!=7)
      paintField(i);
    super.paintComponent(g); Firt, super.paintComponent should be first in the paintComponent class, not last. Second, you only want to paintField when board is not 7?
You should also see if you can pass the same graphic component to paintField that you use for this drawing, like:
paintField(i, g);
instead of getting a new graphics.

Similar Messages

  • 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

  • How can i pass a parameter into paintComponent()?

    public void paintComponent(Graphics g)
    Graphics2D g2 = (Graphics2D) g;
              for(int i = 150;i<=250;i+=20)
                   for(int a = 50;a<=200;a+=50)
              Rectangle box = new Rectangle(i, a, 15, 15);
    g2.draw(box);
    this is my paintComponent method. as far as i'm concerned, all our codings for drawing must be inside this method rite? My assignment is to create something like a cinema ticket system where we will display all the seats then user enters a position then we mark it. when i prompt the user for the position..how do i pass it into this method? pls help me. obviously the coding to prompt is in another .java file.

    //this is my main
    public class AirAsia extends JComponent {
              static JLabel input, input2;
         private static void test(){
              JFrame frame = new JFrame("Aeroplane Seating");
              frame.setSize(500,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
              String prompt = JOptionPane.showInputDialog("Enter x");
         input = new JLabel("You have entered " +prompt);     
    String prompt 2= JOptionPane.showInputDialog("Enter x");
         input 2= new JLabel("You have entered " +prompt2);     
              RectangleComponent component = new RectangleComponent();
    frame.add(component);
              frame.setVisible(true);
    private static void createAndShowGUI()
         JFrame.setDefaultLookAndFeelDecorated(true);
              test();
    public static void main(String[] args)
    createAndShowGUI();
    //now this is my paint component in another file
    public class RectangleComponent extends JComponent
    public void paintComponent(Graphics g)
    Graphics2D g2 = (Graphics2D) g;
              for(int i = 150;i<=250;i+=20)
                   for(int a = 50;a<=200;a+=50)
              Rectangle box = new Rectangle(i, a, 15, 15);
    g2.draw(box);}
              for(int i = 60;i<=160;i+=20)
                   for(int a = 240;a<=820;a+=15)
              Rectangle box = new Rectangle(i, a, 15, 15);
    g2.draw(box);
    first of all, i ask the user to enter 2 inputs which are x and y. so now how do i pass in the x and y into paint component method so i can mark/draw the box?

  • Can I exit from paintComponent?  ...or... how can I check for invalid data?

    I'm writing a calendar applet for a programming class and I've nearly completed it but I'm stuck at checking for valid data.
    What seems to be happening is that paintComponent() is being called before actionPerformed.
    In actionPerformed (when they click the button), it checks to make sure they entered a valid month (1 to 12). If the didn't it dispalys a message, but if they did it calls repaint().
    But even if repaint() isn't called, Java still seems to call it before actionPerformed and I get exceptions.
    So I tried checking inside of paintComponent() by using a simple if(...) return; but that doesn't seem to do anything... it just keeps going through with the method.
    So -- Once the user presses my button I want to make sure the data is valid before repainting the screen. How can I do this?

    I validate it in actionPerformed which is called by
    the action listener... that is what you meant right?
    The problem is that it seems paintComponent() is being
    called before I can validate the data with
    actionPerformed(). I need to stop paintComponent()
    from always being calledMVC. (Model, View, Controller)
    Initially the internal value of the data (the model) should be valid (or null with a check in the paintComponent method)
    paintComponent (the view part) shows the state of the valid data.
    You press the button.
    actionPerformed is called (the controller).
    It checks the value and, if valid, writes it to the data (model), then updates the view.
    At no point will the view have to render invalid data, because the model is only updated after actionPerformed checks the value.
    The pattern may be applied with different classes performing the three roles, or different methods in the same class (sometimes it's easier that way for simple cases).
    Pete

  • 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)?

  • PaintComponent method refuses to be invoked.

    Hello All!
    I have a problem with graphics representation by swing. Namely I have an application based on Jframe object. It includes three Jpanel components. I need to map information from Jtable as diagram in the plotPanel. That�s code fragment I try to use:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JComponent.*;
    import java.lang.*;
    import java.io.*;
    * @author  Administrator
    public class ROC extends javax.swing.JFrame{
    public ROC() {
            initComponents();
    /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            menuPanel = new javax.swing.JPanel();
            openButton = new javax.swing.JButton();
            tablePanel = new javax.swing.JPanel();
            pointsTable = new javax.swing.JTable();
            generateButton = new javax.swing.JButton();
            plotPanel = new javax.swing.JPanel();
            plotPanel.add(new PlotArea(), java.awt.BorderLayout.CENTER);
    ������ //This is a piece of code to initialize other components
            plotPanel.setLayout(new java.awt.BorderLayout());
            plotPanel.setBackground(java.awt.Color.white);
            plotPanel.setPreferredSize(new java.awt.Dimension(600, 380));
            plotPanel.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
            plotPanel.addContainerListener(new java.awt.event.ContainerAdapter() {
                public void componentAdded(java.awt.event.ContainerEvent evt) {
                    plotPanelComponentAdded(evt);
            getContentPane().add(plotPanel, java.awt.BorderLayout.CENTER);
            pack();
    ������  // Different functions (such as loading data from the file to JTable i.e.)
           public static void main(String args[]) {
            System.out.println("Application starts");
            new ROC().show();
        // Variables declaration - do not modify
        private javax.swing.JPanel menuPanel;
        private javax.swing.JButton openButton;
        private javax.swing.JPanel tablePanel;
        private javax.swing.JTable pointsTable;
        private javax.swing.JButton generateButton;
        private javax.swing.JPanel plotPanel;
        // End of variables declaration
    public class PlotArea extends javax.swing.JComponent{
        /** Creates new plotPanel */
        public PlotArea() {
            System.out.println("PlotArea has been created");
            setPreferredSize(new java.awt.Dimension(600, 380));
            setMinimumSize(new java.awt.Dimension(200, 100));
            super.setBorder(BorderFactory.createLineBorder(Color.red, 5));
            repaint();
        public void paintComponent(java.awt.Graphics g) {
            System.out.println("PaintComponent method has been invoked");
            Graphics2D g2d = (Graphics2D)g;
    ������ // this is the code to implement custom painting
    }The trouble is that PaintComponent method hasn�t been invoked. Help me please. What should I do to cause PaintComponent to be performed?

    You might want to ensure your "plotPanel" uses a BorderLayout if you're specifying a constraint:
    plotPanel = new javax.swing.JPanel(new BorderLayout());
    plotPanel.add(new PlotArea(), java.awt.BorderLayout.CENTER);You shouldn't need to call "repaint" in the constructor of PlotArea, either. I doubt it'll make any difference.
    Hope this helps.

  • How to use Paintcomponent using parameters/variable

    Hi, I am new to Java.have looked in many topics of this forum, references and could not find the answer. thanks for helping.
    I am trying to test a simple procedure to draw a line from (0,0) to (x,x), where x is an integer entered by the user using a showInputDialog.
    I am using a JPanel and the paintComponent as suggested by some tutorial (so that, the frame can be moved, resized etc..and the line still remains there).
    I have tried for hours how to get the x variable into the g.drawline method. Can anyone help.
    Additionally, my frame has its top-left corner centered on the screen, resulting in the frame being shown in the bottom-right quadrant of the PC screen. How do I center it?
    thanks for the help
    package graphictest;
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Draw extends JFrame {
         public Draw(){                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
            String inputString = JOptionPane.showInputDialogu(null,"enter input")l
            int input;
            input = Integer.parseInt(inputString);
            add(new NewPanel());
         public class NewPanel extends JPanel {
               protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawLine(0, 0,input, input);
        public static void main(String[] args) {  
            Draw frame = new Draw();
            frame.setTitle("Title");
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,800);
            frame.setVisible(true);
    }

    You need to make the variable input a class variable, not a variable local to any one method:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    public class Draw extends JFrame
        private int input = 0; //*** you need input to be a class variable
        public Draw()
            String inputString = JOptionPane.showInputDialog(null, "enter input");
            //int input;  //*** and not a variable local to this method!
            input = Integer.parseInt(inputString);
            add(new NewPanel());
        public class NewPanel extends JPanel
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                g.drawLine(0, 0, input, input);
        public static void main(String[] args)
            Draw frame = new Draw();
            frame.setTitle("Title");
            //frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //frame.setSize(800, 800);
            frame.setPreferredSize(new Dimension(800, 800));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
    }

  • 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();
    }

  • Swing layout + awt paintcomponent issue

    Hi guys
    I have a small issue while creating my very first application, or better, creating its GUI.
    i would like to insert in a jpanel three JTextFields on top of the panel where the user could eventually enter data, once the data are entered, a paintComponent displays the results beneath it using graphics, with simple drawLine from the paintComponent method.
    The problem is that i dont succeed to design a "good looking" panel where i can combine the organized layout of the fields and the space left for the lines of the paintcomponent method
    i can enter the fields and the lines like this:
    //contstructor definition
    add(field10);
    add(field2);
    add(field3);
    //eof constructor definition
    public void paintComponent(Graphics g){
    g.drawString("ciao"20,20);
    }but i cannot do this...
    //contructor definition
    setLayout(new GridLayout(3,2));
    add(field10);
    add(field2);
    add(field3);
    //eof constructor definition
    public void paintComponent(Graphics g){
    g.drawString("ciao"20,20);
    }because the GridLayout will occupy the whole panel and the size of the fields will be huge, so that there will be no space left for the paintComponents.
    What i would like to do is to let the GridLayout to occupy only the upper part of the JPanel so that the part below could be left to graphic content.
    I hope it sounds clear.
    Thank you
    Take care
    Edited by: classboy on Sep 8, 2009 9:28 PM

    One of the keys to understanding use of layout managers with Java is that they can be nested. More accurately, you can next Components and have each one use its own layout manager. One solution to your problem is to have a main JPanel use a BorderLayout, then add another JPanel, say called textFieldPanel that uses GridLayout and holds the three JTextFields. This panel can be added to the main panel BorderLayout.SOUTH or .NORTH, depending on your preference, and then have a third JPanel a drawingPanel that overrides paintComponent and displays the graphics, and add this to the main JPanel BorderLayout.CENTER.
    The iterations possible here are close to endless.
    Much luck.

  • PaintComponent: inner class / method?

    Hi,
    I am doing a lot of painting in my paintComponent method and would like to ask whether it's possible to use e.g. inner classes or methods within paintComponent? I think I am confronted with the problem that my paintComponent method gets too unstructured :-/
    Thanks for your help!

    I am doing a lot of painting in my paintComponent
    method and would like to ask whether it's possible to
    use e.g. inner classes or methods within
    paintComponent? I think I am confronted with the
    problem that my paintComponent method gets too
    unstructured :-/paintComponent is a method... so, you can call other methods from it. I'm not sure what you mean by "use inner classes". You can define an inner class and instantiate an object of that class from within paintComponent just like you can from any other method. Your question seems a bit weird, or I'm not understanding it.
    Is your paintComponent too slow or just too long? By all means, use methods to logically separate different things you are doing, but this only add organization, not speed.

  • 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).

  • 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?

  • This paintComponent Method is Annoying - HELP

    ok, I think I touched upon this problem sometime earlier, however I face a larger problem which I've been trying to solve by a different and simpler means but I get nothin.
    I have a paintComponent method which DRAWS lines, strings and shapes that get PAINTED on to a JFrame all good and well.
    Now, because of the amount of lines, strings and shapes I have on this "paintComponent", I want to put it in a class of its own. and THEN call it from the class it was in.
    So I want to create a new class, just for the paintComponent.
    Now, I've tried Numerous ways of trying to call it from another class but it just comes up as a blank screen. Oh and no I am not calling it directly too.
    Does anyone know where I am going wrong?
    help would be very much appreciated.

    ok LETS do this.
    class beep
    I call the paintComponent here to paint my JFrame BUT HOW!
    class drawingBoard----------------------------------------------------
    // create a rectangle called 'therectangle';
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.draw(therectangle)
    g2.drawString("", 100, 100)
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM
    Edited by: Calibre2007 on Feb 20, 2008 4:11 PM

  • Overriding paintcomponent method JButton

    Hi,
    I'm trying to make my own buttons (with a JPEG image as template and a string painted on this template, depending on which button it is) by overriding the paintComponent-method of the JButton class, but I still have a small problem. I want to add some mouse-events like rollover and click and the appropriate animation with it (when going over the button, the color of the button becomes lighter, when clicking, the button is painted 2 pixels to the left and to the bottom). But my problem is there is some delay on these actions, if you move the mousepointer fast enough, the pointer can already be on another button before the previous button is restored to its original state. And of course, this isn't what I want to see.
    I know you can use methods like setRollOverIcon(...), but if doing so, I think you need a lot of images ( for each different button at least 3) and I want to keep the number of images to a minimum.
    I searched the internet and these forums for a solution, but I didn't found any. I'm quite sure there is at least one good tutorial on this since I already tried to do this once, but I forgot how to do it, and I can't find the tutorial anymore.
    This is an example of the MyButton-class I already wrote, I hope it clarifies my problem:
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class MyButton extends JButton{
         BufferedImage button = null;
         int x, y;
         String text = "";
         MyButton(String t){
              super(t);
              text = t;
              setContentAreaFilled(false);
              setBorderPainted(false);
              setFocusPainted(false);
              addMouseListener(new MouseListener(){
                   public void mouseClicked(MouseEvent arg0) {
                        x += 2;
                        y += 2;
                   public void mouseEntered(MouseEvent arg0) {
                        //turn lighter
                   public void mouseExited(MouseEvent arg0) {
                        x -= 2;
                        y -= 2;
                   public void mousePressed(MouseEvent arg0) {}
                   public void mouseReleased(MouseEvent arg0) {}
         protected void paintComponent(Graphics g){
              Graphics2D g2d = (Graphics2D)g;
              try{
                   button = ImageIO.read(new File("Red_Button.jpg"));
              }catch(IOException ioe){}
              //Drawing JButton
              g2d.drawImage(button, null, x, y);
              g2d.drawString(text, x+5, y+5);     
    }Thanks in advance,
    Sam

    Okay, thanks, I replaced the image-read-in into the constructor of a JButton, and I think it goes a lot faster now (but that can be my imagination).
    I still use a mouseListener because I have no idea how to use the ButtonModelinterface. I searched to find a good tutorial, but I didn't really find one? Any recommendations (yes, I read the sun-tutorial, but did not find it really explanatory).
    Here's a complete SSCCE (although it isn't really necessary anymore since my main problem seams to be solved):
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class MyButton extends JButton{
         BufferedImage button = null;
         int x, y;
         String text = "";
         public MyButton(String t){
              super(t);
              text = t;
              try{
                   button = ImageIO.read(new File("Blue_Button.jpg"));
              }catch(IOException ioe){}
              setBorderPainted(false);
              addMouseListener(new MouseListener(){
                   public void mouseClicked(MouseEvent arg0) {}
                   public void mouseEntered(MouseEvent arg0) {
                        x += 2;
                        y += 2;
                   public void mouseExited(MouseEvent arg0) {
                        x -= 2;
                        y -= 2;
                   public void mousePressed(MouseEvent arg0) {}
                   public void mouseReleased(MouseEvent arg0) {}
         protected void paintComponent(Graphics g){
              Graphics2D g2d = (Graphics2D)g;
              g2d.drawImage(button, null, x, y);
              g2d.drawString(text, x+25, y+15);     
         public void fireGUI(){
              JFrame frame = new JFrame("ButtonModelTester");
              frame.setLayout(new GridLayout(2,1,10,10));
              frame.add(new MyButton("Test1"));
              frame.add(new MyButton("Test2"));
              frame.setSize(200,100);
              frame.setVisible(true);
         public static void main(String[] args){
              SwingUtilities.invokeLater(new Runnable(){
                   public void run(){
                        new MyButton(null).fireGUI();
    }Thanks,
    Sam
    PS: you mentioned my earlier posts? So they are still somewhere on this forum, because I couldn't find the anymore, they aren't in my watch list. I Checked this since I thought I asked something similar before...

  • PaintComponent Method

    Hello,
    can any one tell me when paintComponent(Graphics gc){} method will be called???
    it's needed that i have to extends JPanel.
    in my prog m extending theJApplet class.
    can paintComponent(Graphics gc){} will called if m extending the JApplet..
    plz tell me..
    waiting 4 yr reply.
    Regards,
    Shruti.

    Swing related questions should be posted in the Swing forum.
    You override paintComponent of JPanel and add the panel to your JApplet. The paintComponent() method will be called as required.

Maybe you are looking for

  • Photoshop CS4, Win XP Pro, NVidia 9800GT

    Be forewarned!!! If you have the above stated system you will have a problem from day one with the installation. After trouble shooting with Adobe using their infernal email system the end result is that Adobe's install routine for Photoshop is corru

  • Printing headers & footers?

    Hi there, How on earth do you disable the printing of headers & footers in Safari 5.0.3 for Windows!? Thanks.

  • Dynamic tables derived from ddic tables

    I'm trying to create an internal table, which contains a lot of components of existing tables, but not all. So i tried to get the type description of the existing table, delete the not needed fields and create a new table by RTTS. Here is my code: RE

  • Azure Benefit for Partner

    Hi all, Just want to know why encourage customer to move to the Cloud ? Let say, customer running all services in on-premises such as Exchange, Lync and SharePoint. And then we push them move to the cloud, if the cost more cheaper, what happen with t

  • Adobe Elements 11 and Premiere Elements 11: invalid serial number on the number for Premiere???

    During the install, the Elements 11 portion accepted the serial on the box just fine and installed, but the Premiere serial number was rejected as "invalid"???