Repaint

I'm trying to make a small city simulator game. I have a two-dimensional table (40 * 40), which is drawn on a JPanel using small gifs. Every time when player builds something and the table changes, the program repaints the panel. The problem is that this is very slow. How could I do it faster?

There are two version of the repaint method: one that repaints the whole component and one that repaints only a certain area of the component. You could try the latter one. See also this article:
http://java.sun.com/products/jfc/tsc/articles/painting/index.html

Similar Messages

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Repaint a JEditorPane after inserting data in the Document

    Hi,
    I have a button that inserts some text in a Document using the method insert(int offset, ElementSpec[] data)After that insert, the View recalculates the heights of the text lines, but they don't get refreshed on the JEditorPane. I have to manually insert a new line to make the JEditorPane get updated with the new line height.
    I have tried using invalidate() and repaint() but nothing happens. Is there another way to refresh the contents of the JEditorPane?
    Thanks!!

    revalidate() didn't work. I still have to press "enter" in any part of the document in order to have the line height changed. The method that recalculates the height of the line is View.getPreferredSpan(int) but it isn't called until I insert a new line by pressing enter.
    I think now it's not a repainting issue, I move the window outside the screen and back again and it still doesn't update. The problem is that getPreferredSpan() is not called when it repaints.
    Thanks for your response. I will try to find out how to have the view's size recalculated when I insert content.

  • How to repaint a portion of a component?

    I am working with JLayeredPane and several overlapping components which I draw a selection rectangle around when the user clicks on a component to indicate that it is "selected". If the user selects another component I need to wipe out the selection rectangle on the previously selected component. I'm not sure what the best approach for this is.
    If the initially selected component was underneath (in a lower layer than) another component, I can't simply repaint it without repainting all of the components that are above it. This seems like it could be too much painting just to remove a selection box. Can someone recommend a good approach for this problem?
    Thanks,
    Jonathan

    Thanks for the response. The components should be on separate layers (added via JLayeredPane.add(JComponent) ) so if the painter takes the layers into account, then there must be something else wrong. Here's a quick demo program of what I'm doing:
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class LayerDemo {
         private ControlMouseInputAdapter controlMouseInputAdapter = new ControlMouseInputAdapter();
    private static void createAndShowGUI() {
         LayerDemo layerDemo = new LayerDemo();
    JFrame mainFrame = new JFrame();
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {;}
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(400, 400);
    JLayeredPane layeredPane = mainFrame.getLayeredPane();
    layeredPane.add(layerDemo.createColoredLabel("test1", Color.RED, new Point(20, 20)));
    layeredPane.add(layerDemo.createColoredLabel("test2", Color.BLUE, new Point(40, 40)));
    mainFrame.setVisible(true);
    private JLabel createColoredLabel(String text, Color color,
    Point origin) {
    JLabel label = new JLabel();
    label.addMouseListener(controlMouseInputAdapter);
    label.setText(text);
    label.setOpaque(true);
    label.setBackground(color);
    label.setBounds(origin.x, origin.y, 140, 140);
    return label;
    public static void main(String[] args) throws Exception {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {createAndShowGUI();}
    private class ControlMouseInputAdapter extends MouseInputAdapter {
    public void mouseEntered(MouseEvent e) {
    JComponent component = (JComponent) e.getSource();
    component.setBorder(BorderFactory.createLineBorder(Color.black));
    public void mouseExited(MouseEvent e) {
    JComponent component = (JComponent) e.getSource();
    component.setBorder(null);
    }

  • How to repaint a component when it moves?

    Hello, I have an application with many JPanels packed together, and one of them has a picture that I render with the paint() method, using the coordinates of the panel as reference. For example, suppose I were to draw the diagonal:
    Dimension d = getSize();
    int w = d.width;
    int h = d.height;
    g.clearRect(0, 0, w, h);
    g.drawLine(0, 0, d.width - 1, d.height - 1);Now on events of user input, the size of other components may change and I revalidate the root pane. This may move or resize my JPanel where I drew.
    So I thought paint() would automatically be called if the component is moved. But it's not! the JPanel moves around, with the diagonal staying in its old place on the screen (so it is no longer the diagonal of the moved JPanel).
    Why and How to do this properly?      It would not be easy, if the user changes any of the many components, to have to manually keep track of everything else and repaint() everything else on the account that it might move, or have to compute whether it moved and repaint(). Wouldn't I be doing the job of the layout manager then? (I use many nested GridBag Layout managers).
    Thank you for any insight. Mark

    For example:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    * @version 1.0, 11/13/2008
    * @author Pete
    * Image from Funny Junk website: http://www.funnyjunk.com/funny_pictures/
    public class MovePicPanel
      private static final Dimension PANEL_SIZE = new Dimension(800, 700);
      private JPanel mainPanel = new JPanel();
      private BufferedImage image;
      private JPanel picPanel = new JPanel()
        protected void paintComponent(Graphics g)
          super.paintComponent(g);
          if (image != null)
            //!! here's where I draw my image in the JPanel
            g.drawImage(image, 0, 0, this);
      public MovePicPanel()
        try
          image  = ImageIO.read(new URL("http://newmedia.funnyjunk.com/pictures/bills-in-context.jpg"));
        catch (MalformedURLException e)
          e.printStackTrace();
        catch (IOException e)
          e.printStackTrace();
        if (image != null)
          int width = image.getWidth();
          int height = image.getHeight();
          picPanel.setSize(new Dimension(width, height));
          picPanel.setLocation(0, 0);
        JLabel clickMeLabel = new JLabel("Click me and drag mouse");
        clickMeLabel.setFont(clickMeLabel.getFont().deriveFont(Font.BOLD, 32));
        clickMeLabel.setForeground(Color.red);
        picPanel.add(clickMeLabel);
        MouseAdapter mouseAdapter = new MyMouseAdapter();
        mainPanel.addMouseListener(mouseAdapter);
        mainPanel.addMouseMotionListener(mouseAdapter);
        mainPanel.setPreferredSize(PANEL_SIZE);
        mainPanel.setLayout(null);
        mainPanel.add(picPanel);
      public JComponent getComponent()
        return mainPanel;
      private class MyMouseAdapter extends MouseAdapter
        @Override
        public void mousePressed(MouseEvent e)
          picPanel.setLocation(e.getPoint());
        @Override
        public void mouseDragged(MouseEvent e)
          picPanel.setLocation(e.getPoint());
      private static void createAndShowUI()
        JFrame frame = new JFrame("MovePicPanel");
        frame.getContentPane().add(new MovePicPanel().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }

  • How to repaint a panel

    Hi All!
    I am trying to display a few textFields in an AWT applet. The number of textFields I need to set is variable. I want to repaint a portion of an applet (the panel in which these textFields are placed) when a button is clicked.
    In the code below, I added a textField array in panel 1(p1), initialized with record size (no_of_rec), which I know at the beginning (no_of_rec = 2 at INDEX = 0).
    When I click "Next Item" button, I want to show 4 textFields (no_of_rec = 4 at INDEX = 1), with the values C, D, E, F.
    One more click (INDEX = 2) should show one textField only, with the value X.
    The codes for the textFields are in a method(addDataPanel), so that I can call it when I click "Next Item" button. A system.out check shows that 4 textFields are created when INDEX = 1, and so on, but with calling repaint() inside the button's actionPerformed method, I am unable to update the panel (p1) dynamically.
    When I minimize the window with [-] button, and get back to the original size, I can see the no of textFields have increased to 6; 2 from the beginning and 4 from the first click.
    Could someone please help?
    Thank you.
    Tienshan
    Here is my code:
    import java.awt.*;                           
    import java.applet.*;                       
    import java.awt.event.*;
    public class test1020 extends Applet{
         int NO_OF_REC = 0;
         int INDEX = 0;
         TextField[] txtDataRowDisplay;
         String[] data;
         Panel p1;
         GridBagConstraints c1;
         Color pnlBgColor = new Color(144, 196, 222);
         public void init() {     
              data = getData(INDEX);
              NO_OF_REC = data.length;
              //main Panel
              Panel pMain = new Panel();
              pMain.setLayout(new GridBagLayout());
              GridBagConstraints c  = new GridBagConstraints();
              pMain.setBackground(pnlBgColor);
              //p0
              Panel p0 = new Panel();
              p0.setLayout(new GridBagLayout());
              GridBagConstraints c0  = new GridBagConstraints();
              c0.fill = GridBagConstraints.HORIZONTAL;
              p0.setBackground(pnlBgColor);
              //p1
              p1 = new Panel();
              p1.setLayout(new GridBagLayout());
              c1  = new GridBagConstraints();
              Button btnNext = new Button("Next Item");
              c0.insets = new Insets(0, 0, 10, 0);
              c0.gridx = 3;
              c0.gridy = 0;
              p0.add(btnNext, c0);
              btnNext.addActionListener(
                   new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                             INDEX++;     
                             data = getData(INDEX);
                             NO_OF_REC = data.length;
                             addDataPanel(p1, c1);
                             display(data);
                             p1.repaint();
              //call a method to add data row(s)
              addDataPanel(p1, c1);
              //add p0 and p1 to pMain;
              c.gridx = 0;
              c.gridy = 0;
              pMain.add(p0, c);
              c.gridx = 0;
              c.gridy = 1;
              pMain.add(p1, c);
              add(pMain);
              this.setBackground(pnlBgColor);
              display(data);
         }//init
         private String[] getData(int index){
              if(index == 0){
                   String[] names = { "A", "B" };
                   return names;
              else if (index==1) {
                   String[] names = { "C", "D", "E", "F" };
                   return names;
              else {
                   String[] names = { "X" };
                   return names;
        private void addDataPanel(Panel p1, GridBagConstraints c1){
              txtDataRowDisplay = new TextField[NO_OF_REC];
              for(int i = 0; i < NO_OF_REC; i++){
                   txtDataRowDisplay[i] = new TextField(4);
              int cnt = 0;
              for(int m = 0; m < txtDataRowDisplay.length; m++ ){
                   c1.gridx = 0;
                   c1.gridy = m + cnt;
                   p1.add(txtDataRowDisplay[m], c1);
                   cnt++;
         private void display(String[] data){
              for(int i = 0; i < data.length; i++){
                   txtDataRowDisplay.setText(data[i]);

    BickelT , yes, it does work! I am almost there, only a small hurdle. When I initialize my textFields with a bigger size, all the smaller sizes are painted correctly. But when the initial size (when index is 0, that is at the time of init) is small, all the subsequent sizes are fixed to that init size.
    For example, when I change my code to the following, it works fine.
    private String[] getData(int index){
              if(index == 0){
                   String[] names = { "C", "D", "E", "F" };
                   return names;
              else if (index==1) {
                   String[] names = { "A", "B" };
                   return names;
              else {
                   String[] names = { "X"};
                   return names;
         } With the code as it is (as posted originally), in the first click, a textField with space(=height) for two textFields is painted with the value C and the lower half is empty. It is refusing to draw the area bigger than the init size of 2. When I resize the applet, I can see that four textFields with the values C, D, E, F.have been painted.
    I added the codes you suggested inside the addActionListner class. Isn't that the correct place to add the codes?
    BTW, with or without p1.repaint, the result is the same.
    What could have gone wrong?
    Thank you.

  • How to repaint a table after a change in data?????????????3F????????

    hi there
    i have a table which contains some values. i am able to delete a row from it. but i need to repaint the table, so that the change can be shown. the table is contained in a scrollPane which is contained in a Pane. i understand that to repaint, i need to call revalidate() or repaint() on a component. in my case, which component should i call the function? or it is done in different way? thank you.
    my code..
    JTable inTable = new JTable(rowDataIn, columName);
    JScrollPane spIn = new JScrollPane(inTable);
    spIn.setPreferredSize(new Dimension(650,270));
    JPanel inPane = new JPanel();
    inPane.add(spIn);
    ..2C270));
    JPanel inPane = new JPanel();
    inPane.add(spIn);
    ..

    After ur modifications done in a JTable, I think u need to call this method.
    fireTableChanged(new TableModelEvent(this)) ;
    Here this is a instance of myModel object which extends AbstractTableModel.
    Hope it helps.

  • How to repaint a table after a change in data?????????????

    hi there
    i have a table which contains some values. i am able to delete a row from it. but i need to repaint the table, so that the change can be shown. the table is contained in a scrollPane which is contained in a Pane. i understand that to repaint, i need to call revalidate() or repaint() on a component. in my case, which component should i call the function? or it is done in different way? thank you.
    my code..
    JTable inTable = new JTable(rowDataIn, columName);
    JScrollPane spIn = new JScrollPane(inTable);
    spIn.setPreferredSize(new Dimension(650,270));
    JPanel inPane = new JPanel();
    inPane.add(spIn);
    ..

    After ur modifications done in a JTable, I think u need to call this method.
    fireTableChanged(new TableModelEvent(this)) ;
    Here this is a instance of myModel object which extends AbstractTableModel.
    Hope it helps.

  • How to repaint a JTextArea inside a JScrollPane

    I am trying to show some messages (during a action event generated process) appending some text into a JTextArea that is inside a JScrollPane, the problem appears when the Scroll starts and the text appended remains hidden until the event is completely dispatched.
    The following code doesnt run correctly.
    ((JTextArea)Destino).append('\n' + Mens);
    Destino.revalidate();
    Destino.paint(Destino.getGraphics());
    I tried also:
    Destino.repaint();
    Thanks a lot in advance

    Correct me if I am wrong but I think you are saying that you are calling a method and the scrollpane won't repaint until the method returns.
    If that is so, you need to use threads in order to achieve the effect you are looking for. Check out the Model-View-Contoller pattern also.

  • How to "repaint" a custom node

    Hi everybody.
    I have working with JavaFX for a short time and a problem has come up... I'm developing an application where I dragg and drop elements from one half of the Scene to the other. Each half is represented by a Custom node that shows some thumbnails. When I dragg an element from one side to the other, I managed to insert that element in the sequence belonging to the destiny (Custom node) side.
    What I want is making this change of position visible, Each side of the Scene has a lot of thumbnails and I use a scroll to browse all the elements. When I transfer a thumbnail from one side of the Scene to the other is still the origin custom node scroll which moves the just transferred thumbnail altought it should be managed by the destiny custom node scroll...
    What I would need is a kind of "repaint" method, like the Swing's one...
    Thank's in advanced. Regards.

    Hi Nachy,
      Thanks for your replay,
    Regards,
    Anumaala Kumar

  • Image repaint preformance and threading

    Folks,
    I'm trying to make this sucker run faster.
    My question is, can anyone please guide me, especially with regards synchronising the Threads more efficiently... I'm thinking of using join and i]notify to make the "navigator" threads yield to the swing threads, to give it a chance to repaint before continuing... does this sound sane to you?
    Currently, without the thread.sleep it paints get the first "burst", and then nothing until the alrorithm has completed... exactly not what I wanted, because the whole point of this GUI is to watch the algorithm at work... sort of a "visual debugger"... I find that watching an algorithm play out helps me to "imagineer" ways of improving it... and in this case improvement means optimisation... it's all about getting from A-J faster than anyone else on the planet, especially those smarty-wishbone-legs C# programmers ;-)
    The code is too big to post (darn that 7500 char limit!) so I'll split it over several posts here, and I've also posted it as a single download to [MazeOfBoltonGUI2.java|http://groups.google.com/group/comp_lang_java_exchange/web/MazeOfBoltonGUI2.java] on my google group (comp lang java exchange).
    Cheers all. Keith.
    package forums.maze;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.SortedMap;
    import java.util.TreeMap;
    import java.util.Stack;
    import java.util.Queue;
    import java.util.PriorityQueue;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.ExecutionException;
    import java.awt.Dimension;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;
    import java.io.PrintWriter;
    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    * A Visual debugger,
    * for the [A* Alogorithm|http://en.wikipedia.org/wiki/A*_search_algorithm] navigator
    * of the [Maze Of Bolton|http://cplus.about.com/od/programmingchallenges/a/challenge12.htm]
    * as implemented by [Prometheuz|http://forums.sun.com/profile.jspa?userID=550123]
    * with GUI by [Kajbj|http://forums.sun.com/profile.jspa?userID=91610]
    * hacked together by [Keith Corlett|http://forums.sun.com/profile.jspa?userID=640846]
    * and posted on [Sun's Java Forum|http://forums.sun.com/thread.jspa?threadID=5319334]
    * and posted on [Google news group|http://groups.google.com.au/group/comp_lang_java_exchange/]
    public class MazeOfBoltonGUI2
      static final char[][] matrix = readMatrix("map.txt");
      public static void main(String[] args) {
        SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              try {
                MazeNavigator navigator = new MazeNavigator(matrix);
                JFrame frame = new JFrame("MazeOfBoltonGUI2");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new MainPanel(navigator));
                frame.pack();
                frame.setVisible(true);
              } catch (Exception e) {
                e.printStackTrace();
       * Reads the file into a char matrix[rows,cols] ie: an array of char arrays.
       * @param String filename - the name of the file to read
       * @return a fixed length array of strings containing file contents.
      private static char[][] readMatrix(String filename) {
        try {
          BufferedReader input = null;
          try {
            input = new BufferedReader(new FileReader(filename));
            char[][] matrix = null;
            List<String> lines = new ArrayList<String>();
            String line = null;
            while ( (line = input.readLine()) != null ) {
              lines.add(line);
            int rows = lines.size();
            matrix = new char[rows][];
            for (int i=0; i<rows; i++) {
              matrix[i] = lines.get(i).toCharArray();
            System.err.println("DEBUG: rows="+rows+", cols="+matrix[0].length);
            return matrix;
          } finally {
            if(input!=null)input.close();
        } catch (IOException e) {
          e.printStackTrace();
          throw new IllegalStateException("Failed to readMatrix!", e);
    class MainPanel extends JPanel
      private static final long serialVersionUID = 1L;
      // button panel
      private final JButton goButton;
      // maze panel
      private final MazeNavigator navigator;
      private final Monitor<Path> monitor;
      private BufferedImage background;
      private BufferedImage image;
      private List<Path>currentPaths;
      public MainPanel(MazeNavigator navigator) {
        this.navigator = navigator;
        this.monitor = new SwingMonitor();
        this.goButton = new JButton("Go");
        goButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent event) {
              final String caption = goButton.getText();
              goButton.setVisible(false);
              monitor.execute();
        add(goButton);
        setPreferredSize(new Dimension(navigator.maze.cols*3, navigator.maze.rows*3)); //w,h
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      private static Color[][] mazeColors;
      private static Color[][] createMazeColors(Maze maze) {
        Color[][] colors = new Color[maze.rows][maze.cols];
        for (int r=0; r<maze.rows; r++) {
          for (int c=0; c<maze.cols; c++) {
            colors[r][c] = getColor(maze.matrix[r][c].ch);
        return colors;
      }*... PTO ...*

    I'm persuaded that the main issue (no intermediate results drawn) is the improper use of SwingWorker.
    When you've got over it, you may want to consider other smaller-effect optimizations:
    Reconsider usage of an offscreen image*
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image==null) {
          image = (BufferedImage)createImage(navigator.maze.cols, navigator.maze.rows);
          mazeColors = createMazeColors(navigator.maze);
        this.draw(image.createGraphics());
        ((Graphics2D)g).drawImage(image, 0, 0, super.getWidth(), super.getHeight(), null);
      }At first I didn't get why you wanted to draw an offscreen image, then paint it to the screen, all that in the EDT.
    After reading the draw() method more closely, I guess you want to ease the coding of the scaling: you draw an image where one cell = one pixel, then paint the image, scaled to the panel's display size.
    In terms of performance, I don't know how it stands:
    On one hand, the image creation if lighter (1 pixel per cell). And you have a point that the built-in scaling offered by Graphics2D.drawImage(image, size) may be efficient. I can't comment on that, I hope the granphics and hardware acceleration folks will pop in the thread.
    On the other hand, if the built-in scaling had poor performance, it may be good to try what "manual" scaling would bring you. That means, in a simplified version, skip the offscreen image creation, and draw directly on the paintComponent()'s Graphics2D argument. the drawing of a cell at coordinates c,r, for example, would look like:
    g.fillRect(c*CELL_WIDTH, r*CELL_HEIGHT, WIDTH, HEIGHT);Performance apart, the scaling as you do it currently has functional drawbacks, if you want pathes as 1-pixel width lines over large cells:
    - if the maze is smaller (in rows, columns) than the panel displaying it (in pixels), the cells will be scaled but the pathes too: so your 1-pixel lines appear as large as the cells. May or may not be a desired effect.
    - if the maze is larger than the display panel, the cells are shrinked, fine, but the so are the path lines, to a point where they may be invisible (probably depending on color blending, I'm a n00b at graphics operations).
    But maybe I misunderstood the need, and maybe the intended drawing of a path is actually the drawing of the rectangles of all its traversed cells, in special path colors?
    Reconsider intermediate allocations*
    Each paintComponent() call results in the allocation of a 2D-array of Color objects (method createMazeColors(Maze)).
    I don't see what the mazeColors array brings you. I assume you wanted to decouple the determination of colors (depending on cell state) and the rendering of the colors: what does it bring: no performance advantage (on the contrary, it adds a 2D array allocation, and 2xN^2 2D-array access), and does not improve the code readability either (subjective rant, sorry).
    Why don't you pass the Maze as an argument to the draw() method, and call the getColor(cell.ch) from there?
    Side note, maybe a bit subjective: performance apart, the design of the usage of this mazeColor array is a no-go!
    An instance method alters a static variable reference,which is used subsequently in another instance method, with no synchronization. The current code does that in a single thread (+paintxxx()+ is only called in the EDT), which keeps that safe (I'd dare to say: by luck), but considerations exposed below may have you refactor the design to introduce other threads, and may exhibit the thread-unsafety of this design.
    Consider drawing the image in a background thread.*
    Indeed the technique of drawing to an offscreen image is quite common, but it is often done to improve responsiveness (not raw performance) of Swing applications. Here is a resource about this (what the author calls the passive approach), although it doesn't use a background thread.
    The idea is that if a paintCompobnent() methods involves lots of computation (arithmetics of traversing a 2D model, scaling things, etc.), this takes CPU times in the EDT, and all subsequent events (such as, a MouseEvent, but also other painting events) keep pending on the event queue, which is consumed by the single event-dispatch thread. The result is that the UI appear unresponsive, and painting of other areas may seem hung.
    The idea is to move the computation to a background thread, which posts rendering to the EDT when the Image is ready to be displayed.
    Of course this doesn't gain any CPU time. This only ensures the EDT uses a minimal part of this CPU (only render and image and process events), instead of performing the whole computation.
    In your case you already have a background thread, and indeed an appropriate choice, a SwingWorker. The application of this technique would consist in calling the draw() method in the worker thread (in the update(Path) method), and invoke super.publish() only after the image has been updated. Note that the process(List<Path>) could then ignore its argument (you may reconsider the choice of type parameter of the worker), and simply get the latest version of the image attribute).
    Of course in this technique, the offscreen image filling is called synchronously from the Navigator, so this halts the algorithm part itself, for the duration of the image generation. You may refine the technique by spawning a dedicated thread for the image generation - with subtle guard code to handle occasions when the algorithm goes faster than the image generation, and posts a new update(Path) while the image generation for the previous path has not completed yet...
    Recuce the number of things to redraw*
    Two parts:
    first, depending on the number of cells and pathes, there may be (yet another) optimization, to not redraw the whole offscreen image, but only the cells/path that have changed in the last update(). In particular, if a path is not a line but a list of cells, then it's quite easy, reusing the current offscreen image, to only fillRect(...) the appropriate cells.
    Second, if a path is not rendered as a thin line over larger cells, but as cells themselves rendered in special path colors, you may paint cells and path in one go: instead of drawing, first the cells, then the path, draw only the cells, electing the color using a decision method such as:
    private Color getColor(Cell) {
        if (cell.getPathState()!=NOT_IN_ANY_PATH) {
            return getColor(cell.getPathState());
        else {
            return getColor(cell.ch);
    }Of course this forces you to modify your data model, and update the new pathState as part of the algorithm (or better isolated, in the update(Path) method, before invoking the drawing machinery). Maybe that was the intention of the mazeColors array?
    I haven't studied your other posts on the logic of the MazeOfBolton algorithm, so I don't know if it's acceptable for you that a cell appear to have only one path state, as opposed to one for each of the pathes that traverse it. This last trick may then seem incorrect, but please consider it as only a graphical information, and indeed your current image drawing draws only ONE path for a given cell (the last path in currentPaths that traverses this cell ).

  • Repaint Problem in JInternalFrame!!!! help plz.

    hi,
    I have a question I have an application that has internal frames, Basically it is a MDI Application. I am using JDK 1.2.2 and windows 2000. The following example shows that when I drag my JInternalFrames only the border is shown and the contents are not shown as being dragged that's fine, but the application I am running have lot of components in my JInternalFrames. And when I drag the JInternalFrame my contents are not being dragged and that's what I want but when I let go the internalFrame it takes time to repaint all the components in the internalFrame. Is there any way I can make the repaint goes faster after I am done dragging the internalFrame. It takes lot of time to bring up the internalframe and it's components at a new location after dragging. Is there a way to speed up the repainting. The following example just shows how the outline border is shown when you drag the internalFrame. As there are not enough components in the internal frame so shows up quickly. But when there are lots of components specially gif images inside the internalframe it takes time.
    /*************** MDITest ************/
    import javax.swing.*;
    * An application that displays a frame that
    * contains internal frames in an MDI type
    * interface.
    * @author Mike Foley
    public class MDITest extends Object {
    * Application entry point.
    * Create the frame, and display it.
    * @param args Command line parameter. Not used.
    public static void main( String args[] ) {
    try {
    UIManager.setLookAndFeel(
    "com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
    } catch( Exception ex ) {
    System.err.println( "Exception: " +
    ex.getLocalizedMessage() );
    JFrame frame = new MDIFrame( "MDI Test" );
    frame.pack();
    frame.setVisible( true );
    } // main
    } // MDITest
    /*********** MDIFrame.java ************/
    import java.awt.*;
    import java.awt.event.*;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    * A top-level frame. The frame configures itself
    * with a JDesktopPane in its content pane.
    * @author Mike Foley
    public class MDIFrame extends JFrame implements Serializable {
    * The desktop pane in our content pane.
    private JDesktopPane desktopPane;
    * MDIFrame, null constructor.
    public MDIFrame() {
    this( null );
    * MDIFrame, constructor.
    * @param title The title for the frame.
    public MDIFrame( String title ) {
    super( title );
    * Customize the frame for our application.
    protected void frameInit() {
    // Let the super create the panes.
    super.frameInit();
    JMenuBar menuBar = createMenu();
    setJMenuBar( menuBar );
    JToolBar toolBar = createToolBar();
    Container content = getContentPane();
    content.add( toolBar, BorderLayout.NORTH );
    desktopPane = new JDesktopPane();
    desktopPane.putClientProperty("JDesktopPane.dragMode", "outline");
    desktopPane.setPreferredSize( new Dimension( 400, 300 ) );
    content.add( desktopPane, BorderLayout.CENTER );
    } // frameInit
    * Create the menu for the frame.
    * <p>
    * @return The menu for the frame.
    protected JMenuBar createMenu() {
    JMenuBar menuBar = new JMenuBar();
    JMenu file = new JMenu( "File" );
    file.setMnemonic( KeyEvent.VK_F );
    JMenuItem item;
    file.add( new NewInternalFrameAction() );
    // file.add( new ExitAction() );
    menuBar.add( file );
    return( menuBar );
    } // createMenuBar
    * Create the toolbar for this frame.
    * <p>
    * @return The newly created toolbar.
    protected JToolBar createToolBar() {
    final JToolBar toolBar = new JToolBar();
    toolBar.setFloatable( false );
    toolBar.add( new NewInternalFrameAction() );
    // toolBar.add( new ExitAction() );
    return( toolBar );
    * Create an internal frame.
    * A JLabel is added to its content pane for an example
    * of content in the internal frame. However, any
    * JComponent may be used for content.
    * <p>
    * @return The newly created internal frame.
    public JInternalFrame createInternalFrame() {
    JInternalFrame internalFrame =
    new JInternalFrame( "Internal JLabel" );
    internalFrame.getContentPane().add(
    new JLabel( "Internal Frame Content" ) );
    internalFrame.setResizable( true );
    internalFrame.setClosable( true );
    internalFrame.setIconifiable( true );
    internalFrame.setMaximizable( true );
    internalFrame.pack();
    return( internalFrame );
    * An Action that creates a new internal frame and
    * adds it to this frame's desktop pane.
    public class NewInternalFrameAction extends AbstractAction {
    * NewInternalFrameAction, constructor.
    * Set the name and icon for this action.
    public NewInternalFrameAction() {
    super( "New", new ImageIcon( "new.gif" ) );
    * Perform the action, create an internal frame and
    * add it to the desktop pane.
    * <p>
    * @param e The event causing us to be called.
    public void actionPerformed( ActionEvent e ) {
    JInternalFrame internalFrame = createInternalFrame();
    desktopPane.add( internalFrame,
    JLayeredPane.DEFAULT_LAYER );
    } // NewInternalFrameAction
    } // MDIFrame
    I'll really appreciate for any help.
    Thank you

    Hi
    if you fill the ranges
    r_rundate-sign = 'I'.
    r_rundate-option = 'EQ'.
    r_rundate-low = '20080613'.
    r_rundate-high = '20080613'.
    APPEND r_rundate.
    EQ = 'equal', the select check the record with data EQ r_rundate-low.
    change EQ with BT  
    BT = between
    r_rundate-sign = 'I'.
    r_rundate-option = 'BT'.
    r_rundate-low = '20080613'.
    r_rundate-high = '20080613'.
    APPEND r_rundate.
    reward if useful, bye

  • MDI JTable Overlap Area Repaint Problem

    Hi all,
    I have a problem for my application in MDI mode.
    I open many windows (JInternalFrame contain JTable) under JDesktopPane. Some of the windows are overlapping and when they receive update in the table, it seems repaint all of the overlapping windows, not only itself. This make my application performance become poor, slow respond for drap & drop an existing window or open a new window.
    To prove this, i make a simple example for open many simple table and have a thread to update the table's value for every 200 mill second. After i open about 20 windows, the performance become poor again.
    If anyone face the same problem with me and any suggestions to solve the problem ?
    Please help !!!!!
    Following are my sources:
    public class TestMDI extends JFrame {
        private static final long serialVersionUID = 1L;
        private JPanel contentPanel;
        private JDesktopPane desktopPane;
        private JMenuBar menuBar;
        private List<TestPanel> allScreens = new ArrayList<TestPanel>();
        private List<JDialog> freeFloatDialogs = new ArrayList<JDialog>();
        private List<JInternalFrame> mdiInternalFrm = new ArrayList<JInternalFrame>();
        int x = 0;
        int y = 0;
        int index = 0;
        private static int MDI_MODE = 0;
        private static int FREE_FLOAT_MODE = 1;
        private int windowMode = MDI_MODE;
        public TestMDI() {
            init();
        public static void main(String[] args) {
            new TestMDI().show();
        public void init() {
            contentPanel = new JPanel();
            desktopPane = new JDesktopPane();
            desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
            desktopPane.setFocusTraversalKeysEnabled(false);
            desktopPane.setFocusTraversalPolicyProvider(false);
            desktopPane.setBorder(null);
            desktopPane.setIgnoreRepaint(true);
            desktopPane.setPreferredSize(new Dimension(1000, 800));
            this.setSize(new Dimension(1000, 800));
            menuBar = new JMenuBar();
            JMenu menu1 = new JMenu("Test");
            JMenuItem menuItem1 = new JMenuItem("Open Lable Screen");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        final TestJLableScreen screen = new TestJLableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            JMenuItem menuItem2 = new JMenuItem("Open Table Screen");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (int i = 1; i < 4; i++) {
                        TestTableScreen screen = new TestTableScreen("Screen  " + (allScreens.size() + 1));
                        screen.startTime();
                        if (windowMode == MDI_MODE) {
                            JInternalFrame frame = createInternalFram(screen);
                            desktopPane.add(frame);
                            mdiInternalFrm.add(frame);
                            if (allScreens.size() * 60 + 100 < 1000) {
                                x = allScreens.size() * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            frame.setLocation(x, y);
                            frame.setVisible(true);
                        } else {
                            JDialog dialog = createJDialog(screen);
                            freeFloatDialogs.add(dialog);
                            if (i * 60 + 100 < 1000) {
                                x = i * 60;
                                y = 60;
                            } else {
                                x = 60 * index;
                                y = 120;
                                index++;
                            dialog.setLocation(x, y);
                            dialog.setVisible(true);
                        allScreens.add(screen);
            menu1.add(menuItem1);
            menu1.add(menuItem2);
            this.setJMenuBar(menuBar);
            this.getJMenuBar().add(menu1);
            this.getJMenuBar().add(createSwitchMenu());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(desktopPane);
            desktopPane.setDesktopManager(null);
        public JInternalFrame createInternalFram(final TestPanel panel) {
            final CustomeInternalFrame internalFrame = new CustomeInternalFrame(panel.getTitle(), true, true, true, true) {
                public void doDefaultCloseAction() {
                    super.doDefaultCloseAction();
                    allScreens.remove(panel);
            internalFrame.setPanel(panel);
            // internalFrame.setOpaque(false);
            internalFrame.setSize(new Dimension(1010, 445));
            internalFrame.add(panel);
            internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setFocusTraversalPolicyProvider(false);
            desktopPane.getDesktopManager();
            // internalFrame.setFocusTraversalKeysEnabled(false);
            internalFrame.setIgnoreRepaint(true);
            return internalFrame;
        public JDialog createJDialog(final TestPanel panel) {
            JDialog dialog = new JDialog(this, panel.getTitle());
            dialog.setSize(new Dimension(1010, 445));
            dialog.add(panel);
            dialog.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    allScreens.remove(panel);
            return dialog;
        public JMenu createSwitchMenu() {
            JMenu menu = new JMenu("Test2");
            JMenuItem menuItem1 = new JMenuItem("Switch FreeFloat");
            menuItem1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = FREE_FLOAT_MODE;
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    remove(desktopPane);
                    desktopPane.removeAll();
    //                revalidate();
                    repaint();
                    add(contentPanel);
                    index = 0;
                    for (JDialog dialog : freeFloatDialogs) {
                        dialog.setVisible(false);
                        dialog.dispose();
                        dialog = null;
                    freeFloatDialogs.clear();
                    for (int i = 0; i < allScreens.size(); i++) {
                        JDialog dialog = createJDialog(allScreens.get(i));
                        freeFloatDialogs.add(dialog);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        dialog.setLocation(x, y);
                        dialog.setVisible(true);
            JMenuItem menuItem2 = new JMenuItem("Switch MDI");
            menuItem2.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    windowMode = MDI_MODE;
                    remove(contentPanel);
                    add(desktopPane);
                    for (int i = 0; i < freeFloatDialogs.size(); i++) {
                        freeFloatDialogs.get(i).setVisible(false);
                        freeFloatDialogs.get(i).dispose();
                    freeFloatDialogs.clear();
    //                revalidate();
                    repaint();
                    for (JInternalFrame frm : mdiInternalFrm) {
                        frm.setVisible(false);
                        frm.dispose();
                        frm = null;
                    mdiInternalFrm.clear();
                    index = 0;
                    for (int i = 0; i < allScreens.size(); i++) {
                        JInternalFrame frame = createInternalFram(allScreens.get(i));
                        desktopPane.add(frame);
                        mdiInternalFrm.add(frame);
                        if (i * 60 + 100 < 1000) {
                            x = i * 60;
                            y = 60;
                        } else {
                            x = 60 * index;
                            y = 120;
                            index++;
                        frame.setLocation(x, y);
                        frame.setVisible(true);
            menu.add(menuItem1);
            menu.add(menuItem2);
            return menu;
    public class TestTableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        JTable testTable = new JTable();
        MyTableModel tableModel1 = new MyTableModel(1);
        private boolean notRepaint = false;
        int start = 0;
        JScrollPane scrollPane = new JScrollPane();
        private Timer timmer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(50);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        notRepaint = false;
                        TestTableScreen.this.update(index + "|" + val);
        public TestTableScreen(String title) {
            this.title = title;
            init();
            tableModel1.setTabelName(title);
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                List vals = tableModel1.getVector();
                if (vals.size() > index) {
                    vals.set(index, val[1]);
    //                 tableModel1.fireTableRowsUpdated(index, index);
                } else {
                    vals.add(val[1]);
    //                 tableModel1.fireTableRowsUpdated(vals.size() - 1, vals.size() - 1);
                tableModel1.fireTableDataChanged();
        public TableModel getTableModel() {
            return tableModel1;
        public void init() {
            testTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            testTable.setRowSelectionAllowed(true);
            this.testTable.setModel(tableModel1);
            int[] width = { 160, 80, 45, 98, 60, 88, 87, 88, 80, 70, 88, 80, 75, 87, 87, 41, 88, 82, 75, 68, 69 };
            TableColumnModel columnModel = testTable.getColumnModel();
            for (int i = 0; i < width.length; i++) {
                columnModel.getColumn(i).setPreferredWidth(width[i]);
            testTable.setRowHeight(20);
            tableModel1.fireTableDataChanged();
            this.setLayout(new BorderLayout());
            TableColumnModel columnMode2 = testTable.getColumnModel();
            int[] width2 = { 200 };
            for (int i = 0; i < width2.length; i++) {
                columnMode2.getColumn(i).setPreferredWidth(width2[i]);
            scrollPane.getViewport().add(testTable);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            this.add(scrollPane, BorderLayout.CENTER);
        class MyTableModel extends DefaultTableModel {
            public List list = new ArrayList();
            String titles[] = new String[] { "袨怓1", "袨怓2", "袨怓3", "袨怓4", "袨怓5", "袨怓6", "袨怓7", "袨怓8", "袨怓9", "袨怓10", "袨怓11",
                    "袨怓12", "袨怓13", "袨怓14", "袨怓15", "袨怓16", "袨怓17", "袨怓18", "袨怓19", "袨怓20", "袨怓21" };
            String tabelName = "";
            int type_head = 0;
            int type_data = 1;
            int type = 1;
            public MyTableModel(int type) {
                super();
                this.type = type;
                for (int i = 0; i < 50; i++) {
                    list.add(i);
            public void setTabelName(String name) {
                this.tabelName = name;
            public int getRowCount() {
                if (list != null) {
                    return list.size();
                return 0;
            public List getVector() {
                return list;
            public int getColumnCount() {
                if (type == 0) {
                    return 1;
                } else {
                    return titles.length;
            public String getColumnName(int c) {
                if (type == 0) {
                    return "head";
                } else {
                    return titles[c];
            public boolean isCellEditable(int nRow, int nCol) {
                return false;
            public Object getValueAt(int r, int c) {
                if (list.size() == 0) {
                    return null;
                switch (c) {
                default:
                    if (type == 0) {
                        return r + " " + c + "  test ";
                    } else {
                        return list.get(r) + "   " + c;
        public boolean isNotRepaint() {
            return notRepaint;
        public void setNotRepaint(boolean notRepaint) {
            this.notRepaint = notRepaint;
    public class TestPanel extends JPanel {
        protected String title = "";
        protected boolean needRepaint = false;
        protected boolean isFirstOpen = true;
        public String getTitle() {
            return title;
        public void setNeedRepaint(boolean flag) {
            this.needRepaint = flag;
        public boolean isNeedRepaint() {
            return needRepaint;
        public boolean isFirstOpen() {
            return isFirstOpen;
        public void setFirstOpen(boolean isFirstOpen) {
            this.isFirstOpen = isFirstOpen;
    public class TestJLableScreen extends TestPanel {
        private static final long serialVersionUID = 1L;
        private JLabel[] allLables = new JLabel[20];
        private Timer timmer = new Timer(20, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Random indexRandom = new Random();
                final int index = indexRandom.nextInt(10);
                Random valRandom = new Random();
                final int val = valRandom.nextInt(600);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        TestJLableScreen.this.setNeedRepaint(true);
                        TestJLableScreen.this.update(index + "|" + val);
        public TestJLableScreen(String title) {
            this.title = title;
            init();
        public void startTime() {
            timmer.start();
        public String getTitle() {
            return title;
        public void update(String updateStr) {
            String[] val = updateStr.split("\\|");
            if (val.length == 2) {
                int index = Integer.valueOf(val[0]);
                allLables[index * 2 + 1].setText(val[1]);
        public void init() {
            this.setLayout(new GridLayout(10, 2));
            boolean flag = true;
            for (int i = 0; i < allLables.length; i++) {
                allLables[i] = new JLabel() {
                    // public void setText(String text) {
                    // super.setText(text);
                    // // System.out.println("  setText " + getTitle() + "   ; " + this.getName());
                    public void paint(Graphics g) {
                        super.paint(g);
                        // System.out.println("  paint " + getTitle() + "   ; " + this.getName());
                    // public void repaint() {
                    // super.repaint();
                    // System.out.println("  repaint " + getTitle() + "   ; " + this.getName());
                allLables[i].setName("" + i);
                if (i % 2 == 0) {
                    allLables[i].setText("Name " + i + "  : ");
                } else {
                    allLables[i].setOpaque(true);
                    if (flag) {
                        allLables[i].setBackground(Color.YELLOW);
                        flag = false;
                    } else {
                        allLables[i].setBackground(Color.CYAN);
                        flag = true;
                    allLables[i].setText(i * 8 + "");
            for (int i = 0; i < allLables.length; i++) {
                this.add(allLables[i]);
    public class CustomeInternalFrame extends JInternalFrame {
        protected TestPanel panel;
        public CustomeInternalFrame() {
            this("", false, false, false, false);
        public CustomeInternalFrame(String title) {
            this(title, false, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable) {
            this(title, resizable, false, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable) {
            this(title, resizable, closable, false, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable) {
            this(title, resizable, closable, maximizable, false);
        public CustomeInternalFrame(String title, boolean resizable, boolean closable, boolean maximizable,
                boolean iconifiable) {
            super(title, resizable, closable, maximizable, iconifiable);
        public TestPanel getPanel() {
            return panel;
        public void setPanel(TestPanel panel) {
            this.panel = panel;

    i had the same problem with buttons and it seemed that i overlayed my button with something else...
    so check that out first do you put something on that excact place???
    other problem i had was the VAJ one --> VisualAge for Java (terrible program)
    it does strange tricks even when you don't use the drawing tool...
    dunno 2 thoughts i had... check it out...
    SeJo

  • Problem with repaint() in JPanel

    Hi,
    This is the problem: I cyclically call the repaint()-method but there is no effect of it.
    When does it appear: The problem occurs by calling the repaint()-method of a JPanel -class.
    This is what i am doing: The repaint() is called from a different class which is my GUI. I do this call in an endless loop which is done within a Thread.
    I tried to add a KeyListener to the JPanel-class and there I called the repaint()-method when i press a Key. Then the Panel is repainted.
    so I implemented a "callRepaint"-method in the JPanel-class that does nothing else than call repaint() (just like the keyPressed()-method does). But when i cyclically call this "callRepaint"-method from my GUI nothing happens.
    Now a few codedetails:
    // JPanel-class contains:
    int i = 0;
    public void callRepaint(){
                    repaint();
    public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawLine(i++,0,200,200);
    public void keyPressed(KeyEvent e) {
            repaint();                       // This is working
    //GUI-class contains:
    // This method is called cyclically
    public void draw() {
                  lnkJPanelclass.repaint();             // This calling didn't work
                  // lnkJPanelclass.callRepaint();  // This calling didn't work     
    Thanks for your advices in advance!
    Cheers spike

    @ARafique:
    This works fine:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Date;
    import javax.swing.*;
    public class Test extends JFrame implements ActionListener{
        private JTextField label;
        private Timer timer;
        private Container cont;
        public Test() {
            label = new JTextField("",0);
            timer = new Timer(1000,this);
            cont = getContentPane();
            cont.add(label);
            setSize(250,70);
            setDefaultCloseOperation(3);
            setVisible(true);
            timer.start();
        public void actionPerformed(ActionEvent e){
            label.setText(new Date(System.currentTimeMillis()).toString());
        public static void main(String[] args){
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new Test();
    }no repaint()/revalidate() needed

  • Problem with repaint of display after a click event

    Hi,
    I have a problem with repaint of display. In particular in method keyPressed() i inserted a statement that, after i clicked bottom 2 of phone, must draw a string. But this string doesn't drawing.
    Instead if i reduce to icon the window, which emulate my application, and then i enlarge it, i see display repainted with the string.
    I don't know why.
    Any suggestions?
    Please help me.

    modified your code little
    don't draw in keyPressed
    import java.io.IOException;
    import javax.microedition.lcdui.Canvas;
    import javax.microedition.lcdui.Command;
    import javax.microedition.lcdui.CommandListener;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Displayable;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    public class PlayerCanvas extends Canvas implements CommandListener{
         Display display;
         Displayable dsp11;
    private Image play, pause, stop, next, previous = null;
    private int gamcode;
    private Command quitCmd = new Command("Back", Command.ITEM, 1);
    public PlayerCanvas(Display display,Displayable dsp11){
         this.display =display;
         this.dsp11 =dsp11;
         addCommand(quitCmd);
         createController();
         setCommandListener(this);
         display.setCurrent(this);
              protected void paint(Graphics g)
              g.setColor(255,200,150);
              g.fillRect(0, 0, getWidth(), getHeight());
              if (play != null){
              g.drawImage(play, getWidth()/5, getHeight()-50, Graphics.BOTTOM | Graphics.HCENTER);
              if (stop != null){
              g.drawImage(stop, getWidth()/5, getHeight()-10, Graphics.BOTTOM | Graphics.HCENTER);
              if (next != null){
              g.drawImage(next, (getWidth()/5)+10, getHeight()-30, Graphics.BOTTOM | Graphics.LEFT);
              if (previous != null){
              g.drawImage(previous, (getWidth()/5)-30, getHeight()-30, Graphics.BOTTOM | Graphics.LEFT);
                   /////this will draw on key UP
                   g.setColor(0,0,0);
                   System.out.print(gamcode);
                   if(gamcode==Canvas.UP){
                        g.drawString("PROVA",10, 0, 0);
                   }else if(gamcode==Canvas.DOWN){
                        g.drawString("DIFFERENT",10, 30, 0);     
    private void createController()
    try {
    play = Image.createImage("/icon3.png");//replace your original images plz
    pause = Image.createImage("/icon3.png");
    stop = Image.createImage("/icon3.png");
    next = Image.createImage("/icon3.png");
    previous = Image.createImage("/icon3.png");
    } catch (IOException e) {
    play = null;
    pause = null;
    stop = null;
    next = null;
    previous = null;
    if (play == null){
    System.out.println("cannot load play.png");
    if (pause == null){
    System.out.println("cannot load pause.png");
    if (stop == null){
    System.out.println("cannot load stop.png");
    if (next == null){
    System.out.println("cannot load next.png");
    if (previous == null){
    System.out.println("cannot load previous.png");
              protected void keyPressed(int keyCode)
                   repaint();
                   if ( (keyCode == 2) || (UP == getGameAction(keyCode)) ){
                        gamcode = UP;
                        repaint();
                        else if ( (keyCode == 8) || (DOWN == getGameAction(keyCode)) ){
                             gamcode =DOWN;
                             repaint();
              else if ( (keyCode == 4) || (LEFT == getGameAction(keyCode)) ){
              else if ( (keyCode == 6) || (RIGHT == getGameAction(keyCode)) ){
              public void commandAction(Command arg0, Displayable arg1) {
                   // TODO Auto-generated method stub
                   if(arg0==quitCmd){
                        display.setCurrent(dsp11);
    }

  • Avoiding the repaint of all components in an JApplet

    Hello everyone,
    Thannks to all who gave me advices for the two JComboBoxes I had...finally I found two "if" conditions in the actionPerformed of the first JComboo which restricted the list of elements posted in the second one.
    I have a much bigger problem now....The Applet contains an object which is an extension of JPanel, and in this extension there is a "paintComponent()" that creates a certain number of JButtons in a "for" loop. The problem I have is :
    How could I avoid this panel to be repainted every time the page containing the Applet is resized? Is it even possible( because from what I've been reading a "paint()" of the applet always calls for all the components' "repaint()".....I haven't even definned a "paint()" for the applet, .....and then, each button has an action listener that simply won't work after a repaint() of the whole applet. And honestly i'm starting to lose my mind a bit over all this......Oh, I had almost forgotten....the problem after re-sizing is that within the borders of the Panel there are always buttons created by the "for" loop ....and they are smaller and appear high up "north" in the panel...it's horrible!!!!!
    This is my code for the paintComponent() of the extension of the JPanel:
    public void paintComponent(Graphics g){
           g.drawLine (130,50,130,450);
           g.drawLine (129,50,129,450);
           g.drawLine (270,50,270,450);
           g.drawLine (271,50,271,450);
           g.drawString("Plateau no.", 80,40);
           g.setColor(ballon);
           g.fillArc(100,434,200,100,45,-270);
           System.out.println("I've been through paint");
        for(int i=0;i<13;i++)
           System.out.println("buton ok"+i);
           plateaux=new JButton();
    plateaux[i].setEnabled(true);
    plateaux[i].addActionListener(this);
    Color cri=new Color(240-15*i,0,0);
    plateaux[i].setBounds(130,60+30*i,139,15);
    plateaux[i].setBackground(cri);
    add(plateaux[i], null);
    g.drawString(" "+ (13-i),105,70+30*i);
    There's nothing else in the extension....only the paint ...it implements ActionListener.....
    Thankx in advance....I'd really apreciate it if someone could help me.....
    Ruxi

    To clear the background for each repaint add a call to super or use clearRect or fillRect (with the background color set, of course). If you don't do this you will get artifacts in your graphics.
    class GraphicComponent extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            // carry on...
    }Paint code is the place to render graphics and images, not for adding components. Add your components to the GUI in or via init. Generally is is useful to keep your drawing component separate from your other components.
    class GUIClass extends JApplet implements ActionListener {
        public void init() {
            JPanel buttonPanel = getButtonPanel();
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(buttonPanel, "South");
            getContentPane().add(new GraphicComponent());  // default center section
        private JPanel getButtonPanel() {
            JPanel panel = new JPanel(null);
            JButton[] plateaux = nw JButton[13];
            for(int i=0;i<plateaux.length;i++) {
                System.out.println("buton ok"+i);
                plateaux=new JButton("button " + i);
    plateaux[i].setEnabled(true);
    plateaux[i].addActionListener(this);
    Color cri=new Color(240-15*i,0,0);
    plateaux[i].setBounds(130,60+30*i,139,15);
    plateaux[i].setBackground(cri);
    panel.add(plateaux[i]);

Maybe you are looking for

  • Report region source error

    Hi all, I'm trying to display report ( SQL Query report ) the query is as follows:- SELECT E.C001, E.C002, AE.C001, AE.C002 FROM APEX_COLLECTIONS COLLECTION_NAME = 'EXAMPLE' A INNER JOIN APEX_COLLECTIONS COLLECTION_NAME = 'ANOTHER_EXAMPLE' AE ON E.SE

  • WRT54G V. 6 error code 401 unauthorized access

    I wanted to upgrade the firmware, because I was having problems getting to the online properties. I did the powercycling and all,  I would get the error 401 "unathorized access" message. I then downloaded the firmware upgrade to my desktop, then went

  • Export mailboxes to PST (Exchange 2007)

    Hi All, Is there an 'export-mailbox' cmdlet I can use to export each of the mailboxes in our mailbox database using the following file name format, so that the full smtp address is used as the filename of each the PST file exported: [email protected]

  • Ora 01033- Oracle initialization or shutdown in process

    Hi all I am getting this error when I try to connect to SQL......I have restart the serveice of orcl but the result is same here Is any way to get out from this error? Thanks in advance Shayan [email protected]

  • "Invalid Bundle." "...viewer.app does not support the minimum OS version specified in the Info.plist"

    I tried re-building the app and it's not helping. The plist has the minimum OS listed as 6.0. I could go in and try to change it manually but then the signing would be invalid. Please fix this ASAP.