Whyte board painting in Swing?

Hi everyone,
I have an application to which I'd like to attach a home made Java "whyte board". In this a user may drag his mouse to form letters, figures or whatever. I.e. I want the "whyte board JPanel" to paint out the exact movement of the mouse only when the left button of it is pressed.
Has anyone seen this kind of application anywhere (with open source code) or do I have to develop it from scratch? If I have to, then does anyone have a good tip of where to look to find how to catch the mouses movement (when left button is pressed), cause I can't find any good sources...
Hope you can help!
/ jez

Thank you all for your help! And yes with the mouselistener and all, it should work, but some work must be done.
Reply to "ashwin0007", thanx for the tip, and yes cooperation is always welcome. May E-mail is is "[email protected]" case it is not visible here. I'm getting to "work" this weekend, so we might get somewhere.
See ya!
/ jez

Similar Messages

  • Trying Very Hard to Paint in Swing

    I'm sorry that this is such a newbie question, and yes I've been through the forums and the web and everywhere, but the problem isn't so much that I can't find answers to this question, so much as nothing I try will work. I'm just trying to paint into a JFrame in Swing, but I can't get anything to show up. I've tried using both paint(Graphics g) and paintComponent(Graphics g), but neither of those did anything. Then I tried calling super.paintComponent(g), but I got a "cannot resolve symbol" error, and I think I spelled everything correctly and imported everything, but I may be wrong. Here's my code... I hope someone can help me.
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Board extends Thread{
        private BufferedReader readIn;
        private String readFromServer;
        private PrintWriter sendOut;
        public Board(BufferedReader in, PrintWriter out){
         readIn = in;
         sendOut = out;
        public void run() {
         JFrame board = new JFrame("Board");
         board.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                  System.exit(0);
         board.pack();
         board.setVisible(true);
         try {
         readFromServer = readIn.readLine();
            while (true) {
             if (readFromServer.length()<2) {
             readFromServer = readIn.readLine();
             if (readFromServer.startsWith("fics%") && readFromServer.length()<10) {
                  readFromServer = readIn.readLine();
              readFromServer = readIn.readLine();
                //window.append(readFromServer);
             //window.append("\n");
             readFromServer = readIn.readLine();
         catch (IOException sio) { }
        public void paintComponent(Graphics g) {
         super.paintComponent(g);
         Image image = Toolkit.getDefaultToolkit().getImage("e:\\desktop\\page02b.jpg");
         g.drawImage(image, 0, 0, null);
         g.setColor(Color.red);
         g.drawRect(0,0,100,100);
         g.setColor(Color.blue);
         g.drawRect(0,0,100,100);
        //public void update(Graphics g) {
        //paint(g);
    }

    No offense,but it looks like you have total mess in your head.
    Here is working animation application i took from book "Java Thread Programming". Maybe it will help you.
    Why you need to construct your class in a thread that IS this class still mystery to me. Don't forget that you can create a lot of other threads which will do whatever you want.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Slide extends JComponent {
      private BufferedImage[] slide;
      private Dimension slideSize;
      private volatile int currSlide;
    private Thread interThread;
    private volatile boolean noStopRequested;
    public Slide() {
       currSlide = 0;
       slideSize = new Dimension(50, 50);
       buildSlides();
       setMinimumSize(slideSize);
       setPreferredSize(slideSize);
       setMaximumSize(slideSize);
       setSize(slideSize);
       noStopRequested = true;
      Runnable r = new Runnable() {
              public void run() {
                   try {
                        runWork();
                         }catch(Exception x) {
                          x.printStackTrace();
       interThread = new Thread(r, "Slides");
       interThread.start();
    private void buildSlides() {
             slide = new BufferedImage[20];
        Color rectColor = new Color(100, 160, 250);
        Color circleColor = new Color(250, 250, 150);
        for(int i=0; i < slide.length; i++) {
         slide[i] = new BufferedImage(
             slideSize.width,
             slideSize.height,
           BufferedImage.TYPE_INT_RGB);
       Graphics2D gg = slide.createGraphics();
    gg.setColor(rectColor);
    gg.fillRect(0, 0, slideSize.width, slideSize.height);
    gg.setColor(circleColor);
    int d = 0;
    if(i < (slide.length/2)) {
    d = 5 + (8*i);
    }else {
    d = 5 + (8*(slide.length-i));
    int inset = (slideSize.width - d)/2;
    gg.fillOval(inset, inset, d, d);
    gg.setColor(Color.black);
    gg.drawRect(
    0, 0, slideSize.width-1, slideSize.height-1);
    gg.dispose();
    public void paint(Graphics g) {
    g.drawImage(slide[currSlide], 0, 0, this);
    private void runWork() {
    while(noStopRequested) {
    try {
    Thread.sleep(100);
    currSlide =
    (currSlide +1 )%slide.length;
    repaint();
    }catch(InterruptedException x) {
    Thread.currentThread().interrupt();
    public void stopRequest() {
    noStopRequested = false;
    interThread.interrupt();
    public boolean isAlive() {
    return interThread.isAlive();
    public static void main(String[] args) {
    Slide s = new Slide();
    JPanel p = new JPanel(new FlowLayout());
    p.add(s);
    JFrame f = new JFrame("Slide Show");
    f.setContentPane(p);
    f.setSize(250, 150);
    f.setVisible(true);

  • Help Painting in Swing

    I'm new to Swing, and am having trouble painting both buttons and other graphics.
    For instance:
    package example.src;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import example.src.*;
    public class Example extends JFrame {
        public Example() {
             this.setSize(500, 500);
             this.setTitle("Example");
             addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e)
                        System.exit(0);
              Container c = this.getContentPane();
              c.add(new DrawPanel());
              c.add(new ButtonPanel());
        public static void main(String[] args) {
             JFrame Drawing_Ex = new Example();
             Drawing_Ex.setVisible(true);
    package example.src;
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel implements Runnable
         private boolean x = true;
         public DrawPanel() {
              Thread thread = new Thread(this);
              thread.start();
         public void run() {
             int counter = 0;
             while (true) {
                  counter++;
                  if (counter == 500) {
                       if (x) {
                            x = false;
                       else {
                            x = true;
                       counter = 0;
                  this.repaint();
                  try {
                       Thread.sleep(1);
                  catch (InterruptedException ex) {
                       System.out.println("Failed.");
        public void paintComponent(Graphics g) {
             super.paintComponent(g);
             g.setColor(Color.blue);
             if (x) {
                  g.drawString("YES", 100, 100);
             else g.drawString("NO", 100, 100);
    package example.src;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import java.awt.event.*;
    import java.awt.*;
    public class ButtonPanel extends JPanel {
    public static JButton play;
    public static JButton changeCpu;
        public ButtonPanel() {
             super();
             this.setLayout(null);
             play = new JButton("Restart");
            play.setBounds(420, 170, 80, 30);
            play.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent event) {
            this.add(play);
            play.setVisible(true);
            changeCpu = new JButton("Change Level");
            changeCpu.setBounds(300, 170, 120, 30);
            changeCpu.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent event) {
            changeCpu.setVisible(true);
            this.add(changeCpu);
    }This should have two buttons, as well as a string yes/no that switches. However, if the buttons get added last to the content pane, the string doesn't show, and if the drawing gets added last, the buttons won't show. Any help?
    (This is for a pong game - I want two buttons, one that changes the Cpu's level and another that restarts the game, and I need the player, enemy, and ball to be drawn).

    Both using and understanding layouts, is vital in the Java X-plat language. The sooner people realize that, the better off they are.
    There were other things in the code that were either questionable or could be improved, but I stuck to concentrating of the layout.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Example extends JFrame {
      public Example() {
        this.setSize(500, 500);
        this.setTitle("Example");
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e)
            System.exit(0);
        Container c = this.getContentPane();
        // 'when EAST meets WEST' otherwise they are
        // stacked, and only one is visible!
        c.add(new DrawPanel(), BorderLayout.WEST);
        c.add(new ButtonPanel(), BorderLayout.EAST);
        // always (validate or) pack() the main UI
        // otherwise unpredictable behaviour will be seen
        pack();
      public static void main(String[] args) {
        JFrame Drawing_Ex = new Example();
        Drawing_Ex.setVisible(true);
    class DrawPanel extends JPanel implements Runnable
      private boolean x = true;
      public DrawPanel() {
        Thread thread = new Thread(this);
        thread.start();
        // important, so the layout does not collapse the empty
        // panel to 0x0
        setPreferredSize( new Dimension(200,200) );
      public void run() {
        int counter = 0;
        while (true) {
          counter++;
          if (counter == 500) {
            if (x) {
              x = false;
            else {
              x = true;
            counter = 0;
          this.repaint();
          try {
            Thread.sleep(1);
          catch (InterruptedException ex) {
            System.out.println("Failed.");
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        if (x) {
          g.drawString("YES", 100, 100);
        else g.drawString("NO", 100, 100);
    class ButtonPanel extends JPanel {
      public static JButton play;
      public static JButton changeCpu;
      public ButtonPanel() {
        super();
        // don't do that, except in a layout manager..
        //this.setLayout(null);
        play = new JButton("Restart");
        // use a layout manager with appropriate padding,
        // or add borders to the components
        //play.setBounds(420, 170, 80, 30);
        play.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
        this.add(play);
        play.setVisible(true);
        changeCpu = new JButton("Change Level");
        changeCpu.setBounds(300, 170, 120, 30);
        changeCpu.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
        changeCpu.setVisible(true);
        this.add(changeCpu);
    }Edited by: AndrewThompson64 on May 31, 2008 6:56 AM

  • Custom Painting in Swing Panels.

    I am trying to implement a custom painted panel on a JFrame. The panel performs custom painting in a separate thread. In additon, the frame also adds other swing panels (containing standard components) dynamically as per menu selection. I use box layout on frame to add / remove panels.
    The paint panel doesnt render properly whenever other panels are added or replaced. The paint panel is rendered only when no other are panels added to the frame.
    There is no problem however with adding / replacing components-only panels containing no custom painting.
    Please help me understand what I am missing. Any clues / suggestions most welcome
    sridhar

    Hi,
    You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
    JRG

  • Incremental Painting in Swing

    Hello All!
    How can I achieve incremental painting in a JPanel or in general JComponents.. By "incremental painting" I mean I do not want to lose my previous drawings on the panel aka. I want to update the drawing by adding more drawings.
    An example would help this is the code:
    import java.awt.*;
    import javax.swing.*;
    public class CustomPanel extends JPanel{
    public final static int CIRCLE = 1, SQUARE = 2;
    private int shape;
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    if(shape == CIRCLE)
    g.fillOval(50,10,60,60);
    else if(shape == SQUARE)
    g.fillRect(150,110,60,60);
    public void draw(int s){
    shape = s;
    repaint();
    This class is used by the following class:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CustomPanelTest extends JFrame{
    private JPanel buttonPanel;
    private CustomPanel myPanel;
    private JButton circle, square;
    public CustomPanelTest()
    super("Custom Panel Test");
    myPanel = new CustomPanel();
    myPanel.setBackground(Color.green);
    square = new JButton("Square");
    square.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e)
    myPanel.draw(CustomPanel.SQUARE);
    circle = new JButton("Circle");
    circle.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e)
    myPanel.draw(CustomPanel.CIRCLE);
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,2) );
    buttonPanel.add(circle);
    buttonPanel.add(square);
    Container c = getContentPane();
    c.add(myPanel, BorderLayout.CENTER);
    c.add(buttonPanel, BorderLayout.SOUTH);
    setSize(300,150);
    show();
    public static void main ( String args[] )
    CustomPanelTest app = new CustomPanelTest();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing (WindowEvent e )
    System.exit(0);
    While executing, either a circle or square is drawn by erasing the previous drawing. What I want to achieve is for example drawing a series of circles and/or squares without losing the previous drawings.
    Thank you!!!!

    This will do it. I added a bufferedimage.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    public class CustomPanel  extends JPanel
         public final static int CIRCLE = 1, SQUARE = 2;
         private int           shape;
         private BufferedImage I = null;
         private Graphics      G;
    public void paintComponent(Graphics g)
         if (I == null)
              I = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_ARGB);     
              G = I.getGraphics();
              G.setColor(Color.white);
              G.fillRect(0,0,getWidth(),getHeight());
         super.paintComponent(g);
         G.setColor(Color.red);
         if(shape == CIRCLE) G.fillOval(50,10,60,60);
         if(shape == SQUARE) G.fillRect(150,110,60,60);
         g.drawImage(I,0,0,null);
    public void draw(int s)
         shape = s;
         repaint();
    }Noah

  • The bane of my existance = paint()  Please help!

    I am forever getting frustrated with trying to draw things in java and even when I went through my classes in college we hit the basics but no further with this. Basically I am attempting to set up a checker board and want to draw multiple canvases in different states obviously to render a working checker board with pieces, moves etc.
    Every book and online reference that I can find has all the work done in the paint method of the canvas that is being drawn on and not from the parent(if this is even possible...is it???).
    I would like to do something like this from the parent frame:
         private void initializeBlackLayers(int initState) {
              JPanel initPanel;
              // for each state the square can be in create a panel to display that state
              for (int numState = 1; numState < 11; numState++) {
                   // create a new panel and set the size of the panel for the square
                   initPanel = new JPanel();
                   initPanel.setSize(sqSize);
                   // need to figure out which state we are creating for the square and
                   // then create that specific state for the current panel
                   switch (numState) {
                        case 1:
                             initPanel.setBackground(Color.BLACK);  // the plain black sq
                             break;
                        case 2:
                             initPanel.setBackground(Color.BLUE);  // the plain black sq selected for move
                             break;
                        case 3:
                             //NEED TO DRAW A RED CIRCLE, BLACK BACKGROUND
                             break;
                        case 4:
                             initPanel.setBackground(Color.BLUE);
                             // NEED TO DRAW A RED CIRCLE
                             break;
                        // insert code adding new panel to this layered pane and end switch, function etcI figure I either need to set up a new class for each state of the square and draw individually(which I REALLY don't want to do, read: there has GOT to be a better way) or figure out how to set the global color and just draw a filled in oval with the current color in a generic ovalCanvas for each state in the code above in the parent class. If anyone could enlighten me, I would be forever grateful for getting me out of having an extremely frustrating time with this.

    camickr wrote:Well, first of all why would people who have never written a Swing application no anything about the paint() method.Secondly, you should not be overriding the paint() method. Custom painting in Swing is done by overriding the paintComponent() method. Overriding paint() is the way it is done when using AWT.>
    Regardless, it's still the same question, whether you are using paint or paintComponent, my question is the same: How can you get a parent class to draw multiple different canvases(if using AWT) or JPanels (if swing) without constructing the individual components individually. For example, I want to have a Frame (seeing as we are not in the swing forum) that has 2 canvases one with a red circle on a black background and one with a green triangle on a blue background. Is it possible to write this from the frame, initalize 2 canvases and again from the frame, tell the canvases what you want on them?
    Start by reading the Swing tutorial on [How to Use Layered Panes|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]. The tutorial also has a section on Custom Painting.
    I did, it doesn't explain what I want to do. In their example they are just coloring the background to show up so you can see the individual panes. This is where I get stuck and what I am asking about: Write the same code they use in that example but put something on those colored backgrounds as well. Can you do it from the JLayeredPane class?

  • SwingUtilities.paintComponent - problems with painting childs of components

    Maybe this question was mention already but i cant find any answer...
    Thats what could be found in API about method paintComponent in SwingUtilities:
    Paints a component c on an arbitrary graphics g in the specified rectangle, specifying the rectangle's upper left corner and size. The component is reparented to a private container (whose parent becomes p) which prevents c.validate() and c.repaint() calls from propagating up the tree. The intermediate container has no other effect.
    The component should either descend from JComponent or be another kind of lightweight component. A lightweight component is one whose "lightweight" property (returned by the Component isLightweight method) is true. If the Component is not lightweight, bad things map happen: crashes, exceptions, painting problems...
    So this method perfectly works for simple Java components like JButton / JCheckbox e.t.c.
    But there are problems with painting JScrollBar / JScrollPane (only background of this component appears).
    I tried to understand why this happens and i think the answer is that it has child components that does not draw at all using SwingUtilities.paintComponent()
    (JScrollBar got at least 2 childs - 2 buttons on its both sides for scroll)
    Only parent component appears on graphics - and thats why i see only gray background of scrollbar
    So is there any way to draw something like panel with a few components on it if i have some Graphics2D to paint on and component itself?
    Simple example with JScrollPane:
    JScrollPane pane = new JScrollPane(new JLabel("TEST"));
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    SwingUtilities.paintComponent(g2d, pane, new JPanel(), 0, 0, 200, 200);Edited by: mgarin on Aug 11, 2008 7:48 AM

    Well the thing you advised could work... but this wont be effective, because i call repaint of the area, where Components painted, very often..
    So it will lag like hell when i make 10-20 repaints in a second... (for e.g. when i drag anything i need mass repainting of the area)
    Isnt there any more optimal way to do painting of the sub-components?
    As i understand when any component (even complicated with childs) paints in swing - its paint method calls its child components paint() to show them... can this thing be reproduced to paint such components as JScrollPane?

  • Problem painting a JPanel

    I am making a card game for a project. The game features some human players versus some AI players. After a player makes a move, the game should take a short pause if the player was an AI player, so that the humans can see the cards played.
    Currently, the program zips by so fast after an AI move that it's not perceivable. I thought that throwing in a Thread.sleep(1000) after a call to repaint() would solve the problem. By doing this, however, I end up with a blank grey panel from the time the first AI player moves until the time it's a human's turn(at which time the executing thread dies and lets the human take over again).
    As some general information, the project is divided into a basic model/view split. A single thread of execution runs from the display to the model when a button is pressed, and the repaint is called by a callback from the model to the view. I have tried locating the sleep in different places(after the repaint, before the repaint, during AI move selection) with the same result.
    Any suggestions?

    You need to learn more about threading in swing. here is exellent chapter with example how to use timed paint in swing.
    http://developer.java.sun.com/developer/Books/javaprogramming/threads/chap9.pdf
    Here are links to articles in swing connection. You will be interested in topics about threads and using swing timer:
    http://java.sun.com/products/jfc/tsc/articles/
    It will greatly improve your app.
    Regards

  • Background Painting of "Out of focus" tabbed Panel (JTabbedPane) ?

    Hi
    I would like to add a on going Bar Graph to a JTabbedPane, this works fine if the specific Tab is in Focus, but when the tab is switched, Painting stops!
    How can i ensure the painting continues in the background!
    Here is an example which demo's the problem! Also, watch the standard out...
    Any idea's how to solve this ?
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.util.*;
    public class TestPanel extends JPanel {
        // Define the height and width of the bars. Given by calling process.
        private int height [];
        private int width;
        // Define the starting point of the bar chart and base line.
        private int top = 5;
        private int base = 100 + top;
        private int middle = (base/2)+(top/2);
        private int baseOffset = 3;
        private int indent = 45;
        private int step = (base - top)/10;
        private int baseLen = 0;
        private int tpsArray[];
        private int maxValue;
        private int counter = 0;
        private int value;
        public TestPanel(String server, String file ) {
            tpsArray = new int[32768];
            JFrame f =  new JFrame();
            JTabbedPane t = new JTabbedPane();
            // Set the Content and Window layout
            f.setLayout( new BorderLayout() );
            t.add( panel(), "Tab A");
            t.add( new JLabel("I AM TAB B"), "Tab B");
            f.add( t, BorderLayout.CENTER);
            //f.setExtendedState( Frame.MAXIMIZED_BOTH );
            f.setSize(400,400);
            f.setVisible(true);
        public JPanel panel() {
            // Define the JPanel to hold the graphic
            JPanel panel = new JPanel( new BorderLayout());
            panel.setBackground( Color.white );
            AnnimationModel annimationModel = new AnnimationModel();
            AnimationView animationView = new AnimationView(annimationModel);
            panel.add(animationView, BorderLayout.CENTER);
            return panel;
        private class AnimationView extends JPanel {
            private Dimension d = new Dimension();
            AnimationView(AnnimationModel annimationModel) {
                // Save a reference to the model for use
                // when the view is updated
                annimationModel_ = annimationModel;
                // Listen for the events indicating that the model has changed
                annimationModel_.addObserver(new Observer() {
                    public void update(Observable o, Object arg) {
                        // All we need to do is to get the view to repaint
                        AnimationView.this.repaint();
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = ( Graphics2D ) g;
                baseLen = getPanelWidth() - indent * 2 ;
                System.out.println("Painting Again.... Counter = " + counter  );
                int pos = ( indent + 6 );
                addOutLine(g2d);
                // Update the view based on the information in the model.
                g.setColor(Color.green);
                for ( int i=counter;i>0;i--) {
                    if ( pos > ( baseLen + indent )  ) break;
                    g.fill3DRect( pos, (base-tpsArray), 2, tpsArray[i], true );
    pos = pos + 2;
    tpsArray[counter] = value;
    public int getPanelWidth() {
    d.width = getWidth();
    return d.width;
    public void addOutLine(Graphics2D g2d) {
    // Setup the percentage markings on left vertical bar
    g2d.setColor( Color.GRAY );
    g2d.setFont( new Font("Sanserif", Font.PLAIN, 10));
    g2d.drawString( "0", (indent - 14), base + baseOffset );
    // Display the last TPS rate
    g2d.drawString( "" + maxValue, (indent - 20 ) , top+baseOffset );
    // Display the last TPS rate
    g2d.drawString( "(" + value + ")", 3, base + baseOffset );
    // Draw vertical line from top of bar chart to base line
    g2d.drawLine( indent, top, indent, base + baseOffset );
    // Draw horizontal base line
    g2d.drawLine( indent, base, indent+baseLen, base);
    // Draw horizontal top tick mark
    g2d.drawLine( (indent)-5, top, (indent)+5, top);
    // Draw horizontal tick line at 50% or middle point
    g2d.drawLine( (indent)-5, middle, (indent)+5, middle);
    // Draw horizontal tick at bottom base line
    g2d.drawLine( (indent)-5, base, (indent)+5, base);
    // Draw the dotted lines across the bar chart.
    g2d.setColor( new Color( 160,223,233));
    float dashes[] = { 1 };
    g2d.setStroke( new BasicStroke( 1, BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, 0, dashes, 0));
    for (int i=base; i>=top ;i=i-step) {
    g2d.drawLine( indent + 6, i, (indent+baseLen), i );
    // The saved reference to the model
    private AnnimationModel annimationModel_;
    private class AnnimationModel extends Observable {
    // private Shared sharedRef = new Shared();
    AnnimationModel() {
    Thread annimationThread = new Thread() {
    public void run() {
    while(true) {
    try {
    Thread.sleep(1000);
    } catch ( Exception e ) {
    value = 1 + (int) (Math.random() * 100 );
    counter++;
    // Notify the observers
    setChanged();
    notifyObservers();
    annimationThread.start();
    // Simple test main
    static public void main(String[] args) {
    TestPanel app = new TestPanel(null,null);
    Thanks,
    Rob

    How can i ensure the painting continues in the background! Well, I don't think you force painting since Swing appears to be smart enough to not paint a component that isn't visible.
    However, you should be able to do your painting on an offscreen image. So your offscreen image will be continually update. Then your paintComponent(...) method simply paints this offscreen image.
    This posting should get your started using this approach:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607073

  • Difference between paint() and paintcomponent()

    What's the difference between the paint(), paintComponent(), paintAll(), repaint() and update() methods? Which one is preferred when printing graphics with a printer?

    http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html
    http://java.sun.com/docs/books/tutorial/2d/printing/
    paint          ---> AWT
    paintComponent ---> Swing
    repaint(AWT)   ---> update(background) ---> paint
    repaint(Swing) ---> in paintComponent  ---> super.paintComponent(background)

  • Chess Piece display problem in applet

    Hi,
    I'm writing a chess game applet which will be played between to players over the internet. I'm currently working on the applet side at the moment and will develop the server side once I have completed the applet. I'm currently having problems displaying the actual chess pieces on the board at the moment. One of my design decisions was to make a Board class which extends a JPanel. I have painted the actual chess board squares within the Board JPanel. I then propose to draw the pieces on top of these squares (good design decsion? Can anyone suggest another way. I was thinking of having the images as a separate layer which will sit on top of the squares but wasn't sure how to implement it). The chess pieces are contained in a gif strip www.dur.ac.uk/j.d.p.murphy called ChessPieces02.gif . The problem I am having is to display several pieces at the same time. I lloked at a Java tutorial which suggested using g.clipRect() method to display a defined section of the strip (i.e. a single piece of a certain length). Below is the Board class that I am using.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends JPanel{
    // Holds location of the mousePressed event
    Point point = null;
    // Size of a square square on the board
    int square_size = 40;
    // Mediatracker to monitor the loading of the images
    MediaTracker tracker;
    Image image;
    void init() {
    tracker = new MediaTracker(this);
    image = Toolkit.getDefaultToolkit().getImage("ChessPieces02.gif");
    tracker.addImage(image, 0);
    try {
    //Start downloading the images. Wait until they're loaded.
    tracker.waitForAll();
    } catch (InterruptedException e) {
    e.printStackTrace();
    throw new Error("error");
    if (tracker.isErrorAny()) {
    throw new Error("Could not load image");
    addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (point == null)
    point = new Point(0, 0);
    int x = e.getX();
    int y = e.getY();
    System.out.println("X co-ord: " + x + " Y co-ord: " + y);
    // Floor the x and y values to the nearest unit of 25
    x = x - x % square_size;
    y = y - y % square_size;
    point.setLocation(x, y);
    repaint();
    System.out.println(point);
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    System.out.println("Chess Board Paint");
    // Loop to produce the black and white squares to represent the board
    for(int jj = 0; jj < 8; jj ++){
    for(int ii = 0; ii < 8; ii++){
    if(ii % 2 == jj % 2)
    g.setColor(Color.white);
    else
    g.setColor(Color.lightGray);
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    // Draw a highlighted square
    if (point != null){
    g.setColor(Color.green);
    g.fillRect( (int)point.getX(), (int)point.getY(), square_size, square_size);
    //imageStrip is the Image object representing the image strip.
    //imageWidth is the size of an individual image in the strip.
    //imageNumber is the number (from 0 to numImages)
    // of the image to paint.
    int stripWidth = image.getWidth(this);
    int stripHeight = image.getHeight(this);
    int imageWidth = stripWidth / 6;
    System.out.println("Width = " + imageWidth);
    g.clipRect(120, 0, imageWidth, stripHeight / 2);
    g.drawImage(image, 0 * imageWidth, 0, this);
    What code do i need to add more pieces to the board? I plan to make a ChessPiece array (8x8) which will holld all the chess pieces on the board. Should I hold this array in the board class to make drawing the pieces easier? Any other tips for game development would also be most welcome.
    Thanks

    cross post, I think.
    http://forum.java.sun.com/thread.jsp?thread=496287&forum=406

  • Adding custom GUI components to a panel

    <sorry about the 'Hello All' subject in the previous post>
    I am creating a Backgammon game for my JAVA programming class. I would like to design a board and have certain checker pieces that can be dragged around on the board. In the course I am taking, I still have not been able to understand how a GUI interface has GUI components that is "custom built" like my checker class. My checker class below draws a picture of a checker on a JPanel. I want it to exist inside a JPanel(that has a board painted in it) with 30 checkers that can be moved around. Any feedback would be appreciated including helpful packages, classes, trails, etc.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.util.Random;
    import javax.swing.JPanel;
    import java.awt.BasicStroke;
    // Checker.java - This will draw the checkers used in the game
    public class Checker extends JPanel
    private Color checker_color; // color of checker
    private int abs_pos;
    private int player; // player 1 or player 2
    Checker(Color check_color, int pos, int plyr)
         checker_color = check_color;
         abs_pos = pos;
         player = plyr;
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2d = (Graphics2D) g; // cast g to Graphics2D
         this.setBackground(Color.WHITE);
         // make a circle
         g2d.setColor(checker_color);
         g2d.setStroke(new BasicStroke(1.0f));
         g2d.fillOval(47,47, 35, 35);
         g2d.setColor(Color.BLACK);
         g2d.setStroke(new BasicStroke(2.0f));
         g2d.drawOval(47, 47, 35, 35);
    public int getPlayer(){
         return player;
    public Color getCheckerColor(){
         return checker_color;
    public int getPosition(){
         return abs_pos;
    public void setPosition(int pos){
         abs_pos = pos;
    }

    Um... pretty much the way you are doing it in the code you already posted. What is the problem? Not that there's not problems....
    1) setBackground called in paintComponent doesn't do much. Just set the background outside paint and super.paintComponent() will fill the BG color if the component isn't opaque.
    2) a checker, I would expect, would be opaque, actually.
    3) the oval size you draw would probably be better off being based on the size of the component (getSize()) instead, that way it scales easily.
    But other then that, you are doing it right. You probably need to set the size and location of each checker object explicitly, since most likely it's being used in a container with a null layout.

  • Chess piece display problem

    Hi,
    I'm writing a chess game applet which will be played between to players over the internet. I'm currently working on the applet side at the moment and will develop the server side once I have completed the applet. I'm currently having problems displaying the actual chess pieces on the board at the moment. One of my design decisions was to make a Board class which extends a JPanel. I have painted the actual chess board squares within the Board JPanel. I then propose to draw the pieces on top of these squares (good design decsion? Can anyone suggest another way. I was thinking of having the images as a separate layer which will sit on top of the squares but wasn't sure how to implement it). The chess pieces are contained in a gif strip www.dur.ac.uk/j.d.p.murphy called ChessPieces02.gif . The problem I am having is to display several pieces at the same time. I lloked at a Java tutorial which suggested using g.clipRect() method to display a defined section of the strip (i.e. a single piece of a certain length). Below is the Board class that I am using.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends JPanel{
    // Holds location of the mousePressed event
    Point point = null;
    // Size of a square square on the board
    int square_size = 40;
    // Mediatracker to monitor the loading of the images
    MediaTracker tracker;
    Image image;
    void init() {
    tracker = new MediaTracker(this);
    image = Toolkit.getDefaultToolkit().getImage("ChessPieces02.gif");
    tracker.addImage(image, 0);
    try {
    //Start downloading the images. Wait until they're loaded.
    tracker.waitForAll();
    } catch (InterruptedException e) {
    e.printStackTrace();
    throw new Error("error");
    if (tracker.isErrorAny()) {
    throw new Error("Could not load image");
    addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (point == null)
    point = new Point(0, 0);
    int x = e.getX();
    int y = e.getY();
    System.out.println("X co-ord: " + x + " Y co-ord: " + y);
    // Floor the x and y values to the nearest unit of 25
    x = x - x % square_size;
    y = y - y % square_size;
    point.setLocation(x, y);
    repaint();
    System.out.println(point);
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    System.out.println("Chess Board Paint");
    // Loop to produce the black and white squares to represent the board
    for(int jj = 0; jj < 8; jj ++){
    for(int ii = 0; ii < 8; ii++){
    if(ii % 2 == jj % 2)
    g.setColor(Color.white);
    else
    g.setColor(Color.lightGray);
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    // Draw a highlighted square
    if (point != null){
    g.setColor(Color.green);
    g.fillRect( (int)point.getX(), (int)point.getY(), square_size, square_size);
    //imageStrip is the Image object representing the image strip.
    //imageWidth is the size of an individual image in the strip.
    //imageNumber is the number (from 0 to numImages)
    // of the image to paint.
    int stripWidth = image.getWidth(this);
    int stripHeight = image.getHeight(this);
    int imageWidth = stripWidth / 6;
    System.out.println("Width = " + imageWidth);
    g.clipRect(120, 0, imageWidth, stripHeight / 2);
    g.drawImage(image, 0 * imageWidth, 0, this);
    What code do i need to add more pieces to the board? I plan to make a ChessPiece array (8x8) which will holld all the chess pieces on the board. Should I hold this array in the board class to make drawing the pieces easier? Any other tips for game development would also be most welcome.
    Thanks

    And when a piece is taken, you set its position in the array to null, I guess.
    Well, after you draw the board, you can iterate through your array, then draw each piece if its not null, right?
    Or maybe for each square, first you draw the background, and then you draw the piece.
    So maybe you'd have something like:
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    pieces[ii][jj].draw(g);Though personally, I wouldn't code it like this. I'd make Board be a collection of Position objects, and each position object could contain a piece. Each position would also know its own background color, and its neighbors perhaps. Also it would know any of its own special properties, such as "if an opposing side's pawn lands here, it becomes a queen". You'd probably have a subclass of Position for positions that have special properties like that.

  • Help adding to JLayeredPane

    basically I need to create a panel with a background, then use JLayeredPane to put 2 other panel on top of each other over the background. The problem is that each panel will display properly by with the background but not all 3 together.
    /* main gui class for the four score game.*/
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GuiMain extends JFrame
         //declare variables
         private JButton quit = new JButton("Quit");
         private JButton restart = new JButton("Restart");
         //panels
         private BoardPanel myBoard = new BoardPanel();
         private JPanel South = new JPanel();
         //embedded main class used for testing
         public static void main(String[] args)
              new GuiMain();
         /*no arg constructor which zeroes the bead array, creates a new window using the boxlayout manager,
          * creates the board, and adds the quit/restart buttons
         public GuiMain()
              super("Four Score");
              this.addComponentListener(new ResizeListener());
              setSize(640,480);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
              myBoard.setBorder(BorderFactory.createLineBorder(Color.black));
              restart.addActionListener(new ResetListener());
              quit.addActionListener(new QuitListener());
              South.add(quit);
              South.add(restart);
              South.setBorder(BorderFactory.createLineBorder(Color.green));
              add(myBoard, BorderLayout.CENTER);
              add(South, BorderLayout.SOUTH);
              repaint();
              setVisible(true);
         //sends a new complete set of beads to the board
         public void updateBoard(int[][][] newBeads)
              myBoard.updateBoard(newBeads);
         //updates a specific bead then calls the updateboard method
         public void updateBead(int x, int y,int z, int color)
              myBoard.updateBead(x, y, z, color);
         //checks if a peg at a set of coordinates is full
         public boolean isFull(int x, int y)
              return myBoard.isFull(x,y);
         /* customer action listener for the reset button
          * resets the beads array to all zeroes (empty) and
          * sends the command "reset;" to the player
         private class ResetListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   int[][][] beads = new int[4][4][4];
                   for(int i = 0; i < 4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4;k++)
                                  beads[i][j][k] = 0;
                   updateBoard(beads);
                   sendCommand("reset;");
         /* customer action listener for the quit button
          * sends a "quit;" command to the player.
         public class QuitListener implements ActionListener
              public void actionPerformed(ActionEvent e)
                   sendCommand("Quit;");
                   System.exit(0);      //REMOVE AFTER TESTING
         public void sendCommand(String command)
              //so far unused as I still need to work out sending the commands to the appropriate place
         public class ResizeListener implements ComponentListener
              public void componentResized(ComponentEvent e)
                   if(getWidth() != 640 || getHeight() != 480)
                        setSize(640,480);
              public void componentMoved(ComponentEvent e){}
              public void componentShown(ComponentEvent e) {}
              public void componentHidden(ComponentEvent e) {}
    /* class which creates the actual game board
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BoardPanel extends JPanel
         enum BeadStatus {EMPTY, WHITE, BLACK};
         //variables, basic x and y starting points for drawing the board.
         final int x = 100;
         final int y = 100;
         final int[] boardxPoints = {x,x+320,x+420,x+100};
         final int[] boardyPoints = {y,y,y+200,y+200};
         //array for the beads
         private int[][][] beads = new int[4][4][4];
         private PegButton[] pegs = new PegButton[16];
         public JPanel pegsPanel = new JPanel();
         public BeadLayer beadsPanel = new BeadLayer();
         JLayeredPane layers = new JLayeredPane();
          * no arg constructor which simply zeroes the bead array
         public BoardPanel()
              pegsPanel.setLocation(0,0);
              pegsPanel.setPreferredSize(new Dimension(630,480));
              pegsPanel.setOpaque(false);
              setOpaque(false);
              drawPegs();
              layers.setBorder(BorderFactory.createTitledBorder(
            "Test"));
              layers.add(pegsPanel, 1);
              beadsPanel.setLocation(0,0);
              beadsPanel.setPreferredSize(new Dimension(630,480));
              //layers.add(beadsPanel, new Integer(1));
              add(layers);
          * overriden paint component method which draws out the board, pegs, and beads
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.setColor(Color.blue); //board background color
              g.fillPolygon(boardxPoints,boardyPoints, 4); //create the basic board shape
              drawGrid(g);
          * method to draw out the grid shape
         public void drawGrid(Graphics g)
              int p;
              int q;
              g.setColor(Color.cyan);
              //draw the vertical lines
              for(int i=0; i<5;i++)
                   p=x+(i*80);
                   g.drawLine(p,y,p+100,y+200);
              //draw the horizontal lines
              for (int j=0; j<4; j++)
                   p=x+(j*25);
                   q=y+(50*j);
                   g.drawLine(p,q,p+320,q);
              g.drawLine(x+100,y+200,x+420,y+200);
          * draw out the 16 pegs in proper position
         public void drawPegs()
              int p = x;
              int q = y;
              int n;
              for(int i=0; i<4;i++)
                   for(int j=0; j < 4; j++)
                        p = x+(j*80+40)+(i*25+12)-5;
                        q = y+(i*50+25)-80;
                        //g.fillRect(p,q,10,75);
                        //g.fillArc(p, q-5, 10, 10, 0, 180);
                        n =j+(i*4);
                        pegs[n] = new PegButton(i,j);
                        pegs[n].setLocation(p,q);
                        pegsPanel.add(pegs[n]);
         //updates the board by reading in a new bead array then repainting
         public void updateBoard(int[][][] beads)
              for(int i = 0; i < 4; i++)
                   for(int j = 0; j<4; j++)
                        for(int k=0; k<4; k++)
                             this.beads[i][j][k] = beads[i][j][k];
              repaint(); //inheirited method which causes paintcomponent to be called again
         public void updateBead(int x, int y, int z, int color)
              beads[x][y][z] = color;
              repaint();
         //returns true if a peg is full
         public boolean isFull(int x, int y)
              if (beads[x][y][3] != 0)
                   return false;
              return true;
    import java.awt.*;
    import javax.swing.*;
         public class BeadLayer extends JPanel
              enum BeadStatus {EMPTY, WHITE, BLACK};
              final int x = 100;
              final int y = 100;
              private int[][][] beads = new int[4][4][4];
              public BeadLayer()
                   for(int i = 0; i < 4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4; k++)
                                  beads[i][j][k] = 1;
                   repaint();
              //method which takes in a set of coordinates and a color then draws the bead at the correct position
              public void paintComponent(Graphics g)
                   //reads through the bead array and calls the drawbead method where required
                   for(int i = 0; i<4; i++)
                        for(int j = 0; j<4; j++)
                             for(int k=0; k<4;k++)
                                  if(beads[i][j][k] == 1)
                                       drawBead(i,j,k,BeadStatus.BLACK,g);
                                  else if(beads[i][j][k] == 2)
                                       drawBead(i,j,k,BeadStatus.WHITE,g);
              public void drawBead(int x, int y, int z, BeadStatus color, Graphics g)
                   x = this.x+(x*80+40)+(y*25+12)-10;
                   y = this.y+(y*50+25)-18-(18*z);
                   if(color == BeadStatus.WHITE)
                        g.setColor(Color.WHITE);
                   else
                        g.setColor(Color.BLACK);
                   g.fillOval(x, y, 20, 18);
                   g.setColor(Color.GREEN);
                   g.drawOval(x, y, 20, 18);
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PegButton extends JButton implements ActionListener
         private String coord;
         public PegButton(int x, int y)
              getCoord(x,y);
              this.setPreferredSize(new Dimension(10,75));
              this.setBorderPainted(false);
              addActionListener(this);
         public void getCoord(int x, int y)
              y+=1;
              switch(x)
                   case 0: coord = "A"+Integer.toString(y)+".";
                             break;
                   case 1: coord = "B"+Integer.toString(y)+".";
                             break;
                   case 2: coord = "C"+Integer.toString(y)+".";
                             break;
                   case 3: coord = "D"+Integer.toString(y)+".";
                             break;
         public void setLocation(int x,int y)
              if (y != 5)
                   super.setLocation(x,y);
         public void paintComponent(Graphics g)
              g.setColor(Color.RED);
              g.fillRect(0, 7, 10, 75);
              g.fillArc(0, 0, 10, 15, 0, 180);
         public void actionPerformed(ActionEvent e)
              System.out.println(coord);
    }

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5274611

  • Problem in drawing a line in Java Application Program

    Hi,
    I am trying to draw a line after a message is displayed on the screen. But the line is not at all coming on the screen while running. but I can see a red line is appearing on the screen first and and it is getting overridden.
    There is something wrong in the concept what I understood about graphics.Can anybody help to
    understand where the problem is ?
    Here is the part of the code which used to draw line.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.util.Date.*;
    import java.text.*;
    import java.lang.*;
    import MyPack.*;
    class chalan_pay extends JFrame
    JTextField jt1,jt2,jt3,jt4,jt5;
    JLabel jlh,jl1,jl2,jl3,jl4,jl5,jl10;
    JButton bt1,bt2,bt3;
    Choice ch1,ch2,ch3,ch4;
    Connection con = null;
    int i1no,i2no,i3no,i4no,itno;
    String idate;
    public chalan_pay()
    getContentPane().setLayout(null);
    jt1= new JTextField(5);
    jt1.setBounds(110,150,50,20);
    jt2= new JTextField(10);
    jt2.setBounds(400,150,100,20);
    jt3= new JTextField(3);
    jt3.setBounds(590,150,30,20);
    jt4= new JTextField(2);
    jt4.setBounds(750,150,30,20);
    jlh= new JLabel();
    jlh.setText("CHALLAN DETAILS");
    jlh.setBounds(300,50,200,20);
    jl1= new JLabel();
    jl1.setText("IGM No. ");
    jl1.setBounds(50,150,100,20);
    jl2= new JLabel();
    jl2.setText("IGM Date ");
    jl2.setBounds(340,150,100,20);
    jl3= new JLabel();
    jl3.setText("Line No. ");
    jl3.setBounds(530,150,100,20);
    jl4= new JLabel();
    jl4.setText("Subline No. ");
    jl4.setBounds(680,150,100,20);
    jl10= new JLabel();
    jl10.setBounds(100,200,300,20);
    ch1= new Choice();
    ch1.setBounds(170,150,150,20);
    getContentPane().add(ch1);
    ch1.addItemListener(new Opt1());
    bt1= new JButton("Exit");
    bt1.setBounds(200,600,100,20);
    getContentPane().add(bt1);
    bt1.addActionListener(new Ex());
    try
    con=db_connect.getConnection();
    Statement st1 = con.createStatement();
    ResultSet rs1 = st1.executeQuery("select igm_no,to_char(igm_dt,'DD-MON-YY'),line_no,subline_no from "+
    "det_item order by igm_no");
    while(rs1.next())
    ch1.addItem(String.valueOf(rs1.getInt(1))+" "+rs1.getString(2)+" "+
    String.valueOf(rs1.getInt(3))+" "+String.valueOf(rs1.getInt(4)));
    rs1.close();
    st1.close();
    catch(Exception e){e.printStackTrace();}
    getContentPane().add(jlh);
    getContentPane().add(jl1);
    getContentPane().add(jt1);
    getContentPane().add(jl2);
    getContentPane().add(jt2);
    getContentPane().add(jl3);
    getContentPane().add(jt3);
    getContentPane().add(jl4);
    getContentPane().add(jt4);
    getContentPane().add(jl10);
    setSize(900,700);
    setVisible(true);
    show();
    public void paint(Graphics g)
    g.setColor(Color.red);
    g.drawLine(0,300,600,300);
    class Ex implements ActionListener
    public void actionPerformed(ActionEvent evt)
    if(evt.getSource() == bt1)
    dispose();
    return;
    This code is incomplete. The program is compiled and Ran. I am unable to see the Line.
    Is it because , I am using contentPane ?. Please help me to cake it clear.
    mjava

    I have no idea what JTutor is, but if it tells you to override paint() in Swing, it's not worth its disk space.
    [http://java.sun.com/docs/books/tutorial/uiswing/painting/closer.html] clearly says that for all practical purposes paintComponent will be the only method that you will ever need to override.

Maybe you are looking for