Repaint() doesn't call paintComponent()

first I wnt to mention that these are my first steps in java.
I want to create a rectangle to select a region, therefore I get the position of the mouse, what's already working :)
but i'd like to paint the rectangle when the mouse is clicked. so I thought to call paintComponent() with repaint(), but paintComponent() don't get called. I'm confused and cannot understand what is happeneing there :(
the code:
public class CPaintRect extends JPanel implements MouseListener{
     public int startX, startY;
     public int endX, endY;
     int u = 10;
     public CPaintRect() {
          System.out.println("CpaintRect");
     public void actionPerformed(ActionEvent e){
          this.repaint();
     public void mouseClicked (MouseEvent e){
     public void mouseEntered (MouseEvent e){
     public void mouseExited (MouseEvent e){
     public void mousePressed (MouseEvent e){
          startX = (int) e.getX();
          startY = (int) e.getY();
          System.out.println(startX + " " + startY);
          repaint();
     public void mouseReleased (MouseEvent e){
          endX = e.getX();
          endY = e.getY();
          repaint();
          //System.out.println("position: " + selection);
     public void paintComponent(Graphics g) {
          u+=10;
          System.out.println("paint"); //-->not shown
          g.setColor(Color.red);
          g.drawRect(0, 0, u, u); //just as test           g.drawRect(startX, startY, endX-startX, endY-startY);
sorry for my english, and thanks in advance

You forgot to add the mouseListener
In the constructor, aftet this line System.out.println("CpaintRect");
     addMouseListener(this);
Noah

Similar Messages

  • Calling paintComponent(Graphics g) in another class

    Dear Friends,
    I have a class (Class Pee) where I implemented the paintComponent(Graphics g) and another class (Class Bee) where I generate some datas. My intention is to call the paintComponent(Graphics g) method in class Pee at class Bee to make use of the generated data to draw some figures.
    I imported java.awt .Graphics, java.awt.Graphics2D, Polygon and geom and declared Graphics2D g2d = (Graphics2D) g; as well, but still when I call paintComponent (Graphics g) it fails to recognize the g. What is actually wrong.
    See code:
    Class Pee
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Polygon;
    import javax.swing.JPanel;
    public class Pee extends JPanel{
    private int offset;
    public void paintComponent(Graphics g, int b[], int c[]){
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D) g;
    this.setBackground(Color.white);
    Class Bee
        import java.io.*;
        import java.util.*;
        import java.awt.Graphics;
        import java.awt.Graphics2D;
        import java.awt.geom.*;
        import java.awt.Polygon;
       import Graphic.Pee; //importing Pee Class
    public class Bee{
    int x[];
    int y[];
    // other variable declaration
    public Bee{
    x = new int [5];
    y = new int [5];
    Pee dr = new Pee();
    Graphics2D g2d = (Graphics2D) g;
    //code to generate data
    dr.paintComponent(g,x,y);
    }It always say that "g" cannot be resolved. Please how do I get over this.
    Thanks,
    Jona_T

    Swing calls the paintComponent method when we ask a component to draw itself. We do this by
    calling its repaint method. So the general approach is to change the data in the component
    that does the graphics for us and then ask the component to repaint itself. Swing does the
    rest. One benefit of this way of doing things is that the graphic component keeps the data
    and can render all or any part of it at any time. Trying to get a reference to the
    components graphics context from within another class and using it to draw graphics in the
    graphics component prevents this and the foreign class event code can never know when the
    graphics component needs to be re–rendered.
    So the idea is to keep the graphics/rendering component independent from the event code. The
    event code controls the state (member variables) in the graphics component and tells it when
    to re–render itself.
    There are a lot of (creative) ways of putting these things together. Here's an example.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Random;
    import javax.swing.*;
    public class CallingGraphics implements ActionListener {
        GraphicComponentClass graphicComponent;
        DataGenerationClass   dataGenerator = new DataGenerationClass();
        public void actionPerformed(ActionEvent e) {
            Point2D.Double[] data = dataGenerator.getData();
            graphicComponent.setData(data);
        private JPanel getGraphicComponent() {
            graphicComponent = new GraphicComponentClass();
            return graphicComponent;
        private JPanel getLast() {
            JButton button = new JButton("send data to graphics");
            button.addActionListener(this);
            JPanel panel = new JPanel();
            panel.add(button);
            return panel;
        public static void main(String[] args) {
            CallingGraphics test = new CallingGraphics();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getGraphicComponent());
            f.getContentPane().add(test.getLast(), "Last");
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class GraphicComponentClass extends JPanel {
        Ellipse2D.Double[] circles = new Ellipse2D.Double[0];
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            for(int j = 0; j < circles.length; j++) {
                g2.draw(circles[j]);
        public void setData(Point2D.Double[] p) {
            double w = getWidth();
            double h = getHeight();
            double dia = 75.0;
            circles = new Ellipse2D.Double[p.length];
            for(int j = 0; j < circles.length; j++) {
                double x = p[j].x*(w - dia);
                double y = p[j].y*(h - dia);
                circles[j] = new Ellipse2D.Double(x,y,dia,dia);
            repaint();
    class DataGenerationClass {
        Random seed = new Random();
        public Point2D.Double[] getData() {
            int n = seed.nextInt(25);
            Point2D.Double[] locs = new Point2D.Double[n];
            for(int j = 0; j < n; j++) {
                double x = seed.nextDouble();
                double y = seed.nextDouble();
                locs[j] = new Point2D.Double(x, y);
            return locs;
    }

  • Why doesn't calls to my iPhone ring through to my Mac?

    Why doesn't calls to my iPhone ring through to my Mac?

    The following have the requirements and settings and some troubleshooting information:
    Connect your iPhone, iPad, iPod touch, and Mac using Continuity - Apple Support
    Get help using Continuity with iOS 8 and OS X Yosemite - Apple Support

  • Bdc_insert doesn't call

    i have created a bdc for transaction f-43. when i used it for call trasaction then it works successfully but when i use session method then an error occured. the functiom module (bdc_insert) doesn't call.  session is generated but log doesn't generated . can anyone help me?

    REPORT ZWT_MONTH_CONTRIBUTION_UPLOAD
           NO STANDARD PAGE HEADING LINE-SIZE 255.
    TYPE-POOLS : TRUXS.
    TYPES: BEGIN OF TS_WAGETYPE,
             ROW              TYPE I,
             TEMP(10)         TYPE C  
             PERSONNEL_NO(10) ,
             WAGE_TYPE(10)    TYPE C,
             AMOUNT(10)       TYPE C ,
           END OF TS_WAGETYPE.
    TYPES: BEGIN OF TS_FINAL,
            PERSONNEL_NO TYPE PA0001-PERNR,
            BUIS_AREA(10) TYPE C,
            WAGE_TYPE(10) TYPE C,
            AMOUNT        TYPE BSIK-DMBTR,
            NEWUM         TYPE RF05A-NEWUM,
            NEWUM8        TYPE RF05A-NEWUM,
            NEWUM9        TYPE RF05A-NEWUM,
            AMOUNT8       TYPE BSIK-DMBTR,
            AMOUNT9       TYPE BSIK-DMBTR,
            TOTAL_AMOUNT  TYPE BSIK-DMBTR ,
           END OF TS_FINAL.
    TYPES: BEGIN OF TS_MAIN,
             PERSONNEL_NO(10),
             BUIS_AREA(10),
             AMOUNT7(10),
             NEWUM7(2),
             NEWUM8(2),
             NEWUM9(2),
             AMOUNT8(10),
             AMOUNT9(10),
             M_DATE(10),
             TOTAL_AMOUNT(15),
           END OF TS_MAIN.
    TYPES: BEGIN OF TS_PERNR,
            PERSONNEL_NO TYPE PA0001-PERNR,
          END OF TS_PERNR.
    DATA : IT_PAREA    TYPE STANDARD TABLE OF TS_PAREA     INITIAL SIZE 0,
           IT_WAGETYPE TYPE STANDARD TABLE OF TS_WAGETYPE  INITIAL SIZE 0,
           IT_FINAL    TYPE STANDARD TABLE OF TS_FINAL     INITIAL SIZE 0,
           IT_PERNR    TYPE STANDARD TABLE OF TS_PERNR     INITIAL SIZE 0,
           IT_MAIN     TYPE STANDARD TABLE OF TS_MAIN      INITIAL SIZE 0,
           IT_BSIK     TYPE STANDARD TABLE OF TS_BSIK      INITIAL SIZE 0.
    DATA: ITAB LIKE ALSMEX_TABLINE OCCURS 0 WITH HEADER LINE.
    DATA : G_RAW_DATA TYPE TRUXS_T_TEXT_DATA.
    DATA : BEGIN OF BDCDATA OCCURS 0.
            INCLUDE STRUCTURE BDCDATA.
    DATA : END OF BDCDATA.
    DATA : BEGIN OF MESTAB OCCURS 0.
            INCLUDE STRUCTURE BDCMSGCOLL.
    DATA : END OF MESTAB.
    DATA : WA_PAREA       TYPE   TS_PAREA.
    DATA : WA_WAGETYPE    TYPE   TS_WAGETYPE.
    DATA : WA_FINAL       TYPE   TS_FINAL.
    DATA : WA_PERNR       TYPE   TS_PERNR.
    DATA : WA_MAIN        TYPE    TS_MAIN.
    DATA : WA_BSIK        TYPE    TS_BSIK.
    *&                 SELECTION SCREEN
      PERFORM GET_FORMATE_DATE.
      PERFORM GET_BDC_DATA_WAGETYPE.
      ERFORM BDC_F-43_INSERT.
    *&      Form  UPLOADEXCELDATA
          text
    -->  p1        text
    <--  p2        text
    FORM UPLOADEXCELDATA .
      CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
        EXPORTING
          FILENAME                = PA_FILE
          I_BEGIN_COL             = '1'
          I_BEGIN_ROW             = '3'  "Do not require headings
          I_END_COL               = '6'
          I_END_ROW               = '65536'
        TABLES
          INTERN                  = ITAB
        EXCEPTIONS
          INCONSISTENT_PARAMETERS = 1
          UPLOAD_OLE              = 2
          OTHERS                  = 3.
      LOOP AT ITAB.
        WA_WAGETYPE-ROW = ITAB-ROW.
        APPEND WA_WAGETYPE TO IT_WAGETYPE.
      ENDLOOP.
      DELETE ADJACENT DUPLICATES FROM IT_WAGETYPE COMPARING ROW.
      LOOP AT IT_WAGETYPE INTO WA_WAGETYPE.
        LOOP AT ITAB WHERE ROW = WA_WAGETYPE-ROW.
          IF ITAB-COL = '0002'.
            WA_WAGETYPE-TEMP =  ITAB-VALUE .
            MODIFY IT_WAGETYPE FROM WA_WAGETYPE TRANSPORTING TEMP..
          ELSEIF ITAB-COL = '0003'.
            .        WA_WAGETYPE-PERSONNEL_NO =  ITAB-VALUE .
            MODIFY IT_WAGETYPE FROM WA_WAGETYPE TRANSPORTING  PERSONNEL_NO.
          ELSEIF ITAB-COL = '0004'.
            WA_WAGETYPE-WAGE_TYPE =  ITAB-VALUE .
            MODIFY IT_WAGETYPE FROM WA_WAGETYPE TRANSPORTING WAGE_TYPE.
          ELSEIF ITAB-COL = '0005'.
            WA_WAGETYPE-AMOUNT =  ITAB-VALUE .
            MODIFY IT_WAGETYPE FROM WA_WAGETYPE TRANSPORTING AMOUNT.
          ENDIF.
        ENDLOOP.
      ENDLOOP.
      IF SY-SUBRC <> 0.
        WRITE:/ 'Upload Error ', SY-SUBRC.
      ENDIF.
    ENDFORM.                    " UPLOADEXCELDATA
    *&      Form  GET_BDC_DATA_F43
          text
    -->  p1        text
    <--  p2        text
    FORM GET_BDC_DATA_F43 .
      LOOP AT IT_FINAL INTO WA_FINAL.
        WA_MAIN-PERSONNEL_NO  = WA_FINAL-PERSONNEL_NO.
        WA_MAIN-BUIS_AREA     = WA_FINAL-BUIS_AREA.
        WA_MAIN-AMOUNT7       = WA_FINAL-AMOUNT.
        WA_MAIN-NEWUM7        = WA_FINAL-NEWUM.
        WA_MAIN-NEWUM8        = WA_FINAL-NEWUM8.
        WA_MAIN-NEWUM9        = WA_FINAL-NEWUM9.
        WA_MAIN-AMOUNT8       = WA_FINAL-AMOUNT8.
        WA_MAIN-AMOUNT9       = WA_FINAL-AMOUNT9.
        WA_MAIN-M_DATE        = DATE_H.
        WA_MAIN-TOTAL_AMOUNT  = WA_FINAL-TOTAL_AMOUNT.
        APPEND WA_MAIN TO IT_MAIN.
      ENDLOOP.
    ENDFORM.                    " BDC_F-43_INSERT
    *&      Form  BDC_F-43_INSERT
          text
    -->  p1        text
    <--  p2        text
    FORM BDC_F-43_INSERT .
    PERFORM BDC_OPEN_GROUP.
      LOOP AT IT_MAIN INTO WA_MAIN.
        REFRESH BDCDATA.
        CLEAR   BDCDATA.
        IF WA_MAIN-BUIS_AREA = 'IN'.
          PERFORM BDC_DYNPRO      USING 'SAPMF05A' '0100'.
          PERFORM BDC_FIELD       USING 'BDC_CURSOR'
                                        'RF05A-NEWUM'.
          PERFORM BDC_FIELD       USING 'BDC_OKCODE'
                                        '/00'.
          PERFORM BDC_FIELD       USING 'BKPF-BLDAT'
                                         DATE_H_F43.
          PERFORM BDC_FIELD       USING 'BKPF-BLART'
                                        'cp'.
          PERFORM BDC_FIELD       USING 'BKPF-BUKRS'
                                        '044'.
          PERFORM BDC_FIELD       USING 'BKPF-BUDAT'
                                        DATE_H_F43.
          PERFORM BDC_FIELD       USING 'BKPF-MONAT'
                                        I_MONAT .
          PERFORM BDC_FIELD       USING 'BKPF-WAERS'
                                        'INR'.
          PERFORM BDC_FIELD       USING 'BKPF-BKTXT'
                                        'CONTRIBUTION POSTING'.
          PERFORM BDC_FIELD       USING 'FS006-DOCID'
          PERFORM BDC_FIELD       USING 'RF05A-NEWBS'
                                        '39'.
          PERFORM BDC_FIELD       USING 'RF05A-NEWKO'
                                         WA_MAIN-PERSONNEL_NO.
          PERFORM BDC_FIELD       USING 'RF05A-NEWUM'
                                        WA_MAIN-NEWUM7.
          PERFORM BDC_DYNPRO      USING 'SAPMF05A' '0303'.
          PERFORM BDC_FIELD       USING 'BDC_CURSOR'
                                        'RF05A-NEWUM'.
          PERFORM BDC_FIELD       USING 'BDC_OKCODE'
                                        '/00'.
          PERFORM BDC_FIELD       USING 'BSEG-WRBTR'
                                        WA_MAIN-AMOUNT7.
          PERFORM BDC_FIELD       USING 'BSEG-GSBER'
                                        'PF01'.
          PERFORM BDC_FIELD       USING 'BSEG-ZFBDT'
                                         DATE_H_F43.
          PERFORM BDC_FIELD       USING 'RF05A-NEWBS'
                                        '39'.
          PERFORM BDC_FIELD       USING 'RF05A-NEWKO'
                                         WA_MAIN-PERSONNEL_NO.
          PERFORM BDC_FIELD       USING 'RF05A-NEWUM'
                                        WA_MAIN-NEWUM8.
          PERFORM BDC_DYNPRO      USING 'SAPMF05A' '0303'.
          PERFORM BDC_FIELD       USING 'BDC_CURSOR'
                                        'RF05A-NEWUM'.
          PERFORM BDC_FIELD       USING 'BDC_OKCODE'
                                        '/00'.
          PERFORM BDC_FIELD       USING 'BSEG-WRBTR'
                                        WA_MAIN-AMOUNT8.
          PERFORM BDC_FIELD       USING 'BSEG-GSBER'
                                        'PF01'.
          PERFORM BDC_FIELD       USING 'BSEG-ZFBDT'
                                         DATE_H_F43.
          PERFORM BDC_FIELD       USING 'RF05A-NEWBS'
                                        '39'.
          PERFORM BDC_FIELD       USING 'RF05A-NEWKO'
                                         WA_MAIN-PERSONNEL_NO.
          PERFORM BDC_FIELD       USING 'RF05A-NEWUM'
                                       WA_MAIN-NEWUM9.
          PERFORM BDC_DYNPRO      USING 'SAPMF05A' '0303'.
          PERFORM BDC_FIELD       USING 'BDC_CURSOR'
                                        'RF05A-NEWKO'.
          PERFORM BDC_FIELD       USING 'BDC_OKCODE'
                                        '/00'.
          PERFORM BDC_FIELD       USING 'BSEG-WRBTR'
                                        WA_MAIN-AMOUNT9.
          PERFORM BDC_FIELD       USING 'BSEG-GSBER'
                                        'PF01'.
          PERFORM BDC_FIELD       USING 'BSEG-ZFBDT'
                                         DATE_H_F43.
          PERFORM BDC_FIELD       USING 'RF05A-NEWBS'
                                        '01'.
          PERFORM BDC_FIELD       USING 'RF05A-NEWKO'
                                        '1000511'.
          PERFORM BDC_DYNPRO      USING 'SAPMF05A' '0301'.
          PERFORM BDC_FIELD       USING 'BDC_CURSOR'
                                        'BSEG-GSBER'.
          PERFORM BDC_FIELD       USING 'BDC_OKCODE'
                                        '/00'.
          PERFORM BDC_FIELD       USING 'BSEG-WRBTR'
          PERFORM BDC_FIELD       USING 'BSEG-GSBER'
                                        'PF01'.
          PERFORM BDC_FIELD       USING 'BSEG-ZFBDT'
                                        DATE_H_F43.
          PERFORM BDC_DYNPRO      USING 'SAPMF05A' '0301'.
          PERFORM BDC_FIELD       USING 'BDC_CURSOR'
                                        'BSEG-WRBTR'.
          PERFORM BDC_FIELD       USING 'BDC_OKCODE'
                                        '=BU'.
          PERFORM BDC_FIELD       USING 'BSEG-WRBTR'
                                        WA_MAIN-TOTAL_AMOUNT.
          PERFORM BDC_FIELD       USING 'BSEG-GSBER'
                                        'PF01'.
          PERFORM BDC_FIELD       USING 'BSEG-ZFBDT'
                                         DATE_H_F43.
         PERFORM BDC_TRANSACTION USING 'F-43'.
           PERFORM BDC_INSERT .
       PERFORM BDC_TRANSACTION USING 'F-43'.
       ENDIF.
      ENDIF.
      ENDLOOP.
       PERFORM CLOSE_GROUP.
    ENDFORM.                    " GET_BDC_DATA_F43
    *&      Form  bdc_dynpro
          text
         -->P_0174   text
         -->P_0175   text
    FORM BDC_DYNPRO USING PROGRAM DYNPRO.
      CLEAR BDCDATA.
      BDCDATA-PROGRAM  = PROGRAM.
      BDCDATA-DYNPRO   = DYNPRO.
      BDCDATA-DYNBEGIN = 'X'.
      APPEND BDCDATA.
    ENDFORM.                    "BDC_DYNPRO
           Insert field                                                  *
    FORM BDC_FIELD USING FNAM FVAL.
      CLEAR BDCDATA.
      BDCDATA-FNAM = FNAM.
      BDCDATA-FVAL = FVAL.
      APPEND BDCDATA.
    ENDFORM.                    "BDC_FIELD
    *&      Form  bdc_transaction
          text
         -->P_0479   text
    FORM BDC_TRANSACTION  USING  TCODE.
      CALL TRANSACTION TCODE USING  BDCDATA
                      MODE CTUMODE
                      UPDATE 'A'
                      MESSAGES INTO MESTAB.
    ENDFORM.                    " bdc_transaction
    *&      Form  OPEN_GROUP
          text
    -->  p1        text
    <--  p2        text
    FORM OPEN_GROUP .
      B_GROUP = 'PF'.
      SKIP.
      WRITE: /(20) 'Create group'(I01), B_GROUP.
      SKIP.
       open batchinput group
      CALL FUNCTION 'BDC_OPEN_GROUP'
        EXPORTING
          CLIENT = SY-MANDT
          GROUP  = B_GROUP
          USER   = SY-UNAME
          KEEP   = 'X'.
      WRITE: /(30) 'BDC_OPEN_GROUP'(I02),
              (12) 'returncode:'(I05),
                   SY-SUBRC.
    ENDFORM.                    " OPEN_GROUP
    *&      Form  BDC_INSERT
          text
    -->  p1        text
    <--  p2        text
    FORM BDC_INSERT .
      CALL FUNCTION 'BDC_INSERT'
        EXPORTING
          TCODE     = 'F-43'
        TABLES
          DYNPROTAB = BDCDATA.
      REFRESH BDCDATA.
    ENDFORM.                    " BDC_INSERT
    *&      Form  CLOSE_GROUP
          text
    -->  p1        text
    <--  p2        text
    FORM CLOSE_GROUP .
      CALL FUNCTION 'BDC_CLOSE_GROUP'.
      WRITE: /(30) 'BDC_CLOSE_GROUP'(I04),
              (12) 'returncode:'(I05),
                   SY-SUBRC.
    ENDFORM.                    " CLOSE_GROUP

  • Safari doesn't call applet repaint.

    When Safari becomes the top application, after being under another window, it does not call a Java Applet's repaint.
    When playing Runescape (www.runescape.com) this means you have to log into the game again. Firefox does not have this problem.

    You forgot to add the mouseListener
    In the constructor, aftet this line System.out.println("CpaintRect");
         addMouseListener(this);
    Noah

  • Repaint() doesn't seem to work

    I'm just starting to play with 2D graphics, and the repaint method on one of my graphics objects doesn't seem to be working until I resize the outer container.
    I have a class called Grid (subclassed from Component) which paints a rectangular grid, and has an inner class called Square (also subclassed from Component). Grid has a 2-D array of Squares. Square has a method setBackColour which changes the background colour and repaints itself. Grid has a method SelectSquare which displays a square a selected by calling setBackColour on the relevant Square.
    But when I call SelectSquare nothing happens until I do something which causes the whole of the Grid to be repainted (like resizing it), when the new colour suddenly appears. Why is this?
    The code is appended - TestGraphics and GraphPanel were generated by NetBeans so are a bit longer than it need be, and Int2 is just a class with 2 integers for x,y coordinates.
    To see what happens, click on any square, and then resize.
    Thanks in advance,
    Peter
    * Grid.java
    * Created on 02 August 2006, 15:40
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestGraphics;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    * @author PToye
    public class Grid extends Component {
      private static final int THICK_WIDTH=4;
      private static final int THIN_WIDTH=2;
      private static final int DOTTED_WIDTH=2;
      static  final int SQUARE_SIZE=60;
      private final int START_X=0;
      private final int START_Y=0;
      private static final int SQUARES=3;  //standard sudoku
      private static final int BIGSQUARES=SQUARES*SQUARES;
      private static final int TotalSize=(SQUARES+1)*THICK_WIDTH+SQUARES*(SQUARES-1)*THIN_WIDTH+
          BIGSQUARES*SQUARE_SIZE;
      Square[][] squareArray=new Square[BIGSQUARES][BIGSQUARES] ;
      static Font squareFont=new Font("SansSerif",Font.BOLD,20);
      static final Color NORMAL_BACK_COLOUR=Color.LIGHT_GRAY;
      static final Color SELECTED_BACK_COLOUR=Color.PINK;
       * Creates a new instance of Grid
      public Grid() {
        int currentXCoord=START_X;
        int currentYCoord=START_Y;
        currentXCoord=START_X+THICK_WIDTH;
        int currentXIndex=0;
        for (int BigX = 0; BigX < SQUARES; BigX++) {
          for (int LittleX = 0; LittleX < SQUARES; LittleX++) {
            currentYCoord=START_Y+THICK_WIDTH;
            int currentYIndex=0;
            for (int BigY = 0; BigY < SQUARES; BigY++) {
              for (int LittleY = 0; LittleY < SQUARES; LittleY++) {
                squareArray[currentXIndex][currentYIndex]=
                    new Square(currentXCoord,currentYCoord,'4',Color.RED, NORMAL_BACK_COLOUR);
                currentYIndex+=1;
                currentYCoord+=THIN_WIDTH+SQUARE_SIZE;
              currentYCoord+=THICK_WIDTH-THIN_WIDTH;
            currentXIndex+=1;
            currentXCoord+=THIN_WIDTH+SQUARE_SIZE;
          currentXCoord+=THICK_WIDTH-THIN_WIDTH;
      public Dimension getPreferredSize() {
        return new Dimension(TotalSize,TotalSize);
      public void paint(Graphics g) {
        int currentXCoord=START_X;
        int currentYCoord=START_Y;
        int endXCoord=START_X+TotalSize;
        int endYCoord=START_Y+TotalSize;
        Graphics2D g2=(Graphics2D) g;
        g2.setColor(Color.BLACK);
        System.out.println("Painting picture");
        // paint the grid
        for (int BigX = 0; BigX < SQUARES; BigX++) {
          g2.fillRect(currentXCoord,START_Y,THICK_WIDTH,TotalSize);
          g2.fillRect(START_X,currentXCoord,TotalSize,THICK_WIDTH);
          currentXCoord+=THICK_WIDTH+SQUARE_SIZE;
          for (int SmallX = 1; SmallX < SQUARES; SmallX++) {
            g2.fillRect(currentXCoord,START_Y,THIN_WIDTH,TotalSize);
            g2.fillRect(START_X,currentXCoord,TotalSize,THIN_WIDTH);
            currentXCoord+=THIN_WIDTH+SQUARE_SIZE;
        //not forgetting the right & bottom edges
        g2.fillRect(currentXCoord,START_Y,THICK_WIDTH,TotalSize);
        g2.fillRect(START_X,currentXCoord,TotalSize,THICK_WIDTH);
        // paint the squares
        for (int BigX = 0; BigX < BIGSQUARES; BigX++) {
          for (int BigY = 0; BigY < BIGSQUARES; BigY++) {
            squareArray[BigX][BigY].paint(g);
      public Int2 pointToSquare(Point p) {
        double pointX=p.getX();
        double pointY=p.getY();
        int squareX=-1;
        int squareY=-1;
        int currentIndex=0;
        int currentOffset=START_X+THICK_WIDTH;
        searchX:
          for (int i = 0; i < SQUARES; i++) {
            for (int j = 0; j < SQUARES; j++) {
              if (pointX<currentOffset) {
                return null;   // on a black line
              if (pointX<currentOffset+SQUARE_SIZE) {
                squareX=currentIndex;
                break searchX;
              currentOffset+=THIN_WIDTH+SQUARE_SIZE;
              currentIndex++;
            currentOffset+=THICK_WIDTH-THIN_WIDTH;
          if (squareX==-1) {
            return null;
          currentIndex=0;
          currentOffset=START_Y+THICK_WIDTH;
          searchY:
            for (int i = 0; i < SQUARES; i++) {
              for (int j = 0; j < SQUARES; j++) {
                if (pointY<currentOffset) {
                  return null;   // on a black line
                if (pointY<currentOffset+SQUARE_SIZE) {
                  squareY=currentIndex;
                  break searchY;
                currentOffset+=THIN_WIDTH+SQUARE_SIZE;
                currentIndex++;
              currentOffset+=THICK_WIDTH-THIN_WIDTH;
            if (squareY==-1) {
              return null;
            } else {
              return new Int2(squareX,squareY);
      void selectSquare(Int2 squareNos) {
        int x=squareNos.getX();
        int y=squareNos.getY();
        if (x>=0 && x<BIGSQUARES && y>=0 && y<BIGSQUARES) {
          Square s=squareArray[x][y];
          s.setBackColour(SELECTED_BACK_COLOUR);
    //      s.repaint();
      void deselectSquare(Int2 squareNos) {
        int x=squareNos.getX();
        int y=squareNos.getY();
        if (x>=0 && x<BIGSQUARES && y>=0 && y<BIGSQUARES) {
          Square s=squareArray[x][y];
          s.setBackColour(NORMAL_BACK_COLOUR);
    //      s.repaint();
      class Square extends Component {
        // coordinates of upper left pixel
        private int xCoord;
        private int yCoord;
        private char[] value={' '};
        private Color textColour;
        private Color backColour;
        public Square(int x, int y, char valChar, Color tcol, Color bcol) {
          xCoord=x;
          yCoord=y;
          value[0]=valChar;
          textColour=tcol;
          backColour=bcol;
        public void paint(Graphics g) {
          Graphics2D g2=(Graphics2D) g;
          g2.setFont(squareFont);
          FontMetrics fm=g2.getFontMetrics();
          g2.setColor(backColour);
          g2.fillRect(xCoord,yCoord,Grid.SQUARE_SIZE,Grid.SQUARE_SIZE);
          g2.setColor(textColour);
          int charHeight=fm.getAscent();
          int charWidth=fm.charWidth('0');
          g2.drawString(new String(value),xCoord+Grid.SQUARE_SIZE/2-charWidth/2,
              yCoord+Grid.SQUARE_SIZE/2+charHeight/2);
        public Dimension getPreferredSize() {
          return new Dimension(Grid.SQUARE_SIZE,Grid.SQUARE_SIZE);
        public void setBackColour(Color backColour) {
          this.backColour = backColour;
          repaint();
        public void setTextColour(Color textColour) {
          this.textColour = textColour;
          repaint();
        public void setValue(char value) {
          this.value[0] = value;
          repaint();
    * GraphPanel.java
    * Created on 02 August 2006, 16:11
    package com.ptoye.TestGraphics;
    import java.awt.BorderLayout;
    import java.awt.Point;
    * @author  PToye
    public class GraphPanel extends javax.swing.JPanel {
      private Grid p;
      private Int2 selectedSquare;
      /** Creates new form GraphPanel */
      public GraphPanel() {
        initComponents();
        p=new Grid();
        add(p,BorderLayout.CENTER);
        setPreferredSize(p.getPreferredSize());
        selectedSquare=null;
      /** 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() {                         
        FormListener formListener = new FormListener();
        setLayout(new java.awt.BorderLayout());
        setPreferredSize(new java.awt.Dimension(500, 500));
        addMouseListener(formListener);
      // Code for dispatching events from components to event handlers.
      private class FormListener implements java.awt.event.MouseListener {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
          if (evt.getSource() == GraphPanel.this) {
            GraphPanel.this.formMouseClicked(evt);
        public void mouseEntered(java.awt.event.MouseEvent evt) {
        public void mouseExited(java.awt.event.MouseEvent evt) {
        public void mousePressed(java.awt.event.MouseEvent evt) {
        public void mouseReleased(java.awt.event.MouseEvent evt) {
      private void formMouseClicked(java.awt.event.MouseEvent evt) {                                 
        int mouseBtn=evt.getButton();
        Point mousePoint=evt.getPoint();
        if (mouseBtn==evt.BUTTON1) {
          Int2 s=p.pointToSquare(mousePoint);
          if (s!=null) {
            if (selectedSquare!=null) {
              System.out.println("Deselect "+selectedSquare.getX()+selectedSquare.getY());
              p.deselectSquare(selectedSquare);
            selectedSquare=s;
            System.out.println("Select "+selectedSquare.getX()+selectedSquare.getY());
            p.selectSquare(s);
    //      p.repaint();
      // Variables declaration - do not modify                    
      // End of variables declaration                  
    * Int2.java
    * Created on 21 October 2006, 12:01
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestGraphics;
    * @author PToye
    public class Int2 {
        private int x;
        private int y;
        Int2(int x, int y ) {
          this.x=x;
          this.y=y;
        public int getX() {
          return x;
        public int getY() {
          return y;
    * TestGraphics.java
    * Created on 01 August 2006, 22:13
    package com.ptoye.TestGraphics;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    * @author  PToye
    public class TestGraphics extends javax.swing.JFrame {
      private GraphPanel p;
      /** Creates new form TestGraphics */
      public TestGraphics() {
        initComponents();
        p=new GraphPanel();
        setContentPane(p);
        setSize(p.getPreferredSize());
        pack();
      /** 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() {
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Testing graphics");
        jMenu1.setText("Menu");
        jMenuBar1.add(jMenu1);
        setJMenuBar(jMenuBar1);
        pack();
       * @param args the command line arguments
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TestGraphics().setVisible(true);
      // Variables declaration - do not modify
      private javax.swing.JMenu jMenu1;
      private javax.swing.JMenuBar jMenuBar1;
      // End of variables declaration
    }

    Here's a way to implement your gui in the two ways mentioned above:
    GridG � graphics approach with limited redrawing for de/selections
    GridC � component approach where the AWT does a lot of the work.
    This second approach resizes okay.
    Everything has been changed to Swing � lightweight components. One difficulty with
    mixing lightweight and heavyweight components is that the heavyweight components are
    rendered above/over/on top of the lightweight components. So, for example, the Grid class
    extending Component is a heavyweight component and will be rendered over any JMenus and
    JMenuItems that extend below the JMenuBar in the JMenu popupMenu during menu selections,
    when you add them, of course. The Grid component will hide/obscure the JMenu lightweight
    components.
    The Int2 class remains unchanged. I did not use the GraphPanel class.
    import java.awt.*;
    import javax.swing.*;
    public class TG extends JFrame {
        private GridG gridG;
        private GridC gridC;
        public TG() {
            setTitle("Testing graphics");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setJMenuBar(getMenus());
            gridG = new GridG();
            gridC = new GridC();
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("graphics", gridG);
            tabbedPane.addTab("component", gridC);
            setContentPane(tabbedPane);
            pack();
            setLocation(200,50);
        private JMenuBar getMenus() {
            JMenu jMenu1 = new JMenu("Menu");
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(jMenu1);
            return menuBar;
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TG().setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GridG extends JPanel {
        private static final int THICK_WIDTH  =  4;
        private static final int THIN_WIDTH   =  2;
        private static final int DOTTED_WIDTH =  2;
        static         final int SQUARE_SIZE  = 60;
        private        final int START_X      =  0;
        private        final int START_Y      =  0;
        private static final int SQUARES      =  3;  //standard sudoku
        private static final int BIGSQUARES = SQUARES*SQUARES;
        private static final int TotalSize=
                     (SQUARES+1)*THICK_WIDTH+SQUARES*(SQUARES-1)*THIN_WIDTH+
                                        BIGSQUARES*SQUARE_SIZE;
        Square[][] squareArray = new Square[BIGSQUARES][BIGSQUARES];
        static Font squareFont = new Font("SansSerif",Font.BOLD,20);
        static final Color NORMAL_BACK_COLOUR   = Color.LIGHT_GRAY;
        static final Color SELECTED_BACK_COLOUR = Color.PINK;
        public GridG() {
            int currentXCoord=START_X;
            int currentYCoord=START_Y;
            currentXCoord=START_X+THICK_WIDTH;
            int currentXIndex=0;
            for (int BigX = 0; BigX < SQUARES; BigX++) {
                for (int LittleX = 0; LittleX < SQUARES; LittleX++) {
                    currentYCoord=START_Y+THICK_WIDTH;
                    int currentYIndex=0;
                    for (int BigY = 0; BigY < SQUARES; BigY++) {
                        for (int LittleY = 0; LittleY < SQUARES; LittleY++) {
                            squareArray[currentXIndex][currentYIndex]=
                                new Square(currentXCoord,currentYCoord,'4',
                                           Color.RED, NORMAL_BACK_COLOUR);
                            currentYIndex+=1;
                            currentYCoord+=THIN_WIDTH+SQUARE_SIZE;
                        currentYCoord+=THICK_WIDTH-THIN_WIDTH;
                    currentXIndex+=1;
                    currentXCoord+=THIN_WIDTH+SQUARE_SIZE;
                currentXCoord+=THICK_WIDTH-THIN_WIDTH;
            addMouseListener(ml);
            setBackground(Color.BLACK);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2=(Graphics2D) g;
            // paint the squares
            for (int BigX = 0; BigX < BIGSQUARES; BigX++) {
                for (int BigY = 0; BigY < BIGSQUARES; BigY++) {
                    squareArray[BigX][BigY].draw(g);
        public Dimension getPreferredSize() {
            return new Dimension(TotalSize,TotalSize);
        /** This could easily become an outer class. */
        private class Square {
            // coordinates of upper left pixel
            private int xCoord;
            private int yCoord;
            private char[] value={' '};
            private Color textColour;
            private Color backColour;
            public Square(int x, int y, char valChar, Color tcol, Color bcol) {
                xCoord=x;
                yCoord=y;
                value[0]=valChar;
                textColour=tcol;
                backColour=bcol;
            public void draw(Graphics g) {
                Graphics2D g2=(Graphics2D) g;
                g2.setFont(squareFont);
                FontMetrics fm=g2.getFontMetrics();
                g2.setColor(backColour);
                g2.fillRect(xCoord,yCoord,Grid.SQUARE_SIZE,Grid.SQUARE_SIZE);
                g2.setColor(textColour);
                int charHeight=fm.getAscent();
                int charWidth=fm.charWidth('0');
                g2.drawString(new String(value),xCoord+Grid.SQUARE_SIZE/2-charWidth/2,
                                                yCoord+Grid.SQUARE_SIZE/2+charHeight/2);
            public void setBackColour(Color backColour) {
                this.backColour = backColour;
            public void setTextColour(Color textColour) {
                this.textColour = textColour;
            public void setValue(char value) {
                this.value[0] = value;
        /** Ths could become an outer class */
        private MouseListener ml = new MouseAdapter() {
            private Int2 selectedSquare;
            public void mousePressed(MouseEvent e) {
                Point mousePoint = e.getPoint();
                Int2 s = pointToSquare(mousePoint);
                if (s != null) {
                    if (selectedSquare != null) {
                        System.out.println("Deselect " + selectedSquare.getX()
                                                       + selectedSquare.getY());
                        int x = selectedSquare.getX();
                        int y = selectedSquare.getY();
                        squareArray[x][y].setBackColour(NORMAL_BACK_COLOUR);
                        squareArray[x][y].draw(getGraphics());
                    selectedSquare = s;
                    System.out.println("Select " + selectedSquare.getX()
                                                 + selectedSquare.getY());
                    int x = s.getX();
                    int y = s.getY();
                    squareArray[x][y].setBackColour(SELECTED_BACK_COLOUR);
                    squareArray[x][y].draw(getGraphics());
            private Int2 pointToSquare(Point p) {
                double pointX=p.getX();
                double pointY=p.getY();
                int squareX=-1;
                int squareY=-1;
                int currentIndex=0;
                int currentOffset=START_X+THICK_WIDTH;
                searchX:
                    for (int i = 0; i < SQUARES; i++) {
                        for (int j = 0; j < SQUARES; j++) {
                            if (pointX<currentOffset) {
                                return null;   // on a black line
                            if (pointX < currentOffset+SQUARE_SIZE) {
                                squareX=currentIndex;
                                break searchX;
                            currentOffset+=THIN_WIDTH+SQUARE_SIZE;
                            currentIndex++;
                        currentOffset+=THICK_WIDTH-THIN_WIDTH;
                if (squareX==-1) {
                    return null;
                currentIndex=0;
                currentOffset=START_Y+THICK_WIDTH;
                searchY:
                    for (int i = 0; i < SQUARES; i++) {
                        for (int j = 0; j < SQUARES; j++) {
                            if (pointY<currentOffset) {
                                return null;   // on a black line
                            if (pointY < currentOffset+SQUARE_SIZE) {
                                squareY=currentIndex;
                                break searchY;
                            currentOffset += THIN_WIDTH+SQUARE_SIZE;
                            currentIndex++;
                        currentOffset += THICK_WIDTH-THIN_WIDTH;
                if (squareY==-1) {
                    return null;
                } else {
                    return new Int2(squareX,squareY);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GridC extends JPanel {
        private static final int THICK_WIDTH  =  4;
        private static final int THIN_WIDTH   =  2;
        static         final int SQUARE_SIZE  = 60;
        private static final int SQUARES      =  3;  //standard sudoku
        private static final int BIGSQUARES = SQUARES*SQUARES;
        private static final int TotalSize  =
                     (SQUARES+1)*THICK_WIDTH+SQUARES*(SQUARES-1)*THIN_WIDTH+
                             BIGSQUARES*SQUARE_SIZE;
        Square[][] squareArray = new Square[BIGSQUARES][BIGSQUARES] ;
        static Font squareFont = new Font("SansSerif",Font.BOLD,20);
        static final Color NORMAL_BACK_COLOUR   = Color.LIGHT_GRAY;
        static final Color SELECTED_BACK_COLOUR = Color.PINK;
        public GridC() {
            setBackground(Color.black);
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            int[] gws = { 1, GridBagConstraints.RELATIVE, GridBagConstraints.REMAINDER };
            setLayout(gridbag);
            for (int j = 0; j < BIGSQUARES; j++) {
                JPanel cell = new JPanel(gridbag);
                cell.setBackground(Color.black);
                gbc.insets = new Insets(1,1,1,1);
                for (int k = 0; k < BIGSQUARES; k++) {
                    int val = j*BIGSQUARES + k + 1;
                    squareArray[j][k]= new Square(val, Color.RED, NORMAL_BACK_COLOUR);
                    squareArray[j][k].addMouseListener(ml);
                    gbc.gridwidth = gws[k % gws.length];
                    cell.add(squareArray[j][k], gbc);
                gbc.insets = new Insets(0,0,0,0);
                if(j/3 < 2)       gbc.insets.bottom = 2;
                if((j+1) % 3 > 0) gbc.insets.right = 2;
                gbc.gridwidth = gws[j % gws.length];
                add(cell, gbc);
        public Dimension getPreferredSize() {
            return new Dimension(TotalSize, TotalSize);
        private class Square extends JPanel {
            String value;
            private Color textColour;
            private Color backColour;
            public Square(int val, Color tcol, Color bcol) {
                value = String.valueOf(val);
                textColour=tcol;
                backColour=bcol;
            protected void paintComponent(Graphics g) {
                Graphics2D g2=(Graphics2D) g;
                g2.setFont(squareFont);
                FontMetrics fm=g2.getFontMetrics();
                g2.setColor(backColour);
                g2.fillRect(0,0,Grid.SQUARE_SIZE,Grid.SQUARE_SIZE);
                g2.setColor(textColour);
                int charHeight=fm.getAscent();
                int charWidth=fm.stringWidth(value);
                g2.drawString(value, Grid.SQUARE_SIZE/2-charWidth/2,
                                     Grid.SQUARE_SIZE/2+charHeight/2);
            public Dimension getPreferredSize() {
                return new Dimension(Grid.SQUARE_SIZE,Grid.SQUARE_SIZE);
            public void setBackColour(Color backColour) {
                this.backColour = backColour;
                repaint();
            public void setTextColour(Color textColour) {
                this.textColour = textColour;
                repaint();
            public void setValue(int value) {
                this.value = String.valueOf(value);
                repaint();
        private MouseListener ml = new MouseAdapter() {
            private Square selectedSquare;
            public void mousePressed(MouseEvent e) {
                Square square = (Square)e.getSource();
                if (selectedSquare != null)
                    selectedSquare.setBackColour(NORMAL_BACK_COLOUR);
                square.setBackColour(SELECTED_BACK_COLOUR);
                selectedSquare = square;
    }

  • Who knows why the "repaint()"doesn't work when ....?

    I use a "while(threadgroup.activeCount()!=0){} "to block the sentence below
    from being excecuted before I finish the thread above, however since this "while"
    the repaint() in the thread above doesn't work , but I have evidence that the thread
    is really going on ( I use Sytem.out.print() to prove this)

    I'm not sure I follow. Try providing a snippet of the relevant code, and we'll see if anybody on the forum can figure it out for you.

  • Why repaint is automatically called

    in the slot machine program below, you try to run it, play once , after that you leave the bet textfield to be 0, and click play again, when you click down the JOptionMessage dialog, three slot is atomatically set back to lemon, but it shoudn't be that, I didn't call repaint in my program, why
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class Slot extends JFrame implements ActionListener,Runnable
         ImageIcon img;
         JButton play;
         JPanel leftCanvas;
         JPanel centerCanvas;
         JPanel rightCanvas;
         JTextField amount;
         JTextField bet;
         SpinThread t1;
         SpinThread t2;
         SpinThread t3;
         Thread t;
         int credit,betAmount;
         AudioClip audioClip=Applet.newAudioClip(this.getClass().getResource("win.au"));
         public Slot(String s) {
         /** Constructor */
          super( s );
          setSize(300,200);
          img = new ImageIcon("images/lemon.gif") ;
          Container c = getContentPane();
          c.setLayout( new BorderLayout() );
          /** Panel with Label showing title */
         JPanel title = new JPanel ();
          title.setFont(new Font("TimesRoman", Font.BOLD, 16));
          title.add(new Label("Slot Machine Simulation"));
          c.add(title, "North");
          /** Panel with 3 Canvases showing pictures */
          JPanel slotPanel = new JPanel(new GridLayout(1, 3));
          leftCanvas = new JPanel();
          centerCanvas = new JPanel();
          rightCanvas = new JPanel() ;
          slotPanel.add(leftCanvas);
          slotPanel.add(centerCanvas);
          slotPanel.add(rightCanvas) ;
          c.add(slotPanel,"Center") ;
          /** the Bottom panel showing the credit, betting amount and play button */
          JPanel messagePanel = new JPanel(new GridLayout(1,3));
          /** credit panel */
          JPanel creditPanel = new JPanel();
          creditPanel.setLayout(new FlowLayout()) ;
          JLabel label1  = new JLabel("Credit") ;
          creditPanel.add(label1) ;
          amount = new JTextField("1000") ;
          amount.setHorizontalAlignment(JTextField.RIGHT) ;
          amount.setEditable(false) ;
          creditPanel.add(amount) ;
          messagePanel.add(creditPanel) ;     
          /** betting panel*/
          JPanel bettingPanel = new JPanel();
          bettingPanel.setLayout(new FlowLayout()) ;
          JLabel label2  = new JLabel("Bet") ;
          bettingPanel.add(label2) ;
          bet = new JTextField(3) ;
          bet.setText("50") ;
          bet.setHorizontalAlignment(JTextField.RIGHT) ;
          bettingPanel.add(bet) ;
          messagePanel.add(bettingPanel) ;
         /** button panel */
          JPanel buttonPanel = new JPanel();
          buttonPanel.setLayout(new FlowLayout()) ;
          play = new JButton("PLAY") ;
          play.addActionListener(this) ;
          buttonPanel.add(play) ;
          messagePanel.add(buttonPanel) ;
         /** add the last panel to the south end */ 
          c.add(messagePanel,"South") ;
          credit=Integer.parseInt(amount.getText());
          betAmount=Integer.parseInt(bet.getText());
       public void paint(Graphics g)
       {  super.paint(g);
              img.paintIcon(leftCanvas,leftCanvas.getGraphics(),0,0);
          img.paintIcon(centerCanvas,centerCanvas.getGraphics(),0,0);
          img.paintIcon(rightCanvas,rightCanvas.getGraphics(),0,0);
       public void check()
       {credit=Integer.parseInt(amount.getText());
        betAmount=Integer.parseInt(bet.getText());
            if(t1.index==t2.index&&t2.index==t3.index&&t3.index==6)
                 credit=credit+1000000;
                 audioClip.play();
                 //Splash win=new Splash();
                 //win.setSize(200,200);
                 //win.setVisible(true);
        else if(t1.index==t2.index&&t2.index==t3.index)
                credit=credit+betAmount*100;
            else if(t1.index==t2.index||t2.index==t3.index||t3.index==t1.index)
                 credit=credit+betAmount*10;
            else
                 credit=credit-betAmount;
            amount.setText(String.valueOf(credit));
            bet.setText("0");
       public void actionPerformed(ActionEvent e)
            if(e.getSource()==play)
                 credit=Integer.parseInt(amount.getText());
            betAmount=Integer.parseInt(bet.getText());
                 if(betAmount<=0)
                 JOptionPane.showMessageDialog(this,"Bet must be positive!");
           else  if(betAmount>100||betAmount>credit)
                 JOptionPane.showMessageDialog(this,"Bet exceed the upper limit(100) or not enough credit!");
           else if(betAmount<credit&&betAmount<=100&&betAmount>0)
                t1=new SpinThread(leftCanvas,20);
            t2=new SpinThread(centerCanvas,40);
            t3=new SpinThread(rightCanvas,60);
            t=new Thread(this);
             t.setPriority(1);
                t1.start();
                 t2.start();
                 t3.start();
                 t.start();
       public void run()
                boolean done=false;
                while(!done)
                    if(!(t1.isAlive()||t2.isAlive()||t3.isAlive()))
                         done=true;
                check();
       public static void main(String[] args)
             Slot mySlot=new Slot("Slot Machine Simulation");
             mySlot.show();
             mySlot.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    class SpinThread extends Thread
         JPanel p;
         int delay;
         ImageIcon[] img={new ImageIcon("images/ball.gif"),
         new ImageIcon("images/bar.gif"),new ImageIcon("images/bell.gif"),
         new ImageIcon("images/fruit.gif"),new ImageIcon("images/lemeon.gif"),
         new ImageIcon("images/seven.gif")};
         int index;
         public SpinThread(JPanel p,int delay)
              super();
              this.p=p;
              this.delay=delay;
         public void run()
              int i=0;
              while(i<delay)
                   index=Math.round((float)Math.random()*5);
                   display(p.getGraphics());
                   try{
                        sleep(delay);
                   }catch(InterruptedException e){;}
                   i++;
         public void display(Graphics g)
           img[index].paintIcon(p,g,0,0);
    }

    That's the way repaint works
    Anytime a java component which lies beneath some other window is uncovered, the UI thread will do a repaint

  • How can we call paintcomponent

    I wrote a program where I should draw some stuff whenever a key is pressed.
    The drawing is done whenever the key is pressed but can be seen only when i resize the window..
    public void keyPressed(KeyEvent e)  {
    Graphics2D g2 = image.createGraphics();
    if(e.getKeyCode()==37)
         System.out.println("left is pressed");
         key=LEFT;
    sp.SnakeMove(key);
    if(e.getKeyCode()==38)
         System.out.println("up is pressed");
    key=UP;
    sp.SnakeMove(key);
    if(e.getKeyCode()==39)
         System.out.println("right is pressed");
    if(e.getKeyCode()==40)
         System.out.println("down is pressed");
    public void SnakeMove(int key)
         //revalidate();
         //repaint();
         int x1,y1;
         System.out.println("key=="+key);
         String str;
          Graphics2D g2 = image.createGraphics();
    switch(key){
    case LEFT:
         str="--";
                g2.drawString(str, 40, 150);
                   g2.drawRect(10,10,100,100);
                   System.out.println("String drawn");
                   revalidate();
                            repaint();
                   break;
    case UP:
         str="|";
            g2.drawString(str, 45, 150);
         System.out.println("String drawn");
         revalidate();
            repaint();
                   break;
    }//end if switch
    repaint();
         }//end of snakeMove function

    Create a BufferedImage and do your custom painting on the buffered image.
    Override the paintComponent() method of a JPanel and use the Graphics.drawImage() method to draw the buffered image. Then whenever you make a change to the buffered image you invoke panel.repaint().
    Also, the handling of KeyStrokes should be done by using [Key Bindings|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]. The tutorial also has a section on custom painting so read that as well.

  • FSCommand doesn't call vbscript in Vista IE7

    Hey All,
    I have web application with small flash movies which call to
    FSCommand though VBScript. In IE6/7 in XP everything works OK about
    2 years.
    Now, we encounter with new problem that the same code doesn't
    work in Vista (SP0 and SP1) IE7. The problem is that "movie"
    parameter is a full URL address. When I set local file path it
    works fine.
    Please, see attached code examples.
    Just last movie is working.....
    Please, help me with this issue.
    Thanks

    I have the same problem as well, my new laptop doesn't recognize my ipod touch either(16gb) though i plugged my brother's ipod shuffle on an my laptop picked it up. The only difference between my old comp (that picked up my itouch) and my laptop is that the laptop has vista and my pc has xp. The only thing i could think of doing would be redownloading the driver for my itouch to my laptop but i couln't find anything to that nature.
    Message was edited by: deltronn

  • Cross-Company Sales and Billing doesn't call BUV transaction settings

    Hello Dear Experts.
    Please help me with the following issue:
    1) The Company consists of Headquater and branches (one legal entity) - several Company codes are set in the system for each unit.
    2) The Contract for deliverying goods/implementation services with the Customer is concluded by the Head Office. Let's assume it's Company Code One.
    3) The goods is delivered by the plant, which is assigned to one of the branches, that is another Company Code in the system - CC2.
    4) Our FI group customised the Transaction BUV - Clearing between company codes by the following IMG path: Financial Accounting (New)-->General Ledger Accounting (New)-->Business Transactions-->Prepare Cross-Company Code Transactions (TCode OBYA).
    Note: This customising on clearing accounts work well during material transfer between Company Codes in MM and operations within Asset Management in FI-AA.
    5) I've created a sales order in CC1. I've pointed that deliverying plant is from CC2. When the billing is posted the system doesn't take the customising from BUV transaction.
    What do you think the problem is about?
    The entry posts in FI should go as shown in the figure above.
    However right now the entries as follows:
    CC1: Debits 1210 (Receivabless); Credits 6010 (Revenues). just within Company Code 1.
    VAT is not shown both here and in the Figure.
    Thanks in advance, Please help me...
    PS: I have customised Intercompany Billing through IV Billing with Internal Customer an so on, but our FI group wants to have another schema with posting as shown in the Figure above within the one step in creating the billing document.

    I'm not familiar with Verizon wanting people to change their plans online.  We just went in to upgrade a phone and they offered to check and see if we were elligible for a discount.
    Yes, you would think she could have easily given me the credit for 6 weeks but after sitting on hold for as long as I have with this situation, when she came back and wasn't interested in checking about it, I didn't have the strength left in chasing down her supervisor to get it.  Fact is, I should have never spent that much time trying to get them to correct their error.  I'm very disappointed that after talking to as many Verizon employees as I did, no one could tell me what happened and how to fix it.  I can not be the only person that had that kind of change with that plan.
    No one has contacted me yet.  I'd be surprised it they did.
    Jennifer

  • PA40 doesn't call bespoke feature ZPA01?

    There is a bespoke feature ZPA01 which was created some years ago and which is now not working when using transaction PA40.
    I have tried debugging the program for this i.e. /1PAPA/FEAT100ZPA01, but this doesn't even stop at my breakpoint which means that this feature is somehow not even accessed. The feature is active, and to make sure i have reactivated it anyway, but to no avail.
    Anybody had this situation before?

    Hi Glen,
    You can check user-exits ZXPADU01, ZXPADU02, ZXPADU03.
    And you can look at dynamic actions table t588z too, there may be a subroutine to trigger feature after IT0000 recorded.

  • Skype doesn't call the right number

    i was given this local number xxx xxx xxxx to skype call a number xxx xxx xxxx  when i call the skype to go a strange person answers the phone, not the person the number was set up for.  please help me correct this.  thanks

    musalim1981 wrote:
    please help me correct this.
    Hello,
    Please file here:
    https://support.skype.com/en/faq/FA1170/How-can-I-​contact-Skype-Customer-Service
    TIME ZONE - US EASTERN. LOCATION - PHILADELPHIA, PA, USA.
    I recommend that you always run the latest Skype version: Windows & Mac
    If my advice helped to fix your issue please mark it as a solution to help others.
    Please note that I generally don't respond to unsolicited Private Messages. Thank you.

  • Why doesn't calling setEditable(false) disable cursoring

    I want to have JFormattedTextField format my date fields for me. It does a good job of it, so why wouldn't I?
    I have a need to display a non-editable date for reference purposes. Unfortunately I discovered that the cursoring is still active when setEditable(false) is called. In order to prevent this, I have had to subclass DateFormatter in order to override getActions() to return null if I don't want incrementing. There are a number of problems with this:
    1) setEditable on JFormattedTextField should have been enough. If I don't want it editable, then I don't want cursoring. I would have thought that was obvious.
    2) Notwithstanding that, the correct method to override for incrementing is really getSupportsIncrement(), but this has no modifier, so is in the 'friendly' status, which means it can only be overridden in the package.
    3) While I can override getActions, this signature leaves itself open to have other actions than "increment" and "decrement" returned . That is, it works now, but if sun adds more actions to the list of actions returned by getActions(), then my override is broken.
    Is there a bug in there somewhere?
    Thanks, Andrew

    1) setEditable on JFormattedTextField should have
    been enough. If I don't want it editable, then I
    don't want cursoring. I would have thought that was
    obvious.Nope not really. What if the user wants to copy some text using the keyboard?

  • JSF 2 @ViewScoped doesn't call @PreDestroy method

    howdy guys!
    i've been tested the jsf ViewScoped in my application but i have a doubt. The managed bean noted with @ViewScoped sometimes does not call the @PreDestroy method.
    See example below
    ViewScopeMB.java
    @ManagedBean
    @ViewScoped
    public class ViewScopeMB implements Serializable {
    private int counter;
    public ViewScopeMB() { }
    @PostConstruct
    public void contruct() {
    System.out.println("iniciando bean");
    this.counter = 0;
    // getters and setters
    public void increment() {
    System.out.println("incrementing...");
    this.counter++;
    public void forceSetView() {
    System.out.println("modificando a viewroot");
    FacesContext context = FacesContext.getCurrentInstance();
    UIViewRoot root = context.getApplication().getViewHandler().createView(context, "/faces/one.xhtml");
    context.setViewRoot(root);
    @PreDestroy
    public void destroy() {
    System.out.println("destroy the bean");
    I'm using f:ajax to incrementing the counter and this work fine, the bean instance is kept, but when i navigate for new page using <a:href for exemple the ViewScopeMB instance is not destroyed. I change my link to <h:commandLink action="rule"... and the @PreDestroy method is called and the finalize method too.
    My question is, this is a correct behavior of JSF 2? If the user use the navigator back button or to type the new url or the button with javascript history.go(-1) my instance of ViewScopeMB will never be destroyed in the user session?
    When i used forceSetView() method to force a new viewRoot the @PreDestroy is called.
    There are way to solve this case?
    Sorry if i not been very clear.
    Anybody help-me?

    For a view scoped bean, PreDestroy must only be called when the view scope is destroyed which happens when something calls FacesContext.setViewRoot(root).
    It's not very surprising that when you don't use JSF controls for navigation then context.setViewRoot(root);is not called.
    Calling context.setViewRoot(root); yourself guarantees that PreDestroy gets called but you'll probably end up calling it more times than you need to in the cases where you use JSF navigation mechanisms.
    You should be careful with that @PreDestroy method though. Some containers e.g (Tomcat) don't always support those methods fully. In particular, @PreDestroy methods are not called when the view gets destroyed after a restart when the webserver had serialized the ViewScoped bean in the current view so I wouldn't be putting billion dollars worth of logic in that method.

Maybe you are looking for

  • How to declare in anonymous block

    Declare CURSOR c_je2acct_othr IS SELECT j.jemq_num, j.ml_retail_account, -- (CASE WHEN j.exer_type = 4 THEN j.sar_shares ELSE j.shares END) shares, -- removed * -1 from sar_shares Manu 12/02/04 /* Commented 02/01/07*/ (CASE WHEN j.exer_type = 4 THEN

  • Compare two tables and log the difference

    Hi, I want to compare two tables and log the difference in new table with the fields as (old value,new value, column name). The column name should be the changes value column

  • Can I use Concatenate function for multiple rows?

    I have a lead list that contains 5000 leads. The format of this list contains address data that is saved in separate columns (ie: address, address 2, city, state, zip). I need this data in 1 column. I tried to use the concatenate function to combine

  • Order Reporting by Create and/or change date

    Hi all, is it possible using business content to report orders based on the date that they were created -OR- changed/canceled (if they were).  My understanding is that BC reports orders by original CREATE date only. Any links or documents_?

  • Submitting a podcast and iTunes approval

    I submitted a podcast/podcast feed a number of weeks ago and it successfully published in iTunes, however a few days after successfully publishing the feed, iTunes removed it from the US store (most likely because of technical difficulties). I then r