Problem in repaint

I drawn some rectangles.If one rectangle was clicked,the rectangles below it should move down..but for me,its not repainting.the old location as well as the new location was there when i click the rectangle...
import javax.swing.JApplet;
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Rectangle;
import java.awt.event.MouseListener;
import java.util.ArrayList;
* @author 8563
public class TestTree extends JApplet
    @Override
    public void init()
        Container con = getContentPane();
        con.setLayout(new BorderLayout());
        setPreferredSize(new Dimension(300, 300));
        JScrollPane scroll = new JScrollPane();
        getContentPane().add(scroll, BorderLayout.CENTER);
        scroll.setViewportView(new ImagePanel());
    private class ImagePanel extends JPanel implements MouseListener {
        ImagePanel image;
        Rectangle rext = new Rectangle(40, 40, 30, 15);
        int[] x = {75, 95, 115, 130};
        int[] width = {15, 15, 15, 15};
        boolean selected1 = false;
        int count;
        Rectangle [] rects;
        Rectangle [] rectangles;
        ArrayList<Rectangle> hlp;
        public ImagePanel()
            prepareData();
            this.addMouseListener(this);
        @Override
        protected void paintComponent(Graphics g)
            Graphics2D g2 = (Graphics2D) g;
            g2.draw(rext);
            drawRect(g2);
        public void prepareData()
            int x = 75;
            int y = 85;
            int w = 20;
            int h = 15;
            hlp = new ArrayList<Rectangle>();
            for (int i = 0; i < 4; i++) {
                hlp.add(new Rectangle(x, y, w, h));
                y += 25;
            rectangles = hlp.toArray(new Rectangle[hlp.size()]);
       public void drawRect(Graphics g)
            Graphics2D g2 = (Graphics2D) g;
            for (Rectangle r : rectangles)
                g2.draw(r);
                //repaint();
        public void mouseClicked(MouseEvent e)
            Point mse_clk = e.getPoint();
            int count_incr = count+1;
            int y = 150;
            for(int i=count_incr;i<rectangles.length;i++)
                if(selected1)
                    rectangles.setLocation(rectangles[i].x,rectangles[i].y+20);
// repaint();
repaint();
public void mousePressed(MouseEvent e)
Point pres_point = e.getPoint();
for (int i=0;i<rectangles.length;i++)
if(rectangles[i].contains(pres_point))
selected1 = true;
count = i;
break;
public void mouseReleased(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public static void main(String[] args) {
JApplet applet = new TestTree();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(applet);
f.setSize(400, 400);
f.setLocationRelativeTo(null);
applet.init();
f.setVisible(true);

        @Override
        protected void paintComponent(Graphics g)
            // paint the background..
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.draw(rext);
            drawRect(g2);
        }

Similar Messages

  • 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);
    }

  • 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 to "repaint" the 3D screen

    Hi everyone, I wrote an application that moves some geometrical objects when the user click on them, using Picking. The situation was supposed to happens like this: after the user clicks on an object i translate it to a distant position in order to hide it, so the place where the objects were stays empty, then i wait for some seconds and other configurations (i mean other positions) of the objects appear.
    The problem is that the place does not stays empty it keep the old frame (i mean the old positions configuration) during all time i wait and just after that the frame show the new configuration. I guess it something related to Thread.sleep() the method i use to wait some seconds.
    So my question is: Is there other strategy to do this such thing i intend? Maybe something like �Repaint�. Since now thanks a lot. I hope to have made myself to understand due my poor English writing.
    �der.

    messengers, i'm writing the Behavior class but i got a doubt, how can i get the action that wakeup the Thread.sleep in order to pass to wakeuponBehaviorPost class?
    The code i found is like this:
      public class MyBehaviorTranslation extends Behavior{
          MyBehaviorTranslation(Group root, Bounds bounds) {
            this.setSchedulingBounds(bounds);
            BranchGroup branchGroup = new BranchGroup();
            branchGroup.addChild(this);
            root.addChild(branchGroup);
          public void initialize(){
              // set initial wakeup condition
              this.wakeupOn(new WakeupOnBehaviorPost(???, 0));
              // set someIntegerValue to your specific value
              // null can be replaced by an specific Behavior Object to send this value
          // called by Java 3D when appropriate stimulus occures
          public void processStimulus(Enumeration criteria){
            // do what is necessary
            // resetup Behavior
             this.wakeupOn(new WakeupOnBehaviorPost(????, 0));
      }Thanks a lot since now.
    �der.

  • Problems with repainting

    Hi,
    I have a JFrame, which contains a JPanel (named activePanel). I also added a method to change the active JPanel. It goes like this:
    public class MyFrame extends JFrame {
    private JPanel activePanel;
    public void setActivePanel(JPanel otherPanel) {
    activePanel.setVisible(false);
    activePanel = otherPanel;
    activePanel.revalidate();
    activePanel.setVisible(true);
    this.getContentPane().validate();
    this.getContentPane().repaint();
    System.out.println("finished!"); // for debugging only
    The problem is that when this method is called, the current activePanel becomes invisible, the 'finished'-string is printed, but the otherPanel is still not showing...
    What is going wrong? What can I do?
    TIA

    Hello!
    I think you would like to replace the active panel
    with another panel.
    There are two methods to do this:
    1.
    Remove the panel from the frame and then add the new
    panel to the frame
    2.
    Use CardLayout manager instead. It is very fine!
    This layout manager lays out components like cards in deck.
    Only one 'card' can be shown at a time (int this situation the activePanel).
    You can use the show(Container c, String name) method
    to switch between panels.
    I have used this layout manager in my project and it works
    fine.
    Hope it helps you
    regards
    Feri

  • Problem using repaint() method from another class

    I am trying to make tower of hanoi...but unable to transfer rings from a tower to another...i had made three classes....layout21 where all componentents of frame assembled and provided suitable actionlistener.....second is mainPanel which is used to draw the rods n rings in paintComponent.....and third is tower in which code for hanoi is available...i had made an object of mainPanel at layoout21 n tower but i m not able to call repaint from tower..gives an error : cannot find the symbol....method repaint in tower.
    code fragments od three classes are:
    LAYOUT21
    class layout21 extends JFrame implements ActionListener
    { private Vector rod1 = new Vector();
    private Vector rod2 = new Vector();
    private Vector rod3 = new Vector();
    private String elem; //comment
    public String r22;
    public boolean in=false;
    public int count=0; //no of times the transfer to other rods performed
    private int r3,rings; // current no of rings
    private JComboBox nor,col;
    private JLabel no;
    private JLabel moved;
    private JLabel no1;
    private JButton start;
    private JButton ref;
    private AboutDialog dialog;
    private JMenuItem aboutItem;
    private JMenuItem exitItem;
    private tower t;
    final mainPanel2 p =new mainPanel2();
    public layout21()
    { t = new tower();
         Toolkit kit =Toolkit.getDefaultToolkit();
    Image img = kit.getImage("java.gif");
    setIconImage(img);
    setTitle("Tower Of Hanoi");
    setSize(615,615);
    setResizable(false);
    setBackground(Color.CYAN);
         JMenuBar mbar = new JMenuBar();
    setJMenuBar(mbar);
    JMenu fileMenu = new JMenu("File");
    mbar.add(fileMenu);
    aboutItem = new JMenuItem("About");
    aboutItem.addActionListener(this);
    fileMenu.add(aboutItem);
    exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(this);
    fileMenu.add(exitItem);
    Container contentPane =getContentPane();
    JPanel bspanel = new JPanel();
    JPanel bnpanel = new JPanel();
    setBackground(Color.CYAN);
         //JComboBox
    nor = new JComboBox();
    nor.setEditable(false);
    nor.addItem("3");
    nor.addItem("4");
    nor.addItem("5");
    nor.addItem("6");
    nor.addItem("7");
    nor.addItem("8");
    nor.addItem("9");
    bspanel.add(nor);
    col = new JComboBox();
    col.setEditable(false);
    col.addItem("BLACK");
    col.addItem("GREEN");
    col.addItem("CYAN");
    bspanel.add(col);
    JLabel tl = new JLabel("Time");
    tl.setFont(new Font("Serif",Font.BOLD,12));
    bspanel.add(tl);
    JTextField tlag = new JTextField("0",4);
    bspanel.add(tlag);
    start =new JButton("Start");
    bspanel.add(start);
    ref =new JButton("Refresh");
    bspanel.add(ref);
    JButton end =new JButton("End");
    bspanel.add(end);
    start.addActionListener(this);
    nor.addActionListener(this);
    col.addActionListener(this);
    ref.addActionListener(this);
    end.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    dispose(); // Closes the dialog
    contentPane.add(bspanel,BorderLayout.SOUTH);
    JLabel count = new JLabel("No of Transfer reguired:");
    count.setFont(new Font("Serif",Font.BOLD,16));
    bnpanel.add(count);
    no = new JLabel("7");
    no.setFont(new Font("Serif",Font.BOLD,16));
    bnpanel.add(no);
    JLabel moved = new JLabel("Moved:");
    moved.setFont(new Font("Serif",Font.BOLD,16));
    bnpanel.add(moved);
    no1 = new JLabel("0");
    no1.setFont(new Font("Serif",Font.BOLD,16));
    bnpanel.add(no1);
    contentPane.add(bnpanel,BorderLayout.NORTH);
    contentPane.add(p,BorderLayout.CENTER);
         String r = (String)nor.getSelectedItem();
    rings = Integer.valueOf(r).intValue();
    p.draw(rings,1) ;
    public void actionPerformed(ActionEvent evt)
    {  Object source = evt.getSource();
    if(source == start)
    r3 = Integer.valueOf((String)nor.getSelectedItem()).intValue();
    p.transfer(false);
    t.initialise(rod1,rod2,rod3,0);
    t.towerOfHanoi(r3);
         //repaint();
         if(source == ref)
    { rod1.removeAllElements() ;
    rod2.removeAllElements() ;
    rod3.removeAllElements() ;
    count=0;
              r3 = Integer.valueOf((String)nor.getSelectedItem()).intValue();
              p.draw(r3,1);
    p.transfer(true);
    no1.setText(""+0);
    p.trans_vec(rod1,rod2,rod3);
    t.initialise(rod1,rod2,rod3,0);
              System.out.println("");
              repaint();
    if(source == nor)
    { JComboBox j = (JComboBox)source;
    String item = (String)j.getSelectedItem();
    int ring1 = Integer.valueOf(item).intValue();
    int a=1;
    for(int i=1;i<=ring1;i++)
    { a = a*2;
    a=a-1;
    no.setText(""+a);
    p.draw(ring1,1);
    repaint();
    if(source == aboutItem)
    {  if (dialog == null) // first time
    dialog = new AboutDialog(this);
    dialog.setVisible(true);
    if(source == exitItem)
    {  System.exit(0);
         if (source==col)
         { JComboBox j = (JComboBox)source;
    String item = (String)j.getSelectedItem();
              repaint();
    TOWER
    class tower extends Thread
    { private Vector rod1 = new Vector();
    private Vector rod2 = new Vector();
    private Vector rod3 = new Vector();
    private int count ;
    private String elem;
    final mainPanel2 z =new mainPanel2();
    public void initialise(Vector r1,Vector r2,Vector r3,int c)
    { rod1 = r1;
    rod2 = r2;
         rod3 = r3;
         count =c;
    public void towerOfHanoi(int rings)
    for(int i=0;i<rings;i++)
    rod1.add(" "+(i+1));
    System.out.println("rod1:"+rod1.toString());
    hanoi(rings,1,2);
    public void hanoi(int m,int i, int j)
    if(m>0)
    { hanoi(m-1,i,6-i-j);
    if(i==1 && j==2 && rod1.isEmpty()==false)
    { count++;
    //no1.setText(""+count);
    elem = (String)rod1.remove(0);
    rod2.add(0,elem);
         //z.trans_vec(rod1,rod2,rod3);
    repaint(); //NOT ABLE TO USE METHOD HERE...WHY??
    //z.hanoi_paint();
    try
              this.sleep(2000);      
              catch (Exception e) { e.printStackTrace() ;  }
    System.out.println(count+". ROD 2:"+rod2.toString());
    if(i==1 && j==3 && rod1.isEmpty()==false)
    { count++;
         //no1.setText(""+count);
         elem = (String)rod1.remove(0);
    rod3.add(0,elem);
    //z.trans_vec(rod1,rod2,rod3);
    repaint();//
    // z.hanoi_paint();
                   try
              this.sleep(2000);      
              catch (Exception e) { e.printStackTrace() ;  }
    System.out.println(count+". ROD 3:"+rod3.toString());
    if(i==2 && j==1 && rod2.isEmpty()==false)
    { count++;
         //no1.setText(""+count);
         elem = (String)rod2.remove(0);
    rod1.add(0,elem);
    //z.trans_vec(rod1,rod2,rod3);
    repaint();
    //z.hanoi_paint();
    try
              this.sleep(2000);      
              catch (Exception e) { e.printStackTrace() ;  }
    System.out.println(count+". ROD 1:"+rod1.toString());
    if(i==2 && j==3 && rod2.isEmpty()==false)
    { count++;     
         //no1.setText(""+count);
         elem = (String)rod2.remove(0);
    rod3.add(0,elem);
    //z.trans_vec(rod1,rod2,rod3);
    repaint();
    //z.hanoi_paint();
    try
              this.sleep(2000);      
              catch (Exception e) { e.printStackTrace() ;  }
    System.out.println(count+". ROD 3:"+rod3.toString());
    if(i==3 && j==1 && rod3.isEmpty()==false)
    { count++;
         //no1.setText(""+count);
    elem = (String)rod3.remove(0);
    rod1.add(0,elem);
    //z.trans_vec(rod1,rod2,rod3);
    repaint();
    //z.hanoi_paint();
         try
              this.sleep(2000);      
              catch (Exception e) { e.printStackTrace() ;  }
    System.out.println(count+". ROD 1:"+rod1.toString());
    if(i==3 && j==2 && rod3.isEmpty()==false)
    { count++;
         //no1.setText(""+count);
    elem = (String)rod3.remove(0);
    rod2.add(0,elem);
    //z.trans_vec(rod1,rod2,rod3);
    repaint();
    //z.hanoi_paint();
    try
              this.sleep(2000);      
              catch (Exception e) { e.printStackTrace() ;  }
    System.out.println(count+". ROD 2:"+rod2.toString());
    hanoi(m-1,6-i-j,j);
    MAINPANEL
    class mainPanel2 extends JPanel //throws IOException
    public Vector line = new Vector();
    public Vector rod11= new Vector();
    public Vector rod22= new Vector();
    public Vector rod33= new Vector();
    public int no_ring;
    public int rod_no;
    String pixel;
    StringTokenizer st,st1;
    int x,y;
    public boolean initial =true;
    public void paintComponent(Graphics g)
    { System.out.println("repaint test");
    bresenham(100,60,100,360);
         bresenham(101,60,101,360);
    bresenham(102,60,102,360);
    bresenham(103,60,103,360);
    bresenham(104,60,104,360);     
    g.setColor(Color.BLUE);
    while(line.size()>0)
    { pixel = (String)line.remove(0);
    st = new StringTokenizer(pixel);
    x = Integer.valueOf(st.nextToken()).intValue();
    y = Integer.valueOf(st.nextToken()).intValue();
    g.drawLine(x,y,x,y);
    bresenham(300,60,300,360);
    bresenham(301,60,301,360);
    bresenham(302,60,302,360);
    bresenham(303,60,303,360);
    bresenham(304,60,304,360);     
    while(line.size()>0)
    { pixel = (String)line.remove(0);
    st = new StringTokenizer(pixel);
    x = Integer.valueOf(st.nextToken()).intValue();
    y = Integer.valueOf(st.nextToken()).intValue();
    g.drawLine(x,y,x,y);
    bresenham(500,60,500,360);
    bresenham(501,60,501,360);
    bresenham(502,60,502,360);
    bresenham(503,60,503,360);
    bresenham(504,60,504,360);     
    while(line.size()>0)
    { pixel = (String)line.remove(0);
    st = new StringTokenizer(pixel);
    x = Integer.valueOf(st.nextToken()).intValue();
    y = Integer.valueOf(st.nextToken()).intValue();
    g.drawLine(x,y,x,y);
    bresenham(0,361,615,361);//used to get a pixel according to algo.. . func not provided
    bresenham(0,362,615,362);
    bresenham(0,363,615,363);
    bresenham(0,364,615,364);
    bresenham(0,365,615,365);     
    while(line.size()>0)
    { pixel = (String)line.remove(0);
    st = new StringTokenizer(pixel);
    x = Integer.valueOf(st.nextToken()).intValue();
    y = Integer.valueOf(st.nextToken()).intValue();
    g.drawLine(x,y,x,y);
    if(initial==true)
    g.setColor(Color.RED);
    for(int i = no_ring;i>0;i--)
    { g.drawLine(100-(i*8),360-(no_ring - i)*10,100+(i*8)+5,360-(no_ring - i)*10);
    g.drawLine(100-(i*8),359-(no_ring - i)*10,100+(i*8)+5,359-(no_ring - i)*10);
    g.drawLine(100-(i*8),358-(no_ring - i)*10,100+(i*8)+5,358-(no_ring - i)*10);
    g.drawLine(100-(i*8),357-(no_ring - i)*10,100+(i*8)+5,357-(no_ring - i)*10);
    g.drawLine(100-(i*8),356-(no_ring - i)*10,100+(i*8)+5,356-(no_ring - i)*10);
    // draw for each rod
    //System.out.println("rod11:"+rod11);
    //System.out.println("rod22:"+rod22);
    //System.out.println("rod33:"+rod33);
         int r1 = rod11.size();
         int r2 = rod22.size();
         int r3 = rod33.size();
    String rd1,rd2,rd3;
    int r11,r12,r21,r22,r31,r32;
    if(initial == false)
         { g.setColor(Color.RED);
         while(rod11.size()>0)
    { r12 = rod11.size()-1;
              rd1 = (String)rod11.remove(r12);
    r11 = Integer.valueOf(rd1).intValue();
    g.drawLine(100-((r11+1)*8),360-(r1 - (r11+1))*10,100+((r11+1)*8)+5,360-(r1 - (r11+1))*10);
    g.drawLine(100-((r11+1)*8),359-(r1 - (r11+1))*10,100+((r11+1)*8)+5,359-(r1 - (r11+1))*10);
              g.drawLine(100-((r11+1)*8),358-(r1 - (r11+1))*10,100+((r11+1)*8)+5,358-(r1 - (r11+1))*10);
              g.drawLine(100-((r11+1)*8),357-(r1 - (r11+1))*10,100+((r11+1)*8)+5,357-(r1 - (r11+1))*10);
              g.drawLine(100-((r11+1)*8),356-(r1 - (r11+1))*10,100+((r11+1)*8)+5,356-(r1 - (r11+1))*10);
         while(rod22.size()>0)
    { g.setColor(Color.RED);
              r22 = rod22.size()-1;
         System.out.println("TEST *************************:"+r22);
              try
         // e.printStackTrace();      
              InputStreamReader isr = new InputStreamReader(System.in);
         BufferedReader br = new BufferedReader(isr)      ;
         br.readLine() ;
         }catch(Exception f) {}
              rd2 = ((String)rod22.remove(r22)).trim();
    r21 = Integer.valueOf(rd2).intValue();
    g.drawLine(300-((r22+1)*8),360-(r2 - (r22+1))*10,300+((r22+1)*8)+5,360-(r2 - (r22+1))*10);
    g.drawLine(300-((r22+1)*8),359-(r2 - (r22+1))*10,300+((r22+1)*8)+5,359-(r2 - (r22+1))*10);
              g.drawLine(300-((r22+1)*8),358-(r2 - (r22+1))*10,300+((r22+1)*8)+5,358-(r2 - (r22+1))*10);
              g.drawLine(300-((r22+1)*8),357-(r2 - (r22+1))*10,300+((r22+1)*8)+5,357-(r2 - (r22+1))*10);
              g.drawLine(300-((r22+1)*8),356-(r2 - (r22+1))*10,300+((r22+1)*8)+5,356-(r2 - (r22+1))*10);
         while(rod33.size()>0)
    { g.setColor(Color.RED);
              r32 = rod33.size()-1;
              rd3 = (String)rod33.remove(r32);
    r31 = Integer.valueOf(rd3).intValue();
    g.drawLine(500-((r32+1)*8),360-(r3 - (r32+1))*10,500+((r32+1)*8)+5,360-(r3 - (r32+1))*10);
    g.drawLine(500-((r32+1)*8),359-(r3 - (r32+1))*10,500+((r32+1)*8)+5,359-(r3 - (r32+1))*10);
              g.drawLine(500-((r32+1)*8),358-(r3 - (r32+1))*10,500+((r32+1)*8)+5,358-(r3 - (r32+1))*10);
              g.drawLine(500-((r32+1)*8),357-(r3 - (r32+1))*10,500+((r32+1)*8)+5,357-(r3 - (r32+1))*10);
              g.drawLine(500-((r32+1)*8),356-(r3 - (r32+1))*10,500+((r32+1)*8)+5,356-(r3 - (r32+1))*10);
    why i m not able to use repaint() method in tower class? from where i can use repaint() method

    i can't read your code - not formatted with code tags
    I have no chance of getting it to compile (AboutDialog class?? p.draw() ??)
    here's a basic routine - add a couple of things to this to demonstrate what is not
    being redrawn
    (compare the readability of below code (using tags) to yours)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setSize(400,300);
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        final DrawPanel dp = new DrawPanel();
        JButton btn = new JButton("Change Text Location/Repaint");
        getContentPane().add(dp,BorderLayout.CENTER);
        getContentPane().add(btn,BorderLayout.SOUTH);
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            dp.x = (int)(Math.random()*300);
            dp.y = (int)(Math.random()*150)+50;
            repaint();}});
      public static void main(String[] args){new Testing().setVisible(true);}
    class DrawPanel extends JPanel
      int x = 50, y = 50;
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        g.drawString("Hello World",x,y);
    }

  • Problems with repainting in new JD 9.0.4.0

    I just installed new JD 9.0.4.0 . I think that from this moment I have problems with painting java graphics objects (for example Application Module tests or simple login dialogs). When I move that window, its remains are left on the screen until I overlap them with other non-java window. Has anybody the same experience ?

    I haven't seen this. One thought (call it grasping at straws) would be to set the environment variable: J2D_D3D=false
    That disables Java2D and sometimes fixes some quirks.
    Rob
    Team JDev

  • Problem with repainting, should be Threaded...

    Hello,
    I want to smoothly animate a square to some co&ouml;rdinates of the screen, smoothly means with some time between new co&ouml;rds.
    I'm using the following code:
                        for(int i = 0; i<5; i++)
                             bx-=2;
                             repaint();
                             try
                                  Thread.sleep(tijdTussenFrame);
                                  System.out.println("Wacht nummer: "+i);
                             catch(Exception er)
                                  System.out.println("error bij wachten voor pijl links!");
                        }However, I don't seem to repaint when the (small sleep times) are in use...
    My paint Thread should be a different Thread than the one that is sleeping small times...
    My full code:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * @author Man Ik Weet
    import java.applet.*;
    import java.awt.event.*;
    import java.awt.*;
    //import java.net.URL; //alleen als er plaatjes worden geladen!
    public class RPG extends Applet implements KeyListener, Runnable,MouseListener, MouseMotionListener
         //nodig voor extra Thread
         Thread painter = null;
         boolean threadSuspended;
         //Offscreen tekeken
         Graphics bg;
         Image offscreen;
         //dimensie scherm
         int width,height;
         //x en y muis
         int xm,ym = 0;
         //alles voor audio/plaatjes
         //URL base;
         //AudioClip geluidjeNaam;
         //Image plaatjeNaam;
         //MediaTracker mt; //alleen nodig als er plaatjes worden geladen van het internet
         //voor de FPS
         int fps = 25; //de frames per seconde, game sloom? zet dit hoger/lager;
         int tijdTussenFrame;
         //Voor het blokje dat reageert op de pijlen...
         int bx,by = 0;
         boolean keyInGedrukt = false; //als er een toets is gedruk wacht de thread, maar hij vangt wel andere toetsen dan op
         public void init()
              //zorg voor het laden van plaatjes en/of geluid
              /*try
                   base = getDocumentBase();
              catch (Exception e)
              plaatjeNaam = getImage(base,"plaatjeNaam.png");
              mt.addImage(plaatjeNaam,1); 1 = hoeveelste plaatje
              naam = getAudioClip(base, "naam.au");
              try
                  mt.waitForAll();
             catch (InterruptedException  e)
                  System.out.println("Fout bij wachten voor alle plaatjes...");
              //zwarte achtergrond FTW
              setBackground(Color.black);
              //zet alles op voor muis/toetsenboord
              addKeyListener(this);
              addMouseListener(this);
              addMouseMotionListener(this);
              //pixels voor scherm, we willen niet te groot of te klein ;)
              width = getSize().width;
              height = getSize().height;
              offscreen = createImage(width, height);
              bg = offscreen.getGraphics();
              tijdTussenFrame = (1000/fps);
       public void start()
              if (painter == null )
                   painter  = new Thread( this );
                   painter.setPriority( Thread.MAX_PRIORITY );
                   threadSuspended = false;
                   painter.start();
              else
                   if ( threadSuspended )
                        threadSuspended = false;
                        synchronized( this )
                             notify();
         public void stop()
              threadSuspended = true;
         public void run() {
              try
                   while (true)
                        //hier doet het IETS? LMAO! muwahahahaha!
                        if (threadSuspended)
                             synchronized( this )
                                  while (threadSuspended)
                                       wait();
                        repaint();
                        painter.sleep(tijdTussenFrame);  // interval given in milliseconds
              catch (InterruptedException e) { }
         public void paint(Graphics g)
              bg.clearRect(0,0,width,height);
              bg.setColor(Color.red);
              bg.drawString("Key ingedrukt: "+keyInGedrukt,width/2,height/2);
              bg.drawString(xm+";"+ym, xm, ym);
              bg.setColor(Color.cyan);
              bg.fillRect(bx, by, 10, 10);
              g.drawImage(offscreen,0,0,this);
         public void update(Graphics g)
              paint(g);
         public void mouseClicked(MouseEvent me)
              xm = me.getX();
              ym = me.getY();
         public void mousePressed(MouseEvent me)
         public void mouseReleased(MouseEvent me)
         public void mouseEntered(MouseEvent me)
         public void mouseExited(MouseEvent me)
         public void mouseDragged(MouseEvent me)
              xm = me.getX();
              ym = me.getY();
         public void mouseMoved(MouseEvent me)
              xm = me.getX();
              ym = me.getY();
        public void keyTyped(KeyEvent e)
            System.out.println("Key getypt.");
        public void keyPressed(KeyEvent e)
              if(keyInGedrukt==false)
                   keyInGedrukt=true;
                   System.out.println("Key ingedrukt.");
                   if(e.getKeyCode()==KeyEvent.VK_LEFT)
                        System.out.println("Key pijl links.");
                        for(int i = 0; i<5; i++)
                             bx-=2;
                             repaint();
                             try
                                  Thread.sleep(tijdTussenFrame);
                                  System.out.println("Wacht nummer: "+i);
                             catch(Exception er)
                                  System.out.println("error bij wachten voor pijl links!");
                   if(e.getKeyCode()==KeyEvent.VK_RIGHT)
                        System.out.println("Key pijl rechts.");
                        bx+=10;
                   if(e.getKeyCode()==KeyEvent.VK_UP)
                        System.out.println("Key pijl omhoog.");
                        by-=10;
                   if(e.getKeyCode()==KeyEvent.VK_DOWN)
                        System.out.println("Key pijl naar beneden.");
                        by+=10;
              else
                   System.out.println("Key is ingedrukt?");
        public void keyReleased(KeyEvent e)
              keyInGedrukt = false;
            System.out.println("Key losgelaten.");
            if(e.getKeyCode()==KeyEvent.VK_LEFT)
                   System.out.println("Key pijl links losgelaten.");
                   bx-=10;
              if(e.getKeyCode()==KeyEvent.VK_RIGHT)
                   System.out.println("Key pijl rechts losgelaten.");
                   bx+=10;
            if(e.getKeyCode()==KeyEvent.VK_UP)
                   System.out.println("Key pijl omhoog losgelaten.");
                   by-=10;
              if(e.getKeyCode()==KeyEvent.VK_DOWN)
                   System.out.println("Key pijl naar beneden losgelaten.");
                   by+=10;
    }

    Doesn't work that way. You have to remove the old Button and insert the new one:import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class ButtonExample extends JFrame implements ActionListener {
         JButton b1, b2;
         JLabel l1 = new JLabel("left");
         JLabel l2 = new JLabel("right");
         JPanel jp = new JPanel(new BorderLayout());
         ButtonExample() {
              setSize(800, 600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              Container conPane = getContentPane();
              b1 = new JButton("First Click");
              b2 = new JButton("Second Click");
              b1.addActionListener(this);
              jp.add(l1,BorderLayout.EAST);
              jp.add(b1,BorderLayout.CENTER);
              jp.add(l2,BorderLayout.WEST);
              conPane.add(jp);
              pack();
              setVisible(true);
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand() == "First Click") {
                   System.out.println("fldf");
                   jp.remove(b1);
                   jp.add(b2,BorderLayout.CENTER);
                   pack();
                   validate();
         static public void main(String args[]) {
              ButtonExample fr = new ButtonExample();
    }

  • Problem to repaint my applet

    Hi,
    I am developping an applet that owns several interface. So I have an interface Identificator and another Registrator.
    During the init() phase of my applet I create my Panel object Identificator, and I display it.
    When I click on the button register (contained in Identificator), I create my new Panel Object Rgistrator, and I try to display it.
    First I remove the Identificator Panel of the Applet's Container and I add the Registrator Panel to it.
    After that I lauch the method repaint().
    After that nothing is displayed, but if I resize my Browser Window, my interface Registrator is displayed!!!!!!!!
    Is there someone that could help me...
    Thank you very much...

    maybe the setVisible(true) operator may work,. I know that when I forget this in a JFrame my frame won't show.
    Greetings,.
    Arnoud

  • Problem on repaint ()

    currently i am doing a system to generate 3D object
    therefore i am trying rotate the 3d object but the object didnt rotate althought i had call the rotation function and repaint as well
    i have check my rotate function but nothing wrong

    So... what about posting some code now ?...

  • Problem in repainting jtextarea

    My requirement is, client has to sent string messages and server has to receive these messages and display it in jtextarea. In my code sending and receiving are done properly, but the problem is the jtextarea is not updated, it goes blank.
    I have attached the client and server files, can anyone solve my problem?
    Thanks in advance.
    //server file
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MessageCenter extends javax.swing.JFrame {
        public MessageCenter() {
            initComponents();
        private void initComponents() {
            jLabel1 = new JLabel();
            jScrollPane1 = new JScrollPane();
            jTextArea1 = new JTextArea();
            jPanel1 = new JPanel();
            jLabel5 = new JLabel();
            jLabel3 = new JLabel();
            jButton1 = new JButton();
            jButton2 = new JButton();
            jLabel2 = new JLabel();
            jLabel4 = new JLabel();
            menuBar = new JMenuBar();
            fileMenu = new JMenu();
            Start = new JMenuItem();
            jSeparator1 = new JSeparator();
            Stop = new JMenuItem();
            jSeparator2 = new JSeparator();
            Exit = new JMenuItem();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            setTitle("Message Center");
            setMaximizedBounds(new java.awt.Rectangle(0, 0, 560, 700));
            setBounds(0,0,600,700);
            setName("");
            jLabel1.setBackground(new java.awt.Color(255, 255, 255));
            jLabel1.setFont(new java.awt.Font("Georgia", 1, 24));
            jLabel1.setForeground(new java.awt.Color(34, 44, 106));
            jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
            jLabel1.setText("Message Center");
            jLabel1.setIconTextGap(0);
            getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
            jTextArea1.setColumns(20);
            jTextArea1.setFont(new java.awt.Font("Book Antiqua", 0, 12));
            jTextArea1.setLineWrap(true);
            jTextArea1.setRows(25);
            jTextArea1.setBorder(null);
            jScrollPane1.setViewportView(jTextArea1);
            getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
            jPanel1.setLayout(new java.awt.GridLayout(1, 6, 10, 5));
            jPanel1.add(jLabel5);
            jPanel1.add(jLabel3);
            jButton1.setText("Start");
            jPanel1.add(jButton1);
            jButton2.setText("Stop");
            jPanel1.add(jButton2);
            jPanel1.add(jLabel2);
            jPanel1.add(jLabel4);
            getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
            fileMenu.setText("File");
            Start.setText("Start");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    System.out.println("hello");
                    StartActionPerformed(evt);
            fileMenu.add(Start);
            fileMenu.add(jSeparator1);
            Stop.setText("Stop");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    StopActionPerformed(evt);
            fileMenu.add(Stop);
            fileMenu.add(jSeparator2);
            Exit.setText("Exit");
            fileMenu.add(Exit);
            menuBar.add(fileMenu);
            setJMenuBar(menuBar);
            pack();
    private void StartActionPerformed(java.awt.event.ActionEvent evt)  {
              try{
                        Server t=new Server(jTextArea1);
                        t.listenSocket();
              catch(Exception e)
              e.printStackTrace();
        private void StopActionPerformed(java.awt.event.ActionEvent evt) {
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MessageCenter().setVisible(true);
        private JMenuItem Exit;
        private JMenuItem Start;
        private JMenuItem Stop;
        private JMenu fileMenu;
        private JButton jButton1;
        private JButton jButton2;
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JLabel jLabel3;
        private JLabel jLabel4;
        private JLabel jLabel5;
        private JPanel jPanel1;
        private JScrollPane jScrollPane1;
        private JSeparator jSeparator1;
        private JSeparator jSeparator2;
        public JTextArea jTextArea1;
        private JMenuBar menuBar;
    class ClientThread implements Runnable {
      private Socket client;
      JTextArea jt;
      ClientThread(Socket client,JTextArea jt) {
       this.client = client;
       this.jt=jt;
      public void run(){
        try{
               //DataInputStream dis= new DataInputStream(client.getInputStream());
                DataInputStream dis= new DataInputStream(new BufferedInputStream(client.getInputStream()));
               System.out.println("client connected");
               //BufferedReader dis = new BufferedReader(new InputStreamReader(s.getInputStream()));
                   String msg=null;
                   byte msg1[]=new byte[200];
                while(true)
                   try{
                   if(dis.available()>0)
                   dis.readFully(msg1,0,dis.available());
                 //  System.out.println("Msg is ==> "+new String(msg1));
                   new PrinterThread(jt,new String(msg1)).start();
                   msg1=new byte[200];
                   Thread.sleep(1000);
                      }catch (Exception e) {
                         System.out.println("Exception  ");
             } catch (IOException e) {
                         System.out.println("Exception occurred");
    class Server {
              JTextArea jt;
              public Server(JTextArea jt)
                   this.jt=jt;
              public void listenSocket() throws Exception
              ServerSocket ss=null;
              try{
              ss=new ServerSocket(8000);
              System.out.println("Server started");
             catch (IOException e) {
                         System.out.println("Exception");
                         System.exit(-1);
             while(true){
               ClientThread w;
               try{
            w = new ClientThread(ss.accept(),jt);
            Thread t = new Thread(w);
            t.start();
                catch (IOException e) {
            System.out.println("Accept failed: 8000");
           public static void main(String args[])throws Exception {
              /*Server t=new Server();
              t.listenSocket();*/
         class PrinterThread extends Thread
                public PrinterThread(JTextArea jt1,String msg)
                 jTextArea1 = jt1;
                 this.msg=msg;
                 System.out.println("PrinterThread constructor ");
                public void run()
                 try
                    Date today;
                    SimpleDateFormat formatter;
                    String output;
                     String pattern="dd.MM.yyyy '@' H:mm";
                    formatter = new SimpleDateFormat(pattern);
                    today = new Date();
                    output = formatter.format(today);
                        System.out.println(" "+output+"  "+msg+" \n");
                          jTextArea1.append(" "+output+"  "+msg+" \n");
                          jTextArea1.updateUI();
                             jTextArea1.revalidate();
    //                      JOptionPane.showMessageDialog(null,"hi");
                          //System.out.println("Get text "+jTextArea1.getText());
                 catch (Exception exception) {}
                private JComboBox combo;
                private JTextArea jTextArea1;
                String msg=null;
    //client.java
    import java.net.*;
    import java.io.*;
    import java.io.File;
    public class client {
           public static void main(String args[]) {
                   try {
                           Socket ss=new Socket(InetAddress.getLocalHost(),8000);
                           DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
                           for(int i=1;i<100;i++){
                              if((i%2)==0)
                            dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3233");
                              else
                            dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42");
                           Thread.sleep(5000);
                   catch(Exception e) {
                   e.printStackTrace();
                   System.out.println(" ");
    }

    You need to run your Server in a separate Thread.
    Right now its running in the GUI Event Thread.I created new thread for my server, now it's updating jtextarea.
    Thank you very much.

  • Having problems with repaint (I think).

    Hi,
    Im trying to ceate a form which display's all images in the current directory as thumbnails. The problem is that when the form is shown, the images don't remain visible. Any idea how to fix this?
    (Simplified version):
    import javax.swing.JFrame;
    import javax.swing.BoxLayout;
    public class FrmMain extends JFrame
       public FrmMain()
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
          setBounds(0,0,600,400);
       public static void main(String[] args)
          FrmMain formMain = new FrmMain();
          ImagePanel imagePanel1 = new ImagePanel(".\\test01.jpg");
          ImagePanel imagePanel2 = new ImagePanel(".\\test02.jpg");
          formMain.getContentPane().add(imagePanel1);
          formMain.getContentPane().add(imagePanel2);
          formMain.setVisible(true);
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    public class ImagePanel extends JPanel
       public ImagePanel(String fileName)
          this.fileName = fileName;
          setBorder(BorderFactory.createEtchedBorder());
          setBounds(0,0,WIDTH,HEIGHT);
       public void paint(Graphics g)
          super.paint(g);
          File file = new File(fileName);
          if(file.exists())
             try
                BufferedImage buffImage = ImageIO.read(file);
                Image image = getThumbnail(buffImage);
                Graphics2D g2d = (Graphics2D)getGraphics();
                g2d.setColor(Color.BLACK);
                g2d.fillRect(0,0,WIDTH,HEIGHT);
                g2d.drawImage(image, (WIDTH - image.getWidth(null)) / 2, (WIDTH - image.getHeight(null)) / 2, null);
             catch(Exception e)
                System.out.println(e);
       private Image getThumbnail(BufferedImage buffImage)
          int newHeight = 0;
          int newWidth = 0;
          int remain = 0;
          if (buffImage.getHeight() > HEIGHT)
             remain = buffImage.getHeight() - HEIGHT;
             remain = (int)((remain / (double)(buffImage.getHeight())) * 100);
             newHeight = HEIGHT;
             newWidth = (int)(buffImage.getWidth() * ((100 - (double)remain) / 100));
          if (newWidth > WIDTH)
             remain = newWidth - WIDTH;
             remain = (int)((remain / (double)newWidth) * 100);
             newWidth = WIDTH;
             newHeight = (int)(newHeight * ((100 - (double)remain) / 100));
          return buffImage.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_SMOOTH);
       public static int WIDTH = 100;
       public static int HEIGHT = 100;
       private String fileName;
       public String getFileName()
          return fileName;
       public void setFileName(String fileName)
          this.fileName = fileName;
          update(getGraphics());
    }

    Hmmz, didn't know a JLabel could be used to display an image... until now. Thanks for your advice camickr, this solutions gives a good result.
    import javax.swing.JFrame;
    import javax.swing.BoxLayout;
    public class FrmMain extends JFrame
       public FrmMain()
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
          setBounds(0,0,600,400);
       public static void main(String[] args)
          FrmMain formMain = new FrmMain();
          Thumbnail one = new Thumbnail(".\\test01.jpg", 10);
          Thumbnail two = new Thumbnail(".\\test02.jpg", 10);
          Thumbnail three = new Thumbnail(".\\test03.jpg", 10);
          Thumbnail four = new Thumbnail(".\\test04.gif", 10);
          formMain.getContentPane().add(one);
          formMain.getContentPane().add(two);
          formMain.getContentPane().add(three);
          formMain.getContentPane().add(four);
          formMain.setVisible(true);
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.ImageIcon;
    public class Thumbnail extends JLabel
       public Thumbnail(String fileName, int borderSpace)
          this.fileName = fileName;
          setOpaque(true);
          setBorder(BorderFactory.createEmptyBorder(borderSpace, borderSpace, borderSpace, borderSpace));
          thumbnail = getThumbnail();
          setIcon(new ImageIcon(thumbnail));
       private Image getThumbnail()
          int newHeight = 0;
          int newWidth = 0;
          int remain = 0;
          File file = new File(fileName);
          BufferedImage buffImage = null;
          BufferedImage result = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
          Image tempImg = null;
          Graphics2D g2d = (Graphics2D)result.getGraphics();
          g2d.setColor(Color.BLACK);
          g2d.fillRect(0,0,WIDTH,HEIGHT);
          if(file.exists())
             try
                buffImage = ImageIO.read(file);
             catch(Exception e)
                System.out.println(e);
                return null;
             if (buffImage.getHeight() > HEIGHT)
                remain = buffImage.getHeight() - HEIGHT;
                remain = (int)((remain / (double)(buffImage.getHeight())) * 100);
                newHeight = HEIGHT;
                newWidth = (int)(buffImage.getWidth() * ((100 - (double)remain) / 100));
             if (newWidth > WIDTH)
                remain = newWidth - WIDTH;
                remain = (int)((remain / (double)newWidth) * 100);
                newWidth = WIDTH;
                newHeight = (int)(newHeight * ((100 - (double)remain) / 100));
          tempImg = buffImage.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_SMOOTH);
          g2d.drawImage(tempImg, (WIDTH - tempImg.getWidth(null)) / 2, (WIDTH - tempImg.getHeight(null)) / 2, null); 
          return (Image)result;
       public static int WIDTH = 100;
       public static int HEIGHT = 100;
       private String fileName;
       public String getFileName()
          return fileName;
       public void setFileName(String fileName)
          this.fileName = fileName;
          thumbnail = getThumbnail();
          setIcon(new ImageIcon(thumbnail));
       private Image thumbnail;
    }

  • Image repainting problem!! plz HELP!!

    I'm facing a little problem with repaint. I have a moving ball on my JPanel (canvas). Ball (which is a circle) is leaving 2 lines behind it. I don't know why it happens, the code inside my paintComponent() method is as follows:
    public void paintComponent(Graphics comp)
           super.paintComponent(comp);          
           g = (Graphics2D)comp;          
           g.drawLine(0,250, 500,  500/2);      //draw horizontal line from north          
           g.drawLine(500/2, 0, 500/2, 500); //draw vertical line on the equator          
           g.setColor(Color.blue);          
           g.fillArc(width, height, ballSize, ballSize, 0, 360);
    }The above "paint" event has been written for JPanel class. On fillArc() line, only width and height are changes through a thread class. Actually, my ball is bouncing against the walls (edges) of Jframe. Bouncing is fine, but it is printing 2 lines just behind the ball (arc).
    Any expert commetns would be greatly appreciated.
    Raheel.

    Hi.
    I think you should clean up your background at the beginnig of paintComponent:
    public void paintComponent(Graphics comp) {     
      super.paintComponent(comp);
      g = (Graphics2D)comp;
      //comp cleaning
      g.setColor(Color.WHITE); //the color of your background
      comp.fillRect(0, 0, getWidth(), getHeight());
      //end of cleaning
      g.fillRect(0, 0, get
      g.drawLine(0,250, 500,  500/2); //draw horizontal line from north
      g.drawLine(500/2, 0, 500/2, 500); //draw vertical line on the equator    g.setColor(Color.blue);     
      g.fillArc(width, height, ballSize, ballSize, 0, 360);
    }Hope this help.

  • Applet repaint problem

    Hi
    I have problem with repainting. I add components to panel, then in action listener remove them and add a different component. After that the panel is empty, but when I resize the applet, the component appears.
    Do you have any ideas what's wrong?
    Here is the code:
    public class test extends JApplet{
         private Container aplet;                                   
              private JPanel
                   podspodnik = new JPanel(new BorderLayout());
              private JTextPane
                   wyswietl = new JTextPane();          
              private JButton
                   wywolaj = new JButton("Wywolaj"),
                   but = new JButton("Juppi!");
              public void init()
                   try
                        javax.swing.SwingUtilities.invokeAndWait(new Runnable()
                        public void run()
                             createAndShowGUI();
                   catch (Exception noGUI)
                        System.err.println("Nie udalo sie utworzyc interfejsu!!");
                        JOptionPane.showMessageDialog(null,
                                       "Nie udalo sie utworzyc interfejsu!!!",
                                       "Blad krytyczny okna",
                                       JOptionPane.ERROR_MESSAGE);
              private void createAndShowGUI(){
                   aplet = getContentPane();
                   aplet.setPreferredSize(new Dimension(300, 300));
                   wyswietl.setPreferredSize(new Dimension(200, 300));
                   wyswietl.setPreferredSize(new Dimension(130,20));
                   wywolaj.setPreferredSize(new Dimension(130, 20));
                   podspodnik.add(wyswietl, BorderLayout.NORTH);
                   podspodnik.add(wywolaj, BorderLayout.CENTER);
                   aplet.add(podspodnik);
                   addListeners();
                   aplet.setVisible(true);
                   aplet.repaint();
              private void addListeners(){
                   wywolaj.addActionListener(new ActionListener()
                                  public void actionPerformed(ActionEvent e)
                                       podspodnik.remove(wyswietl);
                                       podspodnik.remove(wywolaj);
                                       podspodnik.add(but, BorderLayout.CENTER);
                                       aplet.repaint();
    }

    Try to post this problem in the Java Applet Development forum instead.(
    http://forum.java.sun.com/forum.jspa?forumID=421).
    Applet != Servlet

  • Repaint(Rectangle ) problem

    Hi, anyone knows any problems calling repaint with a Rectangle parameter when the component doesn't fit in the window ( both width and height ).
    I'm trying to repaint an area delimited by a Rectangle, but when its bounds are outside of the window, width and height it doesnt repaint the area. Any idea ? thanks

    If you want to eliminate 'Flicker' in Java you have to override the update(Graphics g) method found in the java.awt.Container class.
    A call to repaint() calls update(Graphics g) first which by default clears the painting surface by painting with the background color (this causes flicker on a large area) after this there is a call to paint(Graphics g).
    There are two ways to proceed. Use 'clipping' if the area that is changing is quite small e.g. numbers on a digital clock or use 'double buffering' if the area is larger e.g. large animation.

Maybe you are looking for

  • How do I transfer money from a account to another account

    I forgot my password to my main account do I decided to use my moms account to redeem my gift card I then remembered my password and want to switch the money to my real account and not my moms please help

  • Ipod with Windows ME..new program??

    Hey would really love some help please! Bought my ipod about a month ago, didnt realise that ITunes needed Windows 2000 or XP. I have Windows ME and downloaded another program to put my songs on. This has now expired and am now looking for another on

  • Office 2007 compatability for OS X

    I have an iBook 900MHz, and I can't open up my Office 2007 files from my windows computer on my Office Mac Word. With office 2007, they have changed all the file extentions. (.doc becomes .docx, power point becomes .pptx) I have manually changed it t

  • [b]insert into...returning[/b] with Pro*COBOL

    Hi, I wrote a COBOL application to insert a row into an Oracle table. It works fine, but when I append the returning clause to return a trigger-generated value (or any other) I would always get an ORA-24343: user defined callback error no matter what

  • Dynamically adding attribute based on PL/SQL function

    I've been tasked with dynamically applying security to an XMLType input sample as a post XML generation process (on an 11g R2 DB) based on several parameters. The best way to describe it is with an example block of code, I need to write ApplySecurity