AWT/Swing difference Component.paint(Graphics g)

In the following code, I try to paint some component into a VolatileImage, also tried with BufferedImage, and draw the Image on some other component. Anyways it works with java.awt.Panel doesn't with JPanel, does anyone have a clue why?
Differences between Graphics and Graphics2D maybe?
package sqltest;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class AWTVC extends java.awt.Panel {
    public AWTVC(Component c) {
        this.c = c;
        //initComponents();
        Thread t = new Thread(){
            public void run(){
                try{
                Thread.sleep(2000);
                bu=createVolatileImage(500,500);
                while(true){
                    AWTVC.this.c.paint(bu.createGraphics());
                    getComponent(0).paint(bu.createGraphics());
                    AWTVC.this.repaint();
                    Thread.sleep(80);
                }catch(Exception e){
                    e.printStackTrace();
        t.start();
        initComponents();
    private void initComponents() {
        setLayout(new java.awt.BorderLayout());
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
    private void formComponentResized(java.awt.event.ComponentEvent evt) {
        bu=createVolatileImage(getWidth(), getHeight());
    final Component c;
    VolatileImage bu=null;
    public void update(Graphics g){
        g.drawImage(bu,0,0,getWidth(),getHeight(),null);
}Any help would be greatly appreciated!
Cheers

Well thanx alot,
Well I just asked out of curiosity, it works perfectly with the LIGHTWEIGHT_RENDERER, I was just curious to know why AWT components won't draw into Graphics2D (That seemed to be the problem). Well It works now so it doesn't really matter. Well I think the HeavyWeight Renderer is hardware accelerated, maybe that's the reason. Also since I'm using jdk 1.5 do you think setting the -Dsun.java2d.opengl=true property will improve performance. I have cpu cycles to spare, so I can't see the difference ;-)

Similar Messages

  • Why Component.paint(Graphics) is too slow?

    Works terrible slow by me :( Why could it be? I just call JDesktopPane.paint()
    Thank you

    Do you have tabbed Panes, JTables and JEditorPanes / JTextAreas on your Component?

  • Difference between AWT,Swing and swt

    Hello,
    I am giving a seminar about swing in which I need to point out differences between AWT,Swing and SWT(Software Widget Tool).
    I have two questions:
    1)I read that-A heavyweight component is one that is associated with its own native screen resource (commonly known as a peer). A lightweight component is one that "borrows" the screen resource of an ancestor-which makes it lighter.Can anybody explain What native screen resource is and how it is borrowed?
    2)I read that SWT uses native widgets and how can it be better than swing?If it is in what way?

    Use Swing for new projects. AWT is the rendering layer underneath Swing in many cases, and AWT provides utility things like Graphics. SWT is an alternative to Swing which used more native rendering, but actually with Java 6, Swing is using a lot of native rendering.
    Fire up NetBeans and use Matisse. Build an application. Run it under Windows, and then under Linux, and then realize how great it is.

  • Scrolling a custom Component (e.g. JPanel) with overridden paint(Graphic g)

    Hi.
    I’m creating an application for modelling advanced electrical systems in a house. Until now I have focused on the custom canvas using Java2D to draw my model. I can move the model components around, draw lines between them, and so on.
    But now I want to implement a JScrollPane to be able to scroll a large model. I’m currently using a custom JPanel with a complete override of the paint(Graphic g) method.
    Screen-shot of what I want to scroll:
    http://pchome.grm.hia.no/~aalbre99/ScreenShot.png
    Just adding my custom JPanel to a JScrollPane will obviously not work, since the paint(Graphic g) method for the JPanel would not be used any more, since the JScrollPane now has to analyze which components inside the container (JPanel) to paint.
    So my question is therefore: How do you scroll a custom Component (e.g. JPanel) where the paint(Graphic g) method is totally overridden.
    I believe the I have to paint on a JViewport instructing the JScrollPane my self, but how? Or is there another solution to the problem?
    Thanks in advance for any suggestions.
    Aleksander.

    I�m currently using a custom JPanel with a complete override of the paint(Graphic g) method. Althought this isn't your problem, you should be overriding the paintComponent(..) method, not the paint(..) method.
    But now I want to implement a JScrollPane to be able to scroll a large model.When you create a custom component to do custom painting then you are responsible for determining the preferredSize of the component. So, you need to override the getPreferredSize(...) method to return the preferredSize of your component. Then scrolling will happen automatically when the component is added to a scrollPane.

  • Component paint problem:

    Hi everybody,
    I have just started playing with the Swing library
    recently, and I am experimenting with writing my
    own little customized component--a mini shape
    editor. There is one problem I am encountering.
    The circles that get re-drawn after a re-sizing
    of the window are crooked! However, when the
    circles were initially drawn to the compnent,
    they looked quite smooth. The only difference
    was that the circles were initially rendered
    via the graphics object that was obtained using
    the getGraphics() of the JComponent. I tried
    to force the paint method to use the graphics
    object returned from getGraphics(), but it
    does not rendered! Does anybody know what is
    the difference between these two graphics objects
    --the one returned from getGraphics() and the
    one passed into paint() by the system?
    Why am I getting the crooked line when the
    rendering is done via the paint graphics object?
    Thank you for your time in answering my question.
    --Chris

    Hi Richard,
    Thanks for your comments. As you suggested, I am
    posting some of my experimental code for discussion.
    Here is my derived class from JComponent:
    package SymbolEditorStuffs;
    import javax.swing.JComponent;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    public class SymbolEditorWidget extends JComponent {
    * Constructor for SymbolEditorWidget.
    public SymbolEditorWidget() {
    super();
    canvas = new Canvas(this);     
    // Register mouse listeners to detect mouse
    // events.
    addMouseMotionListener(
    new SymbolEditorMouseMotionAdopter());
    addMouseListener(
    new SymbolEditorMouseAdopter());
    public void toolChanged(String toolName) {
    canvas.toolChanged(toolName);
    public Graphics getWidgetGraphics() {
    // Return this component's graphics object.
    return super.getGraphics();
    protected void paintComponent(Graphics graphics) {
    // Let the base class paints the component first.
    super.paintComponent(graphics);
    // Then the canvas handles the customized
    // component painting.
    canvas.paintCanvas(graphics);
    protected class SymbolEditorMouseMotionAdopter
    extends MouseMotionAdapter {
    public SymbolEditorMouseMotionAdopter() {
    super();
    public void mouseDragged(
    MouseEvent mouseEvent) {
    // Canvas handles mouse drag event.
    canvas.mouseDragged(mouseEvent);
    protected class SymbolEditorMouseAdopter
    extends MouseAdapter {
    public SymbolEditorMouseAdopter() {
    super();
    public void mousePressed(
    MousEvent mouseEvent) {
    // Canvas handles mouse presse events.
    canvas.mousePressed(mouseEvent);     
    public void mouseReleased(
    MouseEvent mouseEvent) {
    // Canvas handles mouse released events.
    canvas.mouseReleased(mouseEvent);     
    public void mouseClicked(
    MouseEvent mouseEvent) {
    // Canvas handles mouse clicked events.
    canvas.mouseClicked(mouseEvent);
    private Canvas canvas;
    As you correctly pointed out, the code for my repaint
    should be situated in the paintComponent(..., which
    I have overriden with my version. I suspect the base
    class' version of this function does something significant;
    therefore, I made a call to the base class version as
    well.
    The mouse events are what I use to manipulate the
    shapes with. Therefore, a shape that has been manipulated via the mouse must re-draw itself.
    Since the MouseEvent class comes with a function
    to access the component that received the mouse
    events, I am able to get hold of the graphics object
    of that component via the getGraphics(... It is
    with this graphics object that I use to redraw the
    manipulated shape.
    However, it is not true that I have two sets of code
    that redraw a shape. All shapes inherit from an
    interface that has a draw(...:
    interface Shape {
    public void draw(Graphics graphics);
    public void undraw(Graphics graphics);
    etc.
    class CircleShape implements Shape {
    public void draw(Graphics graphics) {
    // Draws the circle at the right location.
    etc.
    etc.
    Utimately, all draws for a shape are funnelled into
    this function. The only difference is where the
    graphics object came from. In the paint case,
    the graphics object was handed to me via the
    system. In all other cases, I have gotten hold of
    the graphics object via the getGraphics(,,,
    What struck me as odd was that when I manipalated
    a circle with the mouse, which caused a redraw of
    the circle via the graphics that I obtained through the getGraphcs(..., and then I resided the window, the
    same circle was NOT rendered as around as before
    the resize of the window. Since I called the
    drawOval(... at precisely the same location in both
    times, I expect the circle to be rendered with exactly
    the same roundness. This should be true because
    the drawOval(... is applying the same algorithm to
    render the circle in both cases. The fact that they are
    not the same roundness is the mystery that I cannot
    explain! What I expected was that both rendering
    should have produced the exact same circle! But
    they did not--one is of lower roundness quality than
    the other!!
    --Chris                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Painting Graphics from an Array

    I have a GUI that displays the Towers of Hanoi solution in a JPanel. Everything actually works except for a slight repainting issue.
    Currently I am overriding the paint() function, I know that for my purpose using paintComponent() would probably be the better route, however that's not my issue...
    The images (disks) in my JPanel are not redrawing properly, and I have no idea why...
    Basically:
    - I call setup() to set the number of disks and the co ordinates they should be drawn. (store them in an array)
    - I call moveDisk() to change the co ordinates of each disk as they are being moved.
    - then drawDisk() is called to go through the array of disks and print them.
    currently paint() calls drawDisk() in order to display the current position of all the disks.
    It seems to work fine for the first 2 moves, then disks start disappearing until there is one (the last disk) left...BUT if I print the co ordinates of the disks they seem to be correct, just not drawing.
    could someone take a look at my code and see what is wrong?
    below is the meat of the code, minus the GUI:
        public class HanoiFrame extends javax.swing.JFrame {
        private static final int STATE_SETUP = 0;
        private static final int STATE_ANIMATE = 1;
        private static final int POLE_AREA_HEIGHT = 356;
        private static final int POLE_AREA_WIDTH = 205;
        private static final int DISK_ARC_HEIGHT = 15;
        private static final int DISK_ARC_WIDTH = 15;
        private static final int DISK_HEIGHT = 23;
        private static final int MAX_DISKS = 10;
        private static final int MAX_ANIMATION_DELAY = 30000;
        private static final int MAX_PHYSICAL_DELAY = 100000;
        private static final int MIN_DISKS = 1;
        private static final int MIN_ANIMATION_DELAY = 1;
        private static final int MIN_PHYSICAL_DELAY = 1;
        private static final int EMPTY_CELL_VALUE = -1;
        private static final int CELL_HEIGHT = 25;
        private static final int COLUMNS = 3;
        private static final int ROW = 11;
        private  static final int MILLISECONDS_PER_SECOND = 1000;
        private final static String newline = "\n";
        private static Disk[] disks;
        private static Disk newDisk;
        private static int[][] diskCells;
        public static  int startX = 2;
        public static  int startY = 340;
        public static int setDiskAmount = 0;
        public static int setAnimationDelay = 0;
        public static int  setPhysicalDelay = 0;
        public static int  moveNumber = 0;
        public static int intMovesLeft = 0;
        private boolean  buttonPressed = false;
        private double movesLeft = 0;
        private int windowState = 0;
        /** Creates new form HanoiFrame */
        public HanoiFrame() {
            initComponents();
            /* initialize the "poles" to hold a certain number of "cells */
            this.diskCells = new int[ROW][COLUMNS];
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            /* reset all the variable to original state */
            setDiskAmount = 0;
            setAnimationDelay = 0;
            setPhysicalDelay = 0;
            moveNumber = 0;
            movesLeft = 0;
            intMovesLeft = 0;
            buttonPressed = false;
            windowState = 0;
            this.startButton.setEnabled(true);
            this.diskAmount.setEditable(true);
            this.animationDelay.setEditable(true);
            this.physicalDelay.setEditable(true);
            /* reset all the cell vales to empty (this could be its own function) */
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
            /* reset the content of the TextFields and Area */
            this.diskAmount.setText("");
            this.animationDelay.setText("");
            this.physicalDelay.setText("");
            this.outTextArea.setText("");
            /* repaint the display panel */
            this.hanoiPanel.repaint();
        /* i have no idea why this is here...It was generated by Netbeans when I
         *made the reset button.  As you can see it made 2.  The one above it the same
         *except it contains code.  Since it was automatically generated
         *I cannot delete it.
        private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
        /* is executed when the start button is pressed.
         *also executes a field check and intializes key variables. Finally,
         *it executes the solution and generates the solve time
        private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
            /* check if the program has already been run (without being reset) */
            if (!buttonPressed){
                /* check the fields to ensure the input is correct and useable */
                if (checkFields()){
                    /* give button a pressed status if all info valid */
                    buttonPressed = true;
                    windowState = 1;
                    /* disable the button */
                    this.startButton.setEnabled(false);
                    /* disable the fields */
                    this.diskAmount.setEditable(false);
                    this.animationDelay.setEditable(false);
                    this.physicalDelay.setEditable(false);
                    /* setup the disks on the starting pole */
                    setup();
                    /* initialize the number of moves required. 2 to the power of n minus 1 */
                    movesLeft = Math.pow(2, setDiskAmount) - 1;
                    /* convert the number to an integer */
                    intMovesLeft = (int)movesLeft;
                    /* set the physical delay */
                    setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();               
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HanoiFrame().setVisible(true);
        /*returns the Animation panel area graphics
         *@return Animation area graphics
        public static Graphics getAnimationArea(){
            /* get the usable area of poleA */
            Container clientArea = hanoiPanel;
            //Container clientArea = this.getContentPane();
            /* get the graphics to the display panel*/
            Graphics gfx = clientArea.getGraphics();
            return gfx;
         *set up the requested amount of disks on the first pole
         *@param diskAmount the amount of disks entered by the user
        public void setup(){
            int numberOfDisks = setDiskAmount;
            this.disks = new Disk[numberOfDisks];
            int diskNumber = 0;
            int diskWidth = POLE_AREA_WIDTH - 4;
            int arcH = DISK_ARC_HEIGHT;
            int arcW = DISK_ARC_WIDTH;
            int x = startX;
            int y = startY;
            int row = 0;
            int col = 0;
            /* get the graphics to the display panel*/
            //Graphics gfx = getAnimationArea();
            /* set the color of the disks */
            //gfx.setColor(Color.MAGENTA);
            /* draw the specified number of disks */
            while (diskNumber < numberOfDisks){
                /* reduce the y position */
                y = startY - diskNumber * CELL_HEIGHT;
                /* draw the disk */
                //gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
                /* create a new instance of disk */
                newDisk = new Disk(x, y, diskWidth);
                /* give the new disk an id */
                this.disks[diskNumber] = newDisk;
                /* add the id to the cell array of poleA */
                this.diskCells[row][col] = diskNumber;
                /* make the disk smaller and center */
                x = x + 8;
                diskWidth = diskWidth - 16;
                /* increase disk number */
                diskNumber++;
                /* move to the next row */
                row++;
            repaint();
         *move the disk from a source pole to the destination pole.
         *this should take the source col and destination col to determine where to draw the
         *disk.  It will also need to know to draw the disk in the first available cell
         *in a col
         *@param source the starting pole of the next move
         *@param destination the end pole of the next move
        public void moveDisk(int src, int dest){
            /* the lines below would not be necessary if I were to pass the Graphics
             *gfx object as a parameter.  I may have to use this option in order
             *to work around the current repainting issue */
            /* get the graphics to the display panel*/
            Graphics gfx = getAnimationArea();
            /* get the id of the disk to be moved */
            int disk = getDiskId(src);
            /* get the to and from rows */
            int sourceRow = getRow(src);
            int destinationRow = getRow(dest);
            /* set the co ordintates of the destination */
            int col = dest * POLE_AREA_WIDTH;
            int x = disks[disk].getStartX() + col;
            int y = startY - (destinationRow * CELL_HEIGHT);
            int width = disks[disk].getDiskWidth();
            disks[disk].setStartX(x);
            disks[disk].setStartY(y);
            disks[disk].setDiskWidth(width);
            //System.out.println("startX " + x);
            //System.out.println("startY " + y);
            //System.out.println("destination row " + destinationRow);
            //System.out.println("disk " + disk);
            //System.out.println("Width " + width);
            diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
            /* set the destination row to the disk id */
            diskCells[destinationRow][dest] = disk;
            drawDisk();
            repaint();
        public void drawDisk(){
            int diskNum = setDiskAmount -1;
            int i = 0;
            Graphics gfx = getAnimationArea();
            gfx.setColor(Color.MAGENTA);
            while(diskNum >= 0){
                //System.out.println("here is the disk IDs " + diskNum);
                //System.out.println("the startY during draw " + disks[diskNum].getStartY());
                gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
                diskNum--;
        public void paint(Graphics gfx){
            if(windowState == 0){
                super.paint(gfx);
                setup();
            } else if (windowState == 1){
                super.paint(gfx);
                drawDisk();
         *returns the id of the disk
         *@param col the the designated column
         *@return the disk identification number
        public static int getDiskId(int col){
            int diskIdent = 0;
            /* initialize the row number to max -1, because the array start at 0 */
            int row = MAX_DISKS - 1;
            /* do a cell check while row is greater than 0
             *this is done so that is starts at the top row
             *and moves down
            while (row > EMPTY_CELL_VALUE){
                /* when the first cell that is not -1 is reached get the disk number
                 *that disk will be the smallest in the stack */
                if(diskCells[row][col] != -1){
                    //diskIdent = this.diskCells[row][col];
                    diskIdent =diskCells[row][col];
                    break;
                row--;
            return diskIdent;
         *returns the first available row
         *@param col the designated col
         *@return the first available row number
        public static int getRow(int col){
            int rowNumber = 0;
            /* cycle through the cells until it finds an empty one */
            while (diskCells[rowNumber][col] != -1){
                rowNumber++;
            return rowNumber;
         *calculate the total time it takes for the tower of hanoi game to be
         *solved, given the amount of disk and the amount of time it takes
         *to physically move a disk from one pole to the other.
        public static void totalTime(){
            int timeInSeconds = setPhysicalDelay * intMovesLeft;
            int i = 0;
            int seconds = 0;
            int minute = 0;
            int hour = 0;
            int day = 0;
            int month = 0;
            int year = 0;
            while (i < timeInSeconds){
                if(seconds > 60){
                    minute++;
                    seconds = 0;
                if(minute > 60){
                    hour++;
                    minute = 0;
                if(hour > 24){
                    day++;
                    hour = 0;
                if(day > 30){
                    month++;
                    day = 0;
                if(month > 12){
                    year++;
                    month = 0;
                seconds++;
                i++;
            updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
                    " days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
                    " disks at " + setPhysicalDelay + " seconds per move");
       

    Sorry if my post was a little too cryptic...
    "How do you know? You have a problem you can't solve. Anything could be your issue." Agreed. However, using the process of elimination and debug statments I have been able to narrow the scope of the issue.
    "If you can't solve it by executing the code and adding debug statements how to you expect us to help."If I could solve but "executing code and adding debug statements" there would be no need to post the problem here.
    "We don't know exactly what you are attempting to do."Trying to paint my graphics to a JPanel based on a set of co ordinates.
    "We don't know why you are passing the Graphics object around."Why not? is it impossible to do it this way?
    "The big problem is in the alogorithm you use to determine the location of each component."Who said you couldn't read minds?
    "If you are using some kind of animation then I would use a Timer to schedule the moving of components. I don't even see how you are doing this in your code."Sorry I guess stating that I didn't post my entire code may have threw things off...I do use a timer in a seperate class. I will include it in the next post.
    "I can't tell if you are using Threads of not."guess you overlooked these lines of code:
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();   Here is the code once again:
    public class HanoiFrame extends javax.swing.JFrame {
        private static final int STATE_SETUP = 0;
        private static final int STATE_ANIMATE = 1;
        private static final int POLE_AREA_HEIGHT = 356;
        private static final int POLE_AREA_WIDTH = 205;
        private static final int DISK_ARC_HEIGHT = 15;
        private static final int DISK_ARC_WIDTH = 15;
        private static final int DISK_HEIGHT = 23;
        private static final int MAX_DISKS = 10;
        private static final int MAX_ANIMATION_DELAY = 30000;
        private static final int MAX_PHYSICAL_DELAY = 100000;
        private static final int MIN_DISKS = 1;
        private static final int MIN_ANIMATION_DELAY = 1;
        private static final int MIN_PHYSICAL_DELAY = 1;
        private static final int EMPTY_CELL_VALUE = -1;
        private static final int CELL_HEIGHT = 25;
        private static final int COLUMNS = 3;
        private static final int ROW = 11;
        private  static final int MILLISECONDS_PER_SECOND = 1000;
        private final static String newline = "\n";
        private static Disk[] disks;
        private static Disk newDisk;
        private static int[][] diskCells;
        public static  int startX = 2;
        public static  int startY = 340;
        public static int setDiskAmount = 0;
        public static int setAnimationDelay = 0;
        public static int  setPhysicalDelay = 0;
        public static int  moveNumber = 0;
        public static int intMovesLeft = 0;
        private boolean  buttonPressed = false;
        private double movesLeft = 0;
        private int windowState = 0;
        /** Creates new form HanoiFrame */
        public HanoiFrame() {
            initComponents();
            /* initialize the "poles" to hold a certain number of "cells */
            this.diskCells = new int[ROW][COLUMNS];
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            /* reset all the variable to original state */
            setDiskAmount = 0;
            setAnimationDelay = 0;
            setPhysicalDelay = 0;
            moveNumber = 0;
            movesLeft = 0;
            intMovesLeft = 0;
            buttonPressed = false;
            windowState = 0;
            this.startButton.setEnabled(true);
            this.diskAmount.setEditable(true);
            this.animationDelay.setEditable(true);
            this.physicalDelay.setEditable(true);
            /* reset all the cell vales to empty (this could be its own function) */
            for (int row = ROW - 1;row >= 0; row--) {
                for (int col = 0;col < COLUMNS ; col++) {
                    diskCells[row][col] = EMPTY_CELL_VALUE;
            /* reset the content of the TextFields and Area */
            this.diskAmount.setText("");
            this.animationDelay.setText("");
            this.physicalDelay.setText("");
            this.outTextArea.setText("");
            /* repaint the display panel */
            this.hanoiPanel.repaint();
        /* i have no idea why this is here...It was generated by Netbeans when I
         *made the reset button.  As you can see it made 2.  The one above it the same
         *except it contains code.  Since it was automatically generated
         *I cannot delete it.
        private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
        /* is executed when the start button is pressed.
         *also executes a field check and intializes key variables. Finally,
         *it executes the solution and generates the solve time
        private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {                                         
            /* check if the program has already been run (without being reset) */
            if (!buttonPressed){
                /* check the fields to ensure the input is correct and useable */
                if (checkFields()){
                    /* give button a pressed status if all info valid */
                    buttonPressed = true;
                    windowState = 1;
                    /* disable the button */
                    this.startButton.setEnabled(false);
                    /* disable the fields */
                    this.diskAmount.setEditable(false);
                    this.animationDelay.setEditable(false);
                    this.physicalDelay.setEditable(false);
                    /* setup the disks on the starting pole */
                    setup();
                    /* initialize the number of moves required. 2 to the power of n minus 1 */
                    movesLeft = Math.pow(2, setDiskAmount) - 1;
                    /* convert the number to an integer */
                    intMovesLeft = (int)movesLeft;
                    /* set the physical delay */
                    setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
                    /* create and start a new thread.  This is EXTREMELY important
                     *as it allows for GUI to be repainted while the soulution
                     *is animated */
                    SolveEngine s = new SolveEngine();
                    s.start();
         *Check all the fields at once to ensure that they are valid
        private boolean checkFields(){
            String numberOfDisks = null;
            String animationDelay = null;
            String physicalDelay = null;
            numberOfDisks = this.diskAmount.getText();
            animationDelay = this.animationDelay.getText();
            physicalDelay = this.physicalDelay.getText();
            /* initiate my array of error messages */
            ArrayList errMsg = new ArrayList(0);
            /* check if the number of disks was left blank */
            if (numberOfDisks.equals("")){
                errMsg.add("Please enter the Number of Disks (MAX " + MAX_DISKS + ")");
            }else{
                /* check if the input given is valid */
                try {
                    /* parse the disk amount entered into an integer */
                    setDiskAmount = Integer.parseInt(numberOfDisks);
                    /* check the # of disks entered is greater than 0 and less than 10 */
                    if (setDiskAmount < MIN_DISKS){
                        errMsg.add("Number of Disks must be greater than " + MIN_DISKS);
                    } else if (setDiskAmount > MAX_DISKS){
                        errMsg.add("Number of Disks must be less than" + MAX_DISKS);
                } catch (NumberFormatException ex) {
                    errMsg.add("Number of Disks must be a Number");
            /* check if animation delay was left blank */
            if (animationDelay.equals("")){
                errMsg.add("Please enter disk Animation Delay");
            } else {
                /* check if the input given is valid */
                try {
                    /* parse the animation delay entered into an integer */
                    setAnimationDelay = Integer.parseInt(animationDelay);
                    /* check range of animation delay */
                    if (setAnimationDelay < MIN_ANIMATION_DELAY){
                        errMsg.add("Animation Delay must be greater than 0");
                    } else if (setAnimationDelay > MAX_ANIMATION_DELAY){
                        errMsg.add("Animation Delay must be less than " + MAX_ANIMATION_DELAY);
                } catch (NumberFormatException ex) {
                    errMsg.add("Animation Delay must be a Number");
            /* check if physical delay was left blank */
            if (physicalDelay.equals("")){
                errMsg.add("Please enter the Physical disk delay");
            } else {
                /* check if the input given is valid */
                try {
                    /* parse the physical delay entered into an integer */
                    setPhysicalDelay = Integer.parseInt(physicalDelay);
                    /* check check the range of the physical delay */
                    if (setPhysicalDelay < MIN_PHYSICAL_DELAY){
                        errMsg.add("Physical Delay must be greater than 0");
                    } else if (setPhysicalDelay > MAX_PHYSICAL_DELAY){
                        errMsg.add("Physical Delay must be less than " + MAX_PHYSICAL_DELAY);
                } catch (NumberFormatException ex) {
                    errMsg.add("Physical Delay must be a Number");
            /* if there is any problem, add the message to the popup and display */
            if (!errMsg.isEmpty()){
                JOptionPane.showMessageDialog(this, errMsg.toArray());
                return false;
            return true;
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new HanoiFrame().setVisible(true);
        /*returns the Animation panel area graphics
         *@return Animation area graphics
        public static Graphics getAnimationArea(){
            /* get the usable area of poleA */
            Container clientArea = hanoiPanel;
            //Container clientArea = this.getContentPane();
            /* get the graphics to the display panel*/
            Graphics gfx = clientArea.getGraphics();
            return gfx;
         *set up the requested amount of disks on the first pole
         *@param diskAmount the amount of disks entered by the user
        public void setup(){
            int numberOfDisks = setDiskAmount;
            this.disks = new Disk[numberOfDisks];
            int diskNumber = 0;
            int diskWidth = POLE_AREA_WIDTH - 4;
            int arcH = DISK_ARC_HEIGHT;
            int arcW = DISK_ARC_WIDTH;
            int x = startX;
            int y = startY;
            int row = 0;
            int col = 0;
            /* get the graphics to the display panel*/
            //Graphics gfx = getAnimationArea();
            /* set the color of the disks */
            //gfx.setColor(Color.MAGENTA);
            /* draw the specified number of disks */
            while (diskNumber < numberOfDisks){
                /* reduce the y position */
                y = startY - diskNumber * CELL_HEIGHT;
                /* draw the disk */
                //gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
                /* create a new instance of disk */
                newDisk = new Disk(x, y, diskWidth);
                /* give the new disk an id */
                this.disks[diskNumber] = newDisk;
                /* add the id to the cell array of poleA */
                this.diskCells[row][col] = diskNumber;
                /* make the disk smaller and center */
                x = x + 8;
                diskWidth = diskWidth - 16;
                /* increase disk number */
                diskNumber++;
                /* move to the next row */
                row++;
            repaint();
         *move the disk from a source pole to the destination pole.
         *this should take the source col and destination col to determine where to draw the
         *disk.  It will also need to know to draw the disk in the first available cell
         *in a col
         *@param source the starting pole of the next move
         *@param destination the end pole of the next move
        public void moveDisk(int src, int dest){
            /* the lines below would not be necessary if I were to pass the Graphics
             *gfx object as a parameter.  I may have to use this option in order
             *to work around the current repainting issue */
            /* get the graphics to the display panel*/
            Graphics gfx = getAnimationArea();
            /* get the id of the disk to be moved */
            int disk = getDiskId(src);
            /* get the to and from rows */
            int sourceRow = getRow(src);
            int destinationRow = getRow(dest);
            /* set the co ordintates of the destination */
            int col = dest * POLE_AREA_WIDTH;
            int x = disks[disk].getStartX() + col;
            int y = startY - (destinationRow * CELL_HEIGHT);
            int width = disks[disk].getDiskWidth();
            disks[disk].setStartX(x);
            disks[disk].setStartY(y);
            disks[disk].setDiskWidth(width);
            //System.out.println("startX " + x);
            //System.out.println("startY " + y);
            //System.out.println("destination row " + destinationRow);
            //System.out.println("disk " + disk);
            //System.out.println("Width " + width);
            diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
            /* set the destination row to the disk id */
            diskCells[destinationRow][dest] = disk;
            drawDisk();
            repaint();
            String output = "";
            //must initialize row to max - 1 and increment 'til = 0
            //since the array position starts at 0
            //this will print the array from the top down
            for (int row = ROW - 1;row >= 0; row--) {
                for (int colm = 0;colm < COLUMNS ; colm++) {
                    output = output + diskCells[row][colm];
                output = output + "\n";
            System.out.println(output);
            System.out.println(newline);
        public void drawDisk(){
            int diskNum = setDiskAmount -1;
            int i = 0;
            Graphics gfx = getAnimationArea();
            gfx.setColor(Color.MAGENTA);
            while(diskNum >= 0){
                //System.out.println("here is the disk IDs " + diskNum);
                //System.out.println("the startY during draw " + disks[diskNum].getStartY());
                gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
                diskNum--;
        public void paint(Graphics gfx){
            if(windowState == 0){
                super.paint(gfx);
                setup();
            } else if (windowState == 1){
                super.paint(gfx);
                drawDisk();
         *returns the id of the disk
         *@param col the the designated column
         *@return the disk identification number
        public static int getDiskId(int col){
            int diskIdent = 0;
            /* initialize the row number to max -1, because the array start at 0 */
            int row = MAX_DISKS - 1;
            /* do a cell check while row is greater than 0
             *this is done so that is starts at the top row
             *and moves down
            while (row > EMPTY_CELL_VALUE){
                /* when the first cell that is not -1 is reached get the disk number
                 *that disk will be the smallest in the stack */
                if(diskCells[row][col] != -1){
                    //diskIdent = this.diskCells[row][col];
                    diskIdent =diskCells[row][col];
                    break;
                row--;
            return diskIdent;
         *returns the first available row
         *@param col the designated col
         *@return the first available row number
        public static int getRow(int col){
            int rowNumber = 0;
            /* cycle through the cells until it finds an empty one */
            while (diskCells[rowNumber][col] != -1){
                rowNumber++;
            return rowNumber;
         *calculate the total time it takes for the tower of hanoi game to be
         *solved, given the amount of disk and the amount of time it takes
         *to physically move a disk from one pole to the other.
        public static void totalTime(){
            int timeInSeconds = setPhysicalDelay * intMovesLeft;
            int i = 0;
            int seconds = 0;
            int minute = 0;
            int hour = 0;
            int day = 0;
            int month = 0;
            int year = 0;
            while (i < timeInSeconds){
                if(seconds > 60){
                    minute++;
                    seconds = 0;
                if(minute > 60){
                    hour++;
                    minute = 0;
                if(hour > 24){
                    day++;
                    hour = 0;
                if(day > 30){
                    month++;
                    day = 0;
                if(month > 12){
                    year++;
                    month = 0;
                seconds++;
                i++;
            updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
                    " days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
                    " disks at " + setPhysicalDelay + " seconds per move");
         *add the message to the diplay window
         *currently this is not necessary, but may be required to
         *dynamically display the contents of message into the text area
         *@param message the message to be added/appended the the text area
        public static void updateMessageCenter(String message){
            /* append text to the message */
            outTextArea.append(message + newline);
            /* ensure the the most recent line is viewable - auto scroll */
            outTextArea.setCaretPosition(outTextArea.getDocument().getLength());
        public class SolveEngine extends Thread {
            /** Creates a new instance of SolveEngine */
            public SolveEngine() {
            public void run(){
                /* start the engine/animation */
                solutionEngine(HanoiFrame.setDiskAmount,0, 2, 1);
                /* calculate and print the total time after the solution is complete */
                HanoiFrame.totalTime();
         *the recursive solution to the Towers of Hanoi problem
         *@param diskAmount the number of disks that need to be moved
         *@param start the identity of the starting column
         *@param end the identity of the ending column
         *@param temp the identity of the temporary column
            public void solutionEngine(int diskAmount,int start, int end, int temp){
                int disks = diskAmount;
                int startPole = start;
                int endPole = end;
                int tempPole = temp;
                try {
                    if ( disks == 1 ) {
                        HanoiFrame.moveNumber++;
                        HanoiFrame.updateMessageCenter("Moving disk from  "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
                        /* delay the movement of the disk */
                        Thread.sleep(HanoiFrame.setAnimationDelay);
                        /* move the disk */
                        moveDisk(startPole, endPole);
                    } else {
                        solutionEngine( disks - 1, startPole, tempPole, endPole);
                        HanoiFrame.moveNumber++;
                        HanoiFrame.updateMessageCenter("Moving disk from  "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
                        /* delay the movement of the disk */
                        Thread.sleep(HanoiFrame.setAnimationDelay);
                        moveDisk(startPole, endPole);
                        solutionEngine( disks - 1, tempPole, endPole, startPole);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        }

  • What's the difference between paint and paintComponent?

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

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

  • A new AWT/Swing?

    I have a question for the community.
    IMHO, and I am not alone, AWT/Swing have major flaws that really ought to be fixed. Probably, because the APIs themselves are seriously flawed, what is required is a replacement for Swing.
    How would one go about proposing such a thing and getting Sun's support?
    Specific issues:
    1) A set of specific design rules should be codified, which all conforming components, layout managers, UIs, etc., should obey. Along with the rules, there should be automated tests, so that it could be confirmed whether components, layout managers, UIs, etc., work correctly.
    Currently, Swing and 3rd party components often do not work well together, for reasons such as
    a) Highly irrational behavior of layout managers. Currently, none of the AWT/Swing layout managers behave in a reasonable way under all circumstances, with the possible exception of BorderLayout. Also, layout managers use constraints in inconsistent ways, and they are ill-suited to control by GUI builders.
    b) Failure to use minimumSize, preferredSize, and size consistently.
    c) Inconsistent use of UIs. What is the division of responsibility between the UI, layout managers, L&F, and the main class(es)?
    2) Software design rules. For example, there is currently at least one Swing class that alters its behavior depending on which container it is placed in. That violates basic principles of OO development. Perusing the AWT/Swing source code, you will find plenty of objectional coding practices. It seems that the pressure to maintain backwards compatibility has been a real impediment to "doing things right".
    3) Performance. AWT/Swing are notorious for various performance problems, including
    a) Non-linear CPU cost associated with building certain graphical data structures (combo-boxes, for one).
    b) Layout managers that call getMinimumSize or getPreferredSize on child components multiple times. Currently, the layout managers are the CPU bottleneck in many AWT/Swing GUIs.
    c) Some text components are almost unbelievably slow. Try scrolling a lot of text through a JTextArea and you will be disappointed.
    d) The current validation logic is extremely complex, inefficient, and undocumented. I count approximately 15 basic API methods that affect how and when components are repainted. I defy ANYONE to explain how it all works. The typical result is that repaints occur FAR more often than is necessary.
    A lot of optimization is required to fix these problems. That means automating tests, profiling, removing extra repaints, CPU bottlenecks, etc.
    4) Excessive complexity of the APIs. For example, it seems that building practical tables and trees is harder than it should be. The APIs are complex and documentation obscure or lacking in detail. Also, the separation between model and view is often tainted. It shouldn't be necessary to do so much conversion between model and view indices, for example. A basic set of model classes should be shared by all components that use underlying data models. These model classes should support standard functionality such as filtering, sorting, etc.
    5) No portable remote operation. Yes, I am familiar with SAWT (slow and buggy), and the possibility of using X11 remotely when the Java application is run on a *nix platform (slow over a high-latency network such as the Internet and unusable on Windows systems).  There does not seem to be a usable, universal solution.
    Yes, I am familiar with SWT. However, for a variety of reasons, I believe that the AWT approach is superior. SWT is more platform dependent and it has the X11 reverse-object-orientation in which child classes know about their parents. I have done some performance testing, which suggests that
    1) SWT layout managers are faster than their corresponding AWT/Swing managers
    2) Most other graphics, including 2D graphics, are faster in AWT/Swing than SWT.
    I am sure that SWT encapsulates some good ideas. However, it seems that if the efficiency of validation and layouts could be improved, then AWT/Swing performance would be excellent, while maintaining OO and platform-independent characteristics.
    Possibly, these issues could be worked out piecemeal. For example, a new, rational set of layout managers could be developed entirely independently.
    Other issues, such as defining how UIs, L&F, and component classes should be architected, are going to be more problematic. Creating order in the current chaos will be difficult.
    Any ideas?

    >
    How would one go about proposing such a thing and
    getting Sun's support?
    As for proposing such a thing, you can always become a member of the Java Community Process Program (it's free for individual members): http://www.jcp.org/en/home/index. As a member you can post a Java Specification Request with your suggestions. If you want to operate on a smaller scale you can report bugs to the bug database.
    As for getting Sun's support....well, good luck! :-)

  • TCL/Tk- Awt- Swing

    This is my first Java code. I am attempting to use Java for an applet
    that was originally in TCL/Tk. My first pass used just Awt. Now I have
    a Swing version.
    Linux 2.4.8-26mdk
    java version "1.4.0_02"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0_02-b02)
    Java HotSpot(TM) Client VM (build 1.4.0_02-b02, mixed mode)
    appletviewer
    The Awt version works as I expect. The Swing version also works as
    expected except that the filled arc does not display correctly when
    the arc to be displayed is smaller than the previous one.
    AwtCircle.java:
    package org.emle.equipment;
    import java.applet.*;
    import java.awt.*;
    import javax.swing.*;
    public class AwtCircle extends Applet
      private int fractionDenominator;
      private double decimalValue;
      private Button dButtons[] = new Button[9];
      public void init ()
        fractionDenominator = 4;
        decimalValue = 1.0 / (double)fractionDenominator;
        Box dBox = Box.createHorizontalBox();
        for (int ii=2; ii<=8; ii++)
          dButtons[ii] = new Button("1/" + ii);
          dBox.add(dButtons[ii]);
        } this.add(dBox);
      public void paint(Graphics argG)
        argG.setColor(Color.white);
        argG.fillRect(0, 0, 500, 500);
        argG.setColor(Color.lightGray);
        argG.fillArc(100, 50, 100, 100, 0, (int)(decimalValue * 360.0));
      public boolean action(Event argE, Object argO)
        for (int ii=2; ii <= 8; ii++)
          if (argE.target == dButtons[ii])
            fractionDenominator = ii;
        decimalValue = 1.0 / (double)fractionDenominator;
        showStatus("1/" + fractionDenominator);
        paint (getGraphics());
        return true;
    SwingCircle.java:
    package org.emle.equipment;
    public class SwingCircle extends javax.swing.JApplet
      implements java.awt.event.ActionListener
      private int fractionDenominator;
      private double decimalValue;
      private java.awt.Button dButtons[] = new java.awt.Button[9];
      public void init ()
        fractionDenominator = 4;
        decimalValue = 1.0 / (double)fractionDenominator;
        javax.swing.Box dBox = javax.swing.Box.createHorizontalBox();
        for (int ii=2; ii<=8; ii++)
          dButtons[ii] = new java.awt.Button("1/" + ii);
          dBox.add(dButtons[ii]);
          dButtons[ii].addActionListener(this);
        } getContentPane().add(dBox,java.awt.BorderLayout.SOUTH);
      public void paint(java.awt.Graphics argG)
        argG.setColor(java.awt.Color.white);
        argG.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
        argG.setColor(java.awt.Color.lightGray);
        argG.fillArc(100, 50, 100, 100, 0, (int)(decimalValue * 360.0));
        dButtons[fractionDenominator].requestFocus();
      public void actionPerformed(java.awt.event.ActionEvent argE)
        String cmd = argE.getActionCommand();
        for (int ii=2; ii <= 8; ii++)
          if (dButtons[ii].getActionCommand().equals(cmd))
            fractionDenominator = ii;
        decimalValue = 1.0 / (double)fractionDenominator;
        showStatus("1/" + fractionDenominator);
        paint(getGraphics());
        return;
    C.W.Holeman II
    [email protected] http://MistyMountain.org/~cwhii
    Remove the fives Send spam to [email protected]

    Cimi has made tcl/tk-cvs packages.
    http://bbs.archlinux.org/viewtopic.php? … light=cimi

  • Help overloading Component.paint()

    I can't seem to figure out what I'm doing wrong here. I haven't used a null LayoutManager in a while, so there is probably something I'm missing or forgetting. Anyhows, here is some sample code that is supposed draw a Panel with 7 rectangular boxes in one horizontal line. I built an inner class extending Component for each of the boxes, overloading paint to draw a rectangle. For some reaon, it only draws one of the boxes. Any help would be greatly appreciated. Here's the source:
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class Test extends Frame
         public Test()
              super("test");
              setSize(586, 370);
              Panel panel = new Panel();
              panel.setLayout(null);
              panel.setBackground(Color.blue);
              panel.setSize(586, 370);
              for (int i = 0; i < 7; i++)
                   TestComp comp = new TestComp();
                   int x = (12 * (i + 1)) + (75 * i);
                   comp.setBounds(x, 20, 70, 95);
                   panel.add(comp);
              add(panel);
              // so it'll close on exit
              addWindowListener( new WindowAdapter() {
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
         public class TestComp extends Component
              public TestComp()
                   super();
                   setSize(70, 95);
              public void paint(Graphics g)
                   // draw white rect
                   g.setColor(Color.white);
                   g.fillRect( getLocation().x, getLocation().y, 70, 95);
              public void paintAll(Graphics g)
                   paint(g);
         public static final void main(String args[])
              (new Test()).setVisible(true);
         }

    The problem in your paint() method.
    You use getLocation() but this location is relative to
    the parent's coordinate space.
    And clip region in Graphics is in Component's coordinates.
    Thus you try to draw outside of clip region.
    To correct your test you should draw(0, 0, 70, 95)

  • Component painted three times

    Hello
    I have an AWT application containing a frame F1. This frame contains combos and buttons,
    and another frame F2. Inside this frame F2, I have a TableBean component (GNU table for
    AWT). When I show (only first time) frame F1, table component is painted three times. How can I
    to dectect this component is already painted?. I don�t know how to use paint() or update().
    Many thanks for your help.
    tablaDatosListadoComercio = new tstuder.java.lib.component.table.Table(colDefs,linesComercio);
    tablaDatosListadoComercio.getTitlebar().setBackground(java.awt.Color.blue);
    tablaDatosListadoComercio.getTitlebar().setForeground(java.awt.Color.white);
    tablaDatosListadoComercio.setSelectionMode(tstuder.java.lib.component.table.DataArea.SELECT_ONE);
    tablaDatosListadoComercio.setHorizontalScrollMode(tstuder.java.lib.component.table.Table.HORIZONTAL_SCROLLBAR_OFF);
    panelTablaLstComercio.add(tablaDatosListadoComercio);
    ((java.awt.CardLayout)getLayout()).show(this,"panelDatosListadoComercio");

    I was talking with a co-worker about this kind of issue just yesterday - this isn't a simple problem at all.
    Basically, you (the application programmer) don't have a lot of control over how many times your paint method is called. The Toolkit (AWT) is responsible for deciding when a component's paint method is called. You, as the application programmer, can hint to AWT that a component needs repainting by calling repaint.
    Do not call paint yourself - AWT will call your paint method whenever it decides it wants to. It has in its own mind the state of everything, and which component needs to be repainted when. Controlling multiple repaints is a difficult problem for any GUI toolkit.
    So here's a bit of theory which will hopefully enlighten, rather than confuse, you.
    What you're doing when building an application is creating a bunch of objects that are meant to play together. The rules of the object behaviors are defined by the AWT (and Swing) Component classes. GUI applications are driven by the dispatch of events to them by the underlying system (in this case, Java, AWT and Swing). The bulk of the code being executed to do a GUI application is the underlying system (Java, AWT and Swing) since it's that underlying system that provides the basic framework for the application to exist in the first place.
    - David

  • How do I paint graphics in a JFrame created by netbeans GUI builder?

    I hope it's ok to ask netbeans questions here. Frustrated with Eclipse I'm trying netbeans. I went through the tutorial for the UI builder and I have no trouble laying out the usual swing widgets like JPanels, JButtons, etc. What I haven't figured out is how to mix ordinary graphics like Graphics.draw() with these components.
    Crude example: 2 JPanels in a JFrame. The one on the left has a JSlider bar. The one on the right has a line or something that gets bigger or smaller according to the slider bar.
    If I weren't using the UI builder I'd create a new class that is an extension of JPanel, and override paintComponent() with my draw commands. If I did that to a JPanel I layed out with the UI builder it would get lumped in with the protected code that's created on the fly and probably erased.
    So how do I mix swing components with ordinary graphics without breaking the netbeans UI builder form?
    Thanks,
    Apchar

    This forum is a Java language forum. The NetBeans site has a mailing list. Nabble forums also has NB forums. The contents of both are crossposted. So, you really should post NB use questions to one of them. Post only Java language questions here.
    You can add custom code to the guarded (blue) code blocks. Open a component's property window and select the code button at the top. This allows you to insert code in numerous locations within the guarded blocks and retain the code.
    You can also click a component's property's ellipsis (...) button to bring up the Property Editor dialog box, then select "Custom Code" from the dropdown list at the top of the dialog.
    Note: the above instructions are for NB 6

  • How can i call the public void paint(Graphics g) method on click of button?

    Hello,
    I have done this before i know its got to do something with the repaint() method but can someone show me with and example and call the paint method using AWT in a frame not in an applet....
    Thank you very much.

    Thank You very Much.... You have cleared all my doubts.
    But my main objective is to display an image in an AWT Frame !!
    here is the code that i have been trying..
    import java.awt.*;
    import java.awt.event.*;
    public class check6 extends Panel
         Frame f;
         Image i;
         public check6()
              f = new Frame("Heading");
              f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e){
                        System.exit(0);
              final Button b1 = new Button("Submit");
              b1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e){
                        repaint();
              i = getImage(getCodeBase(), "titanic.jpg");
              add(b1);
              setLayout(new FlowLayout(FlowLayout.LEFT));
              f.add(this);
              f.setSize(500,500);
              f.setVisible(true);
         public void paint(Graphics g)
              g.drawImage(i,10,10,this);
         public static void main(String args[])
              new check6();
    }

  • Why paint(Graphics) is invoked?

    I see paint (Graphics g) method in many awt.* codes. In most cases the method is not explicitly called in, anyhow it invokes. In the code below - main() calls constructor Why_Paint() which has no reference to paint(Graphics g)?
    import java.awt.*;
    import java.awt.event.*;
    class Why_Paint extends Frame
         Why_Paint()
              setTitle("Why paint() is invoked? ");
              setSize(270, 160);
              setBackground(Color.cyan);
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              setVisible (true);
         public void paint (Graphics g)
             g.setColor(Color.pink);
              g.fillRect(45, 40, 180, 90);     
         public static void main (String args[])
              new Why_Paint();
    }

    Thanx for your response.
    Thus the automatic paint() method invocation is the cause of blinking screen in many java programs?
    I couldn't find any hints/tutorials of customizing automatic invocations (I guess many other methods are called automaticly - main() or init() for example) in my JavaDocs. Can anybody give me an idea of where to look for a link?

  • AWT colour chooser and paint

    Hi, this is quite simple but I don't know how to do it, please help!
    The following code should do the following: click in a colour, and paint with the chosen colour .. I cannot make it paint with the colour I choose :(
    import java.awt.*;
    import java.awt.event.*;
    public class E3Events
         extends Frame
         implements MouseListener, MouseMotionListener
         Color colorActual;
         public static void main(String[] args)
              E3Events e3 = new E3Events();
              e3.setTitle("Paint");
              e3.setSize(500, 500);
              e3.addMouseListener(e3);
              e3.addMouseMotionListener(e3);
              e3.show();
         public void paint(Graphics g)
              g.setColor(Color.GREEN);
              g.fillRect(0, 0, 100, 100);
              g.setColor(Color.YELLOW);
              g.fillRect(100, 0, 100, 100);
              g.setColor(Color.RED);
              g.fillRect(200, 0, 100, 100);
              g.setColor(Color.ORANGE);
              g.fillRect(300, 0, 100, 100);
              g.setColor(Color.BLUE);
              g.fillRect(400, 0, 100, 100);
         public void mouseDragged(MouseEvent e)
              Graphics g = getGraphics();
              g.setColor(colorActual);
              int x = e.getX();
              int y = e.getY();
              g.fillOval(x, y, 10, 10);
         public void mouseClicked(MouseEvent e)
         * @see java.awt.event.MouseListener#mouseEntered(MouseEvent)
         public void mouseEntered(MouseEvent arg0)
         * @see java.awt.event.MouseListener#mouseExited(MouseEvent)
         public void mouseExited(MouseEvent arg0)
         * @see java.awt.event.MouseListener#mousePressed(MouseEvent)
         public void mousePressed(MouseEvent arg0)
         * @see java.awt.event.MouseListener#mouseReleased(MouseEvent)
         public void mouseReleased(MouseEvent arg0)
         * @see java.awt.event.MouseMotionListener#mouseMoved(MouseEvent)
         public void mouseMoved(MouseEvent arg0)
    Thanks a million in advance

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.util.List;
    public class ColorPainting
        public static void main(String[] args)
            ColorPaintPanel cpPanel = new ColorPaintPanel();
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(cpPanel.getColorPanel(), "North");
            f.add(cpPanel);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class ColorPaintPanel extends Panel
        Color color;
        Point lastPoint;
        List liveList, lineList;
        public ColorPaintPanel()
            liveList = new ArrayList();
            lineList = new ArrayList();
            addMouseListener(new Starter());
            addMouseMotionListener(new Generator());
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(color);
            Shape s;
            for(int i = 0; i < liveList.size(); i++)
                s = (Shape)liveList.get(i);
                g2.draw(s);
            for(int i = 0; i < lineList.size(); i++)
                s = (Shape)lineList.get(i);
                g2.draw(s);
        public void update(Graphics g)
            paint(g);
        private class Starter extends MouseAdapter
            public void mousePressed(MouseEvent e)
                lastPoint = e.getPoint();
            public void mouseReleased(MouseEvent e)
                lineList.addAll(liveList);
                liveList.clear();
        private class Generator extends MouseMotionAdapter
            public void mouseDragged(MouseEvent e)
                Point currentPoint = e.getPoint();
                Shape s = new Line2D.Float(lastPoint, currentPoint);
                liveList.add(s);
                lastPoint = currentPoint;
                repaint();
        public Panel getColorPanel()
            final Button
                greenButton = new Button("green"),
                yellowButton = new Button("yellow"),
                redButton = new Button("red"),
                orangeButton = new Button("orange"),
                blueButton = new Button("blue");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    if(button == greenButton)
                        color = Color.green;
                    if(button ==yellowButton)
                        color = Color.yellow;
                    if(button == redButton)
                        color = Color.red;
                    if(button == orangeButton)
                        color = Color.orange;
                    if(button == blueButton)
                        color = Color.blue;
            greenButton.addActionListener(l);
            yellowButton.addActionListener(l);
            redButton.addActionListener(l);
            orangeButton.addActionListener(l);
            blueButton.addActionListener(l);
            Panel panel = new Panel();
            panel.add(greenButton);
            panel.add(yellowButton);
            panel.add(redButton);
            panel.add(orangeButton);
            panel.add(blueButton);
            return panel;
    }

Maybe you are looking for

  • RAW PlugIn bei CS2 funktioniert, Bridge nicht???

    Hallo, ich habe die neue Canon 5D und habe den 3.2 Raw PlugIn installiert. Mein CS2 kann die Raw Dateien erkennen mein Adobe Bridge nicht... Was soll ich da jetzt machen?

  • Connect TV to MAC

    what cables do I need to watch films I buy on my mac on my TV

  • Dynamic screen changes in adobe form

    Hi Experts, I have an adobe form with a form type radio button. Based on the form type selected (radio button), some of the fields on the adobe form should become editable and some uneditable. How is it achievable? Please advise. Thanks, Shobhit

  • Imac boots up in verbose mode after been left overnight!

    Hello I have recently bought a used Imac 2010 model and have upgraded to Mountain Lion all was fine for a few days. Know if I leave my computer overnight and reboot it comes on in text mode which I have to exit to get to the GUI. Also when shutting d

  • Having trouble accessing flickr acct on Apple TV

    Just got ATV and trying to see what ican use flickr for. I cant find my flickr acct when doing a search and dont find it when adding a contact as well. I thought I would be able to log into my acct and view traffic for my pictures. Any ideas? What go