Overriding paintComponent ?

Hello,
I'm working with some JScrollBars, but I want to give them a more unique look, because it's for use in a game. But I'm not sure how to repaint them. should I override the paintComponent method, and how will I know all the dimensions of al the parts of the scrollbar? Does anyone have any ideas about this ?
thanks in advance,
Rabon

Hi,
It would be better if you subclassed the UI class (BasicScrollBarUI) and wrote your own paintTrack() and paintThumb() methods. If you want them to be different sizes from the standard values, override getTrackBounds() and getThumbBounds() as well.
Hope that helped,
Ian

Similar Messages

  • Overriding paintcomponent method JButton

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

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

  • Overriding paintComponent but not everything is showing. Should be easy

    The outdent objects are bying drawed and last.
    The others are drown but you can only see them if you move the window arround (when hy needs to repaint constantly)
    @Override
    public void paintComponent(Graphics g) {
         super.paintComponent(g); //JPanel magic
    this.setSize(200,200);
         Graphics2D brush = (Graphics2D) g;
    brush.setBackground(Color.PINK);
    brush.drawOval(150, 150, 50, 150); //visable
    brush.drawOval(150, 150, 50, -150);
    brush.drawLine(15, 15, 100, 5); //visable
    brush.setColor(Color.CYAN);
    brush.fillOval(100,100,50,50); //visable
    brush.drawOval(300, 300, 100, 150);
    brush.setColor(Color.BLUE);
    brush.fillOval(300, 300, 100,150);
    brush.drawOval(250, 250, 50, 150);
    Alle help welcome stuck for a while now.
    Its just includeed in a pannel and the panel in the frame

    I was unable to open your "evil" vi.
    It seems that you already know this, but just in case...
    To customize the apperance of your vi at run-time, in the front panel right-click in the vi icon at the upper-right corner and select "VI Setup..." from the pop-up menu.
    Select "Windows Options" from the menu. Clear the checkmark for those attributes you don't want (Show scroll bars, Show menu bar, etc.)
    Also, I posted an answer about dialog boxes that include an example. It may help you:
    http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RPAGEID=135&HOID=50650000000800000008190000&UCATEGORY_0=_49_%24_6_&UCATEGORY_S=0
    Best regards;
    EJV
    www.vartortech.com

  • Overriding paintComponent() for jInternalFrame to provide transparency

    I am using NetBeans and Swing and have already created a working program. Within the form of the program I have an InternalFrame which consists of a scatterplot on top of a map - the scatterplot consists of pollen data for a selected week which is overlayed on the map. The user is able to select different weeks and thus the scatterplot is updated to reflect this. What I am trying to do is use Java2D and semi-transparency to make the transitions between the scatterplots changing look better i.e. fade out with the old and fade in with the new once the user selects a different week. From a little a research I have reason to believe overriding the paintComponent() for an InternalFrame with something like what is below would be the answer but I am failing miserably, can anyone help? Thanks.
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
            super.paintComponents(g2);
            g2.dispose();
        }

    Hi,
    You may need to set the setOpaque(false) for the JIF content pane.
    Quick refer the links below:
    [http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2006-05/msg00254.html|http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2006-05/msg00254.html]
    [http://forums.sun.com/thread.jspa?threadID=469200&tstart=10186|http://forums.sun.com/thread.jspa?threadID=469200&tstart=10186]
    [http://www.coderanch.com/t/344772/Swing-AWT-SWT-JFace/java/Transparent-JInternalFrame|http://www.coderanch.com/t/344772/Swing-AWT-SWT-JFace/java/Transparent-JInternalFrame]

  • Custom Buttons - Overriding paintComponent

    I am thoroughly confused by the amount of different ways I have seen to make a 'custom' button. In my case my 'custom' button is a button that functions exactly as a JButton but I can set a BufferedImage as the background, and when the mouse is over the button, have a different BufferedImage.
    Here is my CustomButton class:
    public class CustomButton extends JButton
         private BufferedImage unpressed;
         public CustomButton(BufferedImage unpressed)
              this.setContentAreaFilled(false);
              this.setBorder(null);
              this.unpressed = unpressed;
              this.setSize(unpressed.getWidth(), unpressed.getHeight());
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.drawImage(this.unpressed, null, this.getBounds().x, this.getBounds().y);
    }If I tab out setContentAreaFilled and setBorder, then the button appears exactly as a JButton should. If they are untabbed out, then the button is not displayed, as expected.
    The usage of the button is from a JFrame, where a new CustomButton is created and then added to the frame as you would a normal JButton.
    What should I do to make my image "unpressed" appear as the button?

    You don't need an SSCCE anymore, the drawing works fine. I just want to know how to change a BufferedImage to an Icon to use in setRollOverIcon, or any other way of setting it so when the mouse is over the button, an image of my choice is drawn.
    nonetheless if it helps here you are:
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Test extends JFrame
         CustomButton cb;
         BufferedImage test;
         BufferedImage test2;
         public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                public void run()
                { Test t = new Test(); }
         public Test()
              this.setLayout(null);
              this.setBounds(100, 100, 100, 100);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              try
                   test = ImageIO.read(new File("test.png"));
                   test2 = ImageIO.read(new File("test2.png"));
              catch (IOException e)
              { e.printStackTrace(); }
              cb = new CustomButton(test, test, test);
              cb.setBounds(0, 10, test.getWidth(), test.getHeight());
              //convert test2 to an icon here
              Icon i = null;
              cb.setRolloverIcon(i);
              this.getContentPane().add(cb);
              this.setVisible(true);
    }and CustomButton
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import javax.swing.JButton;
    public class CustomButton extends JButton
         private BufferedImage unpressed;
         private BufferedImage depressed;
         private BufferedImage highlight;
         public CustomButton(BufferedImage unpressed, BufferedImage depressed, BufferedImage highlight)
              this.setContentAreaFilled(false);
              this.setBorder(null);
              this.unpressed = unpressed;
              this.depressed = depressed;
              this.highlight = highlight;
              this.setSize(unpressed.getWidth(), unpressed.getHeight());
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.drawImage(this.unpressed, null, 0, 0);
    }

  • Overriding paint for customizing JButton??? Shouldn't be paintComponent?

    Hi
    Shouldn't we always override paintComponent to customize the painting of a component?
    Why MetalScrollButton in javax.swing.plaf.Metal overrides paint instead of paintComponent?
    Should I override paint if I want to write my own LnF?
    Thanks.

    As is said in the online doc about paint(), "This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method, as always. A subclass that just wants to specialize the UI (look and feel) delegate's paint method should just override paintComponent."
    That means you can override paint(), , but in this case you'll have to draw the border yourself... and if you have a composite custom component (a panel containing labels, for example), you will have to call the label's paintComponent() methods by yourself...
    Hope this helped,
    Regards

  • Swing layout + awt paintcomponent issue

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

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

  • PaintComponent Method

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

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

  • Override scrollpane methods?

    problem: I create a time series line graph in a buffered image that has a variable width, sometimes the width is in the millions of pixels and the resulting buffered image is too large to fit into memory, even if I increase the available memory with the -Xmx1024m option. I then place the a fore mentioned buffered image into a scrollpane for viewing.
    I would like to draw only the portion of the graph that is viewable and override the scrollpane methods to redraw the image based on an x position over the total width, but I haven't found anything in the API on overriding the scrollbar or the arrow buttons. Has anyone tried this, or seen and example of how to do it?
    I am aware of products such as JFreeChart and PtolemyPlot, however I don't think either is a good fit for the project and I don't have any use for their capabilities. I am open to any other suggestions on how to accomplish this goal.
    Thanks,
    Peter

    You can try to use JScrollPane by placing a custom component extending JComponent inside the scroll pane and setting it's preferred size to the required size.
    Override paintComponent method of this component and get the view rectangle from the viewport and paint only the visible area.
    If this doesn't work you might need to use JScrollBar and write the logic yourself in this case.

  • What is the difference between paint() and paintComponent()?

    I always confuse by them?
    Thanks

    paintComponent is the method used by Swing components to do the painting necessary for the component. If you are making a custom Swing component, it is recommended that you override paintComponent instead of paint. Non-swing AWT components do not have a paintComponent method.
    A Swing component's default paint() method partitions the painting of a component into separate phases, including painting the component itself, painting the component's border, and finally painting all its children. Overriding paintComponent in a custom Swing component only affects the drawing of the component itself without impacting these other phases of drawing.

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

  • Explain paintComponent concept please

    Hi
    I have a Swing application which implements the paintComponent() method. I am having trouble understanding how it works, could someone help please ?
    - Why can i call the paintComponent() method with rePaint() but not paintComponent() ?
    - When we overide paintComponent with a Graphics object how does this work ? Because we don't explicitly give it a graphics object yet it is still called. I know about method overiding but i don't understand this . . .
    - Can each application can only implement 1 paintComponent method? For instance i use paintComponent initially to draw some things but then later, at a specific point that happens once i need to draw something else. Do i just have to find a way to incorporate this in my paintComponent method ?
    -the super() extends from JFrame. What happens in this second line of code please
         public void paintComponent(Graphics g) {
        super.paintComponent(g);  //what is occuring here ?
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(Color.black); help much appreciated - thanks

    Hi
    I have a Swing application which implements the
    paintComponent() method. I am having trouble
    understanding how it works, could someone help please
    - Why can i call the paintComponent() method with
    rePaint() but not paintComponent() ?Do you know what threads are? Very roughly, threads are "subprocesses" that run at fairly independent rates within a running application. Swing starts a thread called the EDT (Event Dispatch Thread). Its job is to draw your GUI and respond to events like mouse clicks &movements and keyboard input. As the name indicates, the EDT is driven by a queue of events: events are enqueued and later they are dequeued and processed. Some events are higher priority, like mouse movements, and can skip ahead of other events, like requests to repaint parts of components. To get a component repainted, you call one of its repaint methods (many methods, like JTextField's setText, will invoke repaint for you). The repaint methods are asynchronous: when it returns, it's likely that repainting hasn't even begun. All that happened is that the repaint request has been queued. When a Swing component (any subclass of JComponent) is to be repainted, it's paint method is called by code in the EDT (this part of the Swing Framework -- you don't paint directly -- let the EDT call paint when it decides it's right). Component's implementation of paint calls three protected methods in order:
    -- paintComponent : to paint the background of the component
    -- paintBorder
    -- paintChildren, in case the component is a container, like JPanel
    To customize the painting of a JComponent you could override any of these, but the most useful to override is paintComponent.
    >
    - When we overide paintComponent with a Graphics
    object how does this work ? Because we don't
    explicitly give it a graphics object yet it is still
    called. I know about method overiding but i don't
    understand this . . .As a Design Pattern, method paintComponent is an example of a Template Method: you override but your code doesn't call it directly. This is a very common pattern in object oriented code. For example, if you wanted to make Zubs sortable, you could have the Zub class implement Comparable and override the compareTo method. Your code doesn't call this method, the sorting algorithm does.
    >
    - Can each application can only implement 1
    paintComponent method? For instance i use
    paintComponent initially to draw some things but then
    later, at a specific point that happens once i need to
    draw something else. Do i just have to find a way to
    incorporate this in my paintComponent method ?Any JComponent can override paintComponent. There many be several such classes in your app. To "draw things later" means to add state to your JComponent. An example follows at the end of this post.
    >
    -the super() extends from JFrame. What happens in
    this second line of code please
    public void paintComponent(Graphics g) {
    super.paintComponent(g);  //what is occuring here
    ere ?
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(Color.black); help much appreciated - thanks First, its not a great idea to override JFrame's paintComponent -- think of your window as an oil painting: is it the job of the gilt frame to draw what gets fitted inside of it? It's usually better to subclass JPanel or JComponent to do that. Anyway, the call to the super class's paintComponent often does things like painting the background of the component the component's background color...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.List;
    public class X extends JPanel {
        private List points = new ArrayList();
        public X() {
            addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent evt) {
                    points.add(evt.getPoint());
                    repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for(Iterator i = points.iterator(); i.hasNext(); ) {
                Point pt = (Point) i.next();
                g.drawOval(pt.x-2, pt.y-2, 5, 5);
        public static void main(String[] args) {
            final JFrame f = new JFrame("X");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new X());
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);

  • Paint performance with JScrollPane very slow in jdk 1.4?

    I got a simple program that overrides paintComponent on a JPanel. Then draws lots of lines, rectangles and some strings. The panel is then added to a scrollpane.
    The scrolling is very smooth in java 1.3.1, but very slow in 1.4.2
    the paintComponent takes between 16ms and 30ms with java 1.3.1 but 70-200ms with java 1.4.2.
    I tried turning of antialising etc.. but no help. Whats the "improvement" they made in jdk 1.4?

    Ok I made a simple example, which draws around 5000 elements.
    Sourcecode is here: http://www.mcmadsen.dk/files/ScrollPaneTest.java
    I did several testruns on java 1.4.2 and java 1.3.1, heres the "avarage" result:
    Java 1.4.2:
         Current: 140ms High: 203ms Avg: 144ms Low: 125ms
    Java 1.3.1:
         Current: 62ms High: 219ms Avg: 68ms Low: 47ms
    The paintComponent() looks like this:
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    long offset=System.currentTimeMillis();
    PaintElement paintElementTmp;
    for(int i=0;i<paintElements.size();i++)
    paintElementTmp=(PaintElement)paintElements.elementAt(i);
    g.setColor(paintElementTmp.getBackground());
    g.fillRect(paintElementTmp.getX(),paintElementTmp.getY(),paintElementTmp.getWidth(),paintElementTmp.getHeight());
    g.setColor(paintElementTmp.getForeground());
    g.drawString(paintElementTmp.getText(),paintElementTmp.getX(),paintElementTmp.getY());
    long done=System.currentTimeMillis();
    long current=done-offset;
    sum+=current;
    if(current>high)high=current;
    if(low>current)low=current;
    count++;
    System.out.println("Current: "+current+"ms High: "+high+"ms Avg: "+(sum/count)+"ms Low: "+low+"ms");
    I tried all the renderinghints, but no difference (from the default settings). Also the scrolling is very slow and stops all the time in java 1.4.
    Any ideas on how to get java 1.4 to perform as java 1.3.1?
    Thanks

  • Game of Life display problem

    The Rules of Game of Life
    For a space that is 'populated':
    Each cell with one or no neighbors dies, as if by loneliness.
    Each cell with four or more neighbors dies, as if by overpopulation.
    Each cell with two or three neighbors survives.
    For a space that is 'empty' or 'unpopulated'
    Each cell with three neighbors becomes populated.
    I have three classes: Cell, BoardComponent, and GameViewer
    I got few problems in my code: 1. the button shows wrongly, 2. without the button, there is always a dot on the upper-left corner, which is not on purpose, 3, after click the mouse to initialize few dots, nothing happened
    How could I fix those problems?
    My Code:
    1. Cell:
    import java.awt.Rectangle;
    public class Cell extends Rectangle{
         public Cell(int x, int y, int side)
              super(x, y, side, side);
    }2. BoardComponent:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    import com.sun.jdi.event.Event;
    public class BoardComponent extends JComponent{
         public BoardComponent()
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        board[i][j] = new Cell(i*SIDE, j*SIDE, SIDE);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        g2.draw(board[i][j]);
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         public void generate()
              int count = 0;
              for(int i = 0; i < ROW-2; i++)
                   for(int j = 0; j < COL-2; j++)
                        for(int m = 0; m < 2; m++)
                             for(int n = 0; n < 2; n++)
                                  if(m!=0 || n !=0)
                                       if(!(board[i+m][j+n].isEmpty()))
                                            count++;
                        if(count == 3 || count < 2 || count > 4)
                             initialize(i*SIDE, j*SIDE);
         private int mouseX, mouseY;
         private boolean mouseclicked = false;
         public static final int ROW = 40;
         public static final int COL = 40;
         private Cell[][] board = new Cell[ROW][COL];
         public static final int SIDE = 14;
    }3. GameViewer:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class GameViewer extends JFrame{
         public static void main(String[] args)
              final BoardComponent game = new BoardComponent();
              class MouseClickListener extends MouseAdapter
                   public void mouseClicked(MouseEvent event)
                        int x = event.getX();
                        int y = event.getY();
                        game.initialize(x, y);
              MouseAdapter listener = new MouseClickListener();
              game.addMouseListener(listener);
              JButton button = new JButton("Start");
             class TimerListener implements ActionListener
                   public void actionPerformed(ActionEvent event)
                        game.generate();
            ActionListener timer = new TimerListener();
            button.setSize(40, 10);
            button.setLocation(250, 500);
            button.addActionListener(timer);
            final int DELAY = 500;
            Timer t = new Timer(DELAY, timer);
            t.start();  
            JFrame window = new JFrame();
            window.setSize(600, 600);
            window.setTitle("Life of Game");
            window.setDefaultCloseOperation(EXIT_ON_CLOSE);
            window.add(game);
            window.add(button);
            window.setVisible(true);
    }Thanks a million.

    As already said, you should override paintComponent(), not paint(), and don't forget to call the superclass's paintComponent() method.
    public void paintComponent(Graphics g)
       super.paintComponent(g);
    }As for this method:
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         }You really shouldn't be doing any painting outside the paintComponent() method.
    Finally, your GameViewer class extends JFrame, but yet you are creating another JFrame in the main method. This doesn't make sense.

  • Problems with JDesktopPane and JInternalFrame

    hello
    merry christmas .
    I have some strange problem with JDesktopPane .
    I have a frame with an splitpane and in right side of splitpane i have a JDesktopPane .
    I can easily add InternalFrames to this JDesktopPane but when there is two or more InternalFrame and when I have at least 2 internal frame(they are not minimized or in full screen mode or cover completely each other , just when overlap each other) my cpu usage go to 100% and as soon as i minimize one of them or go to full screen mode or drag out one of them problem resolves .
    I have not any extra code that cause this problem(i just overwrite the paint method in internal frames ) .
    Can you help me ?
    Thanks for your time

    Did you override paint() or paintComponent()? Generally you should override paintComponent() for Swing components.
    Regards,
    Tim

Maybe you are looking for

  • Invalid content type for SOAP: TEXT/HTML; HTTP 500 Internal Server Error

    Hi, I have this error on a SOAP Receiver Channel: invalid content type for SOAP: TEXT/HTML; HTTP 500 Internal Server Error I've found several threads on SDN Forums about similar errors, but I did not find a solution for my problem yet. I checked this

  • How to create a array with variables dimensions?

    I try to create a array like that: Object[][] data; data = new Object[] []; But that's doesn't work! Apparently I must specify the dimension of my array So I have done like that : Object[][] data; data = new Object[3] [3]; And that work! But the prob

  • Head Office field error in Vendor Master

    Hello, I am trying to extend an existing vendor master in new company code. But I am getting an error that the "Head Office and CCN combination does not exist". However the same combination is valid in another company code. Please tell me where is He

  • Stay awake option while charging in the developer options section in settings

    Since 4.4 update, my phone will not stay awake while connected to power as before, the screen blacks out in 10min which is the setting I have the display on. BTW, what has happened to the forum format?  I don't like the changes, I like seeing the pos

  • Problem reading pdf in Vista

    Adobe Reader X comes up with "Internal Error Message"