Simple repaint() method doubt

Hi Friends,
I have a simple program in which I need to print 2 strings at the same time.So,I pass the string and the location to the paint method,but the second repaint() method erases the first
string and only the second string is displayed.So,how can i make both the strings display at the same time.Here's a part of my code.
doPaint("String one",200,200);
validate();
doPaint("String two",200,250);
validate();
public void doPaint(String str,width x,height y){
                            this.x = x;
                            this.y = y;
            this.str=str;
           repaint();
public void paint(Graphics g){
                        super.paint(g);
        g.setColor(Color.BLUE);
        g.drawString(str,x,y);
     }Thanks

repaint()clears the component and fills it from the scratch, so when you call your function for the second time it clears first string and draws only the second.
I advise to use two variables if you want them painted together.
And override paintComponent() not paint()

Similar Messages

  • Calling repaint method from another class

    My question in a very simple form :
    how do I call repaint mathod from another class.
    e.g: Let's say class "A.java" is a JFrame .
    Class "B.java" is a JPanel which is added to the JFrame above.
    Class "C.java" is a JDialog containing some JButtons.
    How do I call the repaint method from the class "C.java".
    Thank you in advance!!

    My question in a very simple form :
    how do I call repaint mathod from another class.
    e.g: Let's say class "A.java" is a JFrame .
    Class "B.java" is a JPanel which is added to the JFrame above.
    Class "C.java" is a JDialog containing some JButtons.
    How do I call the repaint method from the class "C.java".
    Thank you in advance!!

  • Repaint() method is not working in MAC IE

    Hi All
    why repaint method is not working in MAC IE ? What i am doing is in one class which is inheriting Canvas class getting the keybord input then adding it to main applet.
    Please help me i am trying it for whole week and i couldn't find any solution. I didn't put my code but if anyone is willing to help me i can post it.
    Thanks in advancs
    Shan

    Hi
    Thanks for your reply. Actually i wrote simple applets and those are working well.
    So i did debug the code and i found that when i am running the following code in Apple MAC IE, nothing is happening in handleEvent method. Especially it is not going into the if statement (if (evt.id==401)). here i am checking for KEY_PRESS. I also tried with keyDown method but same problem in MAC IE.
    I am pasting the code that is giving me problem.
    import java.awt.*;
    import java.applet.*;
    public class testApplet extends Applet
    public void init()
    setLayout(new BorderLayout());
    editableArea = new EditableArea();
    editableArea.setBackground(Color.yellow);
    add("Center", editableArea);
    EditableArea editableArea;
    import java.awt.*;
    public class EditableArea extends Canvas
    String s = "";
    public boolean handleEvent(Event evt)
    if (evt.id==401)
    if(evt.key >= 32 && evt.key <= 255)
    char c = (char)evt.key;
    s = s + c;
    repaint();
    return super.handleEvent(evt);
    public void paint( Graphics g )
    g.setColor(Color.blue);
    g.drawString( s,5,15);
    --------------------------------------------------------------------

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

  • Repaint() method is not being called?

    Hi...experts
    I have appended the unicode characters to the StringBuffer .and i draw it on canvas.
    now i want to delete these unicode characters from last index of StringBuffer with the command "Clear" .
    i m using the following code for doing this....
    StringBuffer sb=new StringBuffer();
    sb.append('\u093E');
    sb.append('\u093F');
    sb.append('\u0940');
    sb.deleteCharAt(sb.length()-1);But the StringBuffer is as it is.
    please suggest me how repaint() method works.
    Edited by: RavindraDiwakar on Sep 25, 2008 7:46 AM

    {color:#ff0000}{size:20px}CROSS POSTED{size}{color}
    [http://forums.sun.com/thread.jspa?threadID=5334750]
    [http://forums.sun.com/thread.jspa?threadID=5334748]
    Cross posting is rude.
    db

  • Alternative for repaint() method

    Hello,
    I am using repaint() method to redraw the components in my screen. Is there any alternative method. In the code below, i will try to explain what i am trying to do.
    class Sample{
    JFrame frame = new JFrame();
    DrawPanel drawPanel = new DrawPanel();
    frame.getContentPane().add(drawPanel);
    callMethod();
    public void callMethod()
    frame.repaint(); //This will call paintComponent again, whether can i do it without repaint() [An alternative approach].
    //This is class is in a diff file
    class DrawPanel extends JPanel{
    public void paintComponent(graphics g)
    Graphics2D g2d = (Graphics2D) g;
    drawRec();
    public void drawRec()
    g2d.fillRect(x,y,100,203);
    Say on clicking a button, i want to draw rectangle with different sizes. How can i do it without calling repaint().
    Please help.
    Thank you.

    I don't get why you don't want to call repaint().
    I can see why you wouldn't want to repaint() the whole frame if only one of its widgets needs to update its appearance, but wishing to redraw a JComponent without going calling repaint() on at least this leaf widget is a way to get into trouble.
    That being said, there's paintImmediately(...) somewhere in the Javadoc, but its use should be limited to special cases.
    Say on clicking a button, i want to draw rectangle with different sizes.See this article for an example that does exactly that, and proposes two approaches, both of them using repaint() (it's a coincidence, the article is about two methods to do custom painting, it turns out that the example topic is drawing rectangles).
    The article meantions the Swing tutorial chapter on [custom painting|http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html] , which explains the Swing painting architecture, and why you shouldn't try to circumvent it unless you really know what you do.
    How can i do it without calling repaint().Again in general there's no reason to avoid repaint(), just invoke it on the appropriate DrawPanel instance, not on the whole frame.

  • My repaint() method flickers

    Hi, can someone help me enhance my GUI so that it won't flicker? I tried to use BufferStrategy but it still flickers. I used the code below to override the repaint method of the Canvas that I am trying to draw. Also, I'm not really sure if the repaint() method was the right method to override.
    public void repaint() {
              super.repaint();
              this.createBufferStrategy(2);
              BufferStrategy bufferStrategy = this.getBufferStrategy();
              Graphics g = bufferStrategy.getDrawGraphics();
              g.setColor(Color.BLACK);
                    //x and y are changed by a different Thread every 1 millisecond
              g.drawOval(x, y, 20, 20);
              g.dispose();
              bufferStrategy.show();
         }I also have another Thread that repaints my Canvas.
    public class Painter implements Runnable {
         private LandAreaCanvas area;
         public Painter(LandAreaCanvas area) {
              this.area = area;
         public void run() {
              while (true) {
                   area.repaint();
    }So in summary, my application has 3 Threads running
    1. Main class with main method that initializes all GUI components
    2. Painter class that repaints forever
    3. Calculator class that changes the value of x and y in the repaint method of the Canvas class.
    Thanks a lot!

    Actually you should do your custom painting by overriding paintComponent(Graphics). Which should not flicker since Swing uses double buffering by default.
    See [the tutorial|http://java.sun.com/docs/books/tutorial/uiswing/painting/].
    On edit looks like you might be using AWT, so above advice might not be relevant. [The linked article|http://java.sun.com/products/jfc/tsc/articles/painting/] in the tutorial still can be of help though.
    Edited by: WalterLaan on May 7, 2009 2:13 AM

  • JPanel repaint() method execution

    Hi,
    I vould like to know if there is a way to catch the end of repaint() method execution.
    Thank you in advance

    This is my scenario ...
    I am using an external tool ,for georeferencied images handling , to generate JPEG images and save them to disk.
    In order to generate an image I overlap n layers provided by this tool ... each time I add a layer I need to repaint the panel and then save the content to disk.
    The problem is that there is a race condition between repaint() and save() method.... in particular ... if I use larger images it takes a long time to repaint the panel and in this while it stores an incomplete image.

  • Component repaint() method changed?

    Did the Component repaint() method used to clear the Component pane as well as painting it again?
    I ask because I think my textbook is assuming that repaint() clears the pane and then paints again but when I implement the code that I've written, I see all previously painted objects.
    Thanks.

    The job of repaint is just to queue a request for the repainting of the object. It sounds like the problem is in your actual painting code. You also haven't said what framework you are using? AWT? Swing? SWT?
    In Swing, you typically override paintComponent like so:
    @Override protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         //do you painting here:
    }The call to super.paintComponent is what clears the component.
    In future, Swing questions should go tot the Swing forum: [http://forums.sun.com/forum.jspa?forumID=57]

  • Stuck with the paint and repaint methods

    I am supposed to create a JApplet with a button and a background color. When the button is clicked the first time a word is supposed to appear (I got that part), when the button is clicked the second time the word is supposed to appear again in a different color and in a different location on the Applet (I got that part).
    The problem is that the first name is supposed to disappear when the second word appears. So I know I have to repaint the screen when the button is clicked the second time and draw the first string in the same color as the background color to make it invisible.
    My problem is I am not sure how I can code to apply different settings each time the button is clicked. Can anyone help? Please let me know if my explanation sucks. I will try to explain better. However here is the code I have so far. I added a counter for the button just for testing purposes.
    I just need some hints on what to do and if there is a easier way than using that if statement please let me know. I probably make it harder than it is.
    Thanks in advance and Merry Christmas.
    import javax.swing.*;
       import java.awt.*;
       import java.awt.event.*;
        public class DisplayMyName extends JApplet
        implements ActionListener
          String myName = "DOG";
          String myName1 = "DOG";
          JButton moveButton = new JButton("Move It");
          Font smallFont = new Font("Arial", Font.BOLD, 12);
          Font largeFont = new Font("Lucida Sans", Font.ITALIC, 20);
          int numClicks = 0;
          JLabel label = new JLabel("Number of button clicks:" + numClicks);
           public void init()
             Container con = getContentPane();
             con.setBackground(Color.RED);
             con.setLayout( new FlowLayout() );
             con.add(moveButton);
             con.add(label);
             moveButton.addActionListener(this);
           public void paint(Graphics g)
             numClicks++;
             label.setText("Number of button clicks: " + numClicks);
             if (numClicks == 2)
             { g.setFont(smallFont);
                g.setColor(Color.BLUE);
                g.drawString(myName, 50, 100);
                   else
             if (numClicks == 3)
             { g.setFont(largeFont);
                g.setColor(Color.YELLOW);
                g.drawString(myName, 100, 200);
           public void actionPerformed(ActionEvent move)
             repaint();
       }

    You're putting your program logic in the paint method, something you should not do. For instance, try resizing your applet and see what effect that has on number of button clicks displayed. This is all a side effect of the logic being in the paint method.
    1) Don't override paint, override paintComponent.
    2) Don't draw/paint directly in the JApplet. Do this in a JPanel or JComponent, and then add this to the JApplet. In fact I'd add the button, the and the label to the JPanel and add the label to the JApplet's contentPane (which usually uses BorderLayout, so it should fill the applet).
    3) Logic needs to be outside of paint/paintComponent. the only code in the paintComponent should be the drawing/painting itself. The if statements can remain within the paintComponent method though.
    4) When calling repaint() make sure you do so on the JPanel rather than the applet itself.
    For instance where should numClicks++ go? Where should the code to change the label go? in the paint/paintComponent method? or in the button's actionlistener? which makes more sense?
    Edited by: Encephalopathic on Dec 24, 2008 9:37 AM

  • 11g Upgrade Method Doubt....

    Hi, DB Version: 11.1.0.6 O/S : Win XP Prof I am reading 11g docs.In the Upgrade guide, there are quite a number of ways listed for the upgrade.Please look here. The listed ways are
    (1)Database Upgrade Assistant (DBUA)
    (2)Manual upgrade using SQL scripts and utilities
    (3)Export and Import utilities
    (4)CREATE TABLE AS SQL statement
    For the last, 4th option,the details are these, Copies data from a database into a new Oracle Database 11g Release 1 (11.1) database. Data copying can copy a subset of the data, leaving the database unchanged. I am not able to understand how CTAS is a way to upgrade?How it can be an option for upgrade when we are just porint data from one database of 11g to another.The same method is given in 11g New Features Book from OU also.If anyone can throw any light over thismethod of upgrade than please do.
    Further,if you just click on Choose an upgrade method link, this method is not listed there. The only 3 which are listed are traditional ones, DBUA, Export/Import, Manual.
    Please clear this for me how this method is usable in the upgrade process?
    Regards
    Aman....
    Changed url tags.
    Message was edited by:
    Aman....

    Hans,
    Now go back and see if you can answer your
    question about 'method 4'
    I knew you would say the same to me that's why I
    mentioned couple of posts above that I am getting
    your point :-).<g>
    Please correct me now in my understanding.This method
    is actualy not an upgrade atleast not the one through
    which we will upgrade teh entire db.This is the one
    when we have two dbs of 11g and from 1 we are
    migrating few objects ( tables) with some
    restrictions on data to db B.Is this correct?You are correct. This is not an upgrade to an existing database.
    However, it can be considered an upgrade in the sense that the data source for an application is 'upgraded'. From the application's perspective, the data source used to be 10g and now it is 11g.
    Hans, my doubt since the origin of this question is
    with the title.This title doesn't seem to be
    appropriate. "Data Copying" which is the title in the
    previous relases docs sounds more appropriate where
    this CTAS is given as an example not as a sole way.Again, I agree. It is all a matter of [mis-]interpretation and perspective.

  • Simple abap query doubt

    Hello all,
       i have one simple doubt plz help.
    data:begin of itab1 occurs 0,
         psnfh like plfh-psnfh,
         end of itab1.
    select  psnfh  into table itab1
    from plfh
                     where plnty = 'N'
                     AND plnNR = group_number
                     AND plnfl  = W_PRT_ASSIGN-SEQUENCE_NO
                     and loekz ne 'X'
                    and plnkn = t_plnkn.
    this query is working fine.
            now i have 3 psnfh entires(0010 0020 0030) ..my requirement is that i have choose maximum of these that is 0030 and wanna add 0010 to it everytime.....and may be it will be better if i can save it in a variable.......
         plz help in this syntax......i know we can use MAX function but it will be better if u can give that exact 2-3 lines of code.

    Hi Abhijeet,
    Do you always want to add "0010" to the maximum value from that internal table?
    If yes, then you can follow the steps mentioned below.
    1. Declare temporary internal table and transfer al values from your main internal table to the temporary.
    ITAB_TEMP[] = ITAB[].
    2. Now Sort the temp table as follows.
    SORT ITAB_TEMP BY fieldname DESCENDING.
    3. Now if you READ this temp table with INDEX 1, you wil get the maximum value to which you can add the value.
    READ TABLE ITAB_TEMP INTO W_ITAB INDEX 1.
    IF SY-SUBRC EQ 0.
      V_MAX = W_ITAB-field + 0010.
    ENDIF.
    Best Regards,
    Ram.

  • Static method doubt

    Hi,
    I have a doubt using static methods:
    If 2 users call the same static method wih diferente parameters, the parameters of first user are changed?
    Thanks,
    rjc

    I already read that the only problem is if i acess
    and change static variables, in these cases i have
    to synchronize the method, is this true?Certainly, it is. If more than one thread are trying to change the same "thing" by using a method, you have to synchronize this method. Or you can synchronize this "thing", too.

  • Simple CLASSICAL REPORT doubt....!!!

    Hi Friends,
    I have a small doubt in reports.
    In a simple report out put How can we give the page footer as  1 of 10 ..in first page 2 of 10 in second page and ....so on for say 10 page out put.
    Thanks in advance.
    Regards,
    Ram.

    Hi Ram,
    Check this 'Rich' code.
    report zrich_0004
           line-size 80
           line-count 65
           no standard page heading.
    data: imara type table of mara with header line.
    selection-screen begin of block b1 with frame title text-001 .
    parameters: p_check type c.
    selection-screen end of block b1.
    start-of-selection.
      perform get_data.
      perform write_report.
    top-of-page.
      perform top_of_page.
    FORM GET_DATA
    form get_data.
      select * into corresponding fields of table imara
            from mara up to 300 rows.
    endform.
    FORM WRITE_REPORT
    form write_report.
      data: xpage(4) type c.
      loop at imara.
        write:/ imara-matnr.
      endloop.
      write sy-pagno to xpage left-justified.
      do sy-pagno times.
        read line 1 of page sy-index.
        replace '****' with xpage into sy-lisel.
        modify current line.
      enddo.
    endform.
    Form  top_of_page
    form top_of_page.
      write:/32 'Test Program',
            at 62 'Page:', at 67 sy-pagno, 'of', '****'.
    endform.
    Thanks,
    Vinay

  • Invoking the paint repaint methods in Java2D

    Hi,
    This is the case:
    I have used the paint method to a JPanel like this:
    public void paint (Graphics g){
    Graphics2D g2 = (Graphics2D) g;
    g2.setPaint(gradientColor);
    g2.fill(rect);
    g2.setPaint(Color.white);
    g2.drawString( "My label");
    Now once the JPanel been painted, after a while,i want to change the
    context of g2.drawString("new label") with a new label, but i want to keep the background painted as before. how do i invoke/use the repaint
    or another method to accomplish that? Please help.
    /E

    allredy solved, thanks any way.

Maybe you are looking for