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!!

Similar Messages

  • Calling a method from another class... that requires variables?

    I'm calling a method from another class to change the date (its a date object) in another class.
    I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
    My code is:
    public int changeDate()
         cycleDate.setDate();
    }I'm guessing I need to pass 3 parameters (day, month, year), but I'm not sure how! I have tried, but then I get errors such as ')' expected?
    Any ideas! :D

    f1d wrote:
    I'm calling a method from another class to change the date (its a date object) in another class.
    I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
    My code is:
    public int changeDate()
    cycleDate.setDate();
    }I'm guessing I need to pass 3 parameters (day, month, year), seems that way from the error you posted
    but I'm not sure how!
    setDate(16, 6, 2008);
    I have tried, but then I get errors such as ')' expected?
    Any ideas! :Dyou need to post your code if you're getting specific errors like that.
    but typically ')' expected means just that, you have too many or not enough parenthesis (or in the wrong place, etc.)
    i.e. syntax error

  • Help on Calling a method from another class

    how can i call a method from another class.
    Class A has 3 methods
    i just want to call only one of these 3 methods into my another class.
    How can I do that.

    When i am trying this
    A a=new A;
    Its calling all the methods from class A. I just want
    to call a specfic method.How can it be done?When i am trying this
    A a=new A();
    Its calling all the methods from class A. I just want to call a specfic method.How can it be done?

  • How do you call a method from  another class without extending as a parent?

    How do you call a method from another class without extending it as a parent? Is this possible?

    Why don't you just create an instance of the class?
    Car c = new Car();
    c.drive("fast");The drive method is in the car class, but as long as the method is public, you can use it anywhere.
    Is that what you were asking or am I totally misunderstanding your question?
    Jen

  • How to call a method from another class

    I have a problem were i have to call a method from another class. What is the command line that i have to use. Thanks.

    Here's one I wipped up in 10 minutes... Cool!
    package forums;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import krc.utilz.io.Filez;
    import java.io.FileNotFoundException;
    class FileDisplayer extends JFrame
      private static final long serialVersionUID = 0L;
      FileDisplayer(String filename) {
        super(filename);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(600, 800);
        JTextArea text = new JTextArea();
        try {
          text.setText(Filez.read(filename));
        } catch (FileNotFoundException e) {
          text.setText(e.toString());
        this.add(text);
      public static void main(String args[]) {
        final String filename = (args.length>0 ? args[0] : "C:/Java/home/src/forums/FileDisplayer.java");
        try {
          java.awt.EventQueue.invokeLater(
            new Runnable() {
              public void run() {
                new FileDisplayer(filename).setVisible(true);
        } catch (Exception e) {
          e.printStackTrace();
    Filez.read
       * reads the given file into one big string
       * @param String filename - the name of the file to read
       * @return the contents filename
      public static String read(String filename) throws FileNotFoundException {
        return Filez.read(new FileReader(filename));
       * Reads the contents of the given reader into one big string, and closes the reader.
       * @param java.io.Reader reader - a subclass of Reader to read from.
       * @return the whole contents of the given reader.
      public static String read(Reader in) {
        try {
          StringBuffer out = new StringBuffer();
          try {
            char[] bfr = new char[BFRSIZE];
            int n = 0;
            while( (n=in.read(bfr,0,BFRSIZE)) > 0 ) {
              out.append(bfr,0,n);
          } finally {
            if(in!=null)in.close();
          return out.toString();
        } catch (IOException e) {
          throw new RuntimeIOException(e.getMessage(), e);
      }Edited by: corlettk on Dec 16, 2007 1:01 PM - dang [code [/tags][                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Can't add list element when calling a method from another class

    I am trying to call a method in another class, which contains code listmodel.addElement("text"); to add an element into a list component made in that class.
    I've put in System.out.println("passed"); in the method just to make sure if the method was being called properly and it displays normally.
    I can change variables in the other class by calling the method with no problem. The only thing I can't do is get listmodel.addElement("text"); to add a new element in the list component by doing it this way.
    I've called that method within it's class and it added the element with no problem. Does Java have limitations about what kind of code it can run from other classes? And if that's the case I'd really like to know just why.

    There were no errors, just the element doesnt get added to the list by doing it this way
    class showpanel extends JPanel implements ActionListener, MouseMotionListener {
           framepanel fp = new framepanel();
           --omitted--
         public void actionPerformed(ActionEvent e){
                  if(e.getSource() == button1){
                       fp.addLayer();
    /*is in a different class file*/
    class framepanel extends JPanel implements ActionListener{
            --omitted--
         public void addLayer(){
              listmodel.addElement("Layer"+numLayer);
              numLayer++;
    }

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

  • ABAP Objects : calling one method from another class

    Hi,
    Can you please tell me how to call method from one class or interfce to another class.The scenario is
    I have one class CL_WORKFLOW_TASK, this class have interface IF_WORKFLOW_TASK & this interface have method IF_WORKFLOW_TASK~CLOSE. Now my requirement is ,
    There is another class CL_WORKFLOW_CHAIN ,this class have interface IF_WORKFLOW_CHAIN & this interface have method IF_WORKFLOW_CHAINCLOSE_ALL_PREDECESSORS. Now i have to write my code in this method but i have to use IF_WORKFLOW_TASKCLOSE method for closing the task.
    Can you please give me the code for the above .
    Please waiting for reply.

    Hi,
    You can use the concept of INHERITANCE  in this scenario.By using this concept, you can call all the public and protected  methods of class CL_WORKFLOW_TASK  in the required calss CL_WORKFLOW_CHAIN as per your requirement.
    Go through the  Introdctory(INHERITANCE) programming from this SAPHELP link.
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    I hope, it will help in you inresolving your problem.
    by
    Prasad GVK.

  • Calling a method from another class or accessing a component from another

    Hi all
    im trying to make a find/replace dialog box
    my main application form has a jtextpane and when i open up the find and replace dialog box it has two textboxes (find and replace)
    now i have the code to do the finding on my jtextpane but how do i call that code to do the find method?
    I have tried having the code in my main application class but then how do i call that method from my dialog box class?
    ive also tried having the code in my dialog box class, but then how to i tell it to work on my jtextpane which is in my main ap class?

    well if someone had been nice enough to provide me
    with a tutorial i wouldnt have gotten into this
    muddle, no need to be rude is there!I'm not rude. And you also wouldn't have gotten into the muddle if you searched yourself. This site provides many very good tutorials about all kinds of stuff.
    http://java.sun.com/docs/books/tutorial/java/javaOO/classes.htmlAmong other things, it mentions that "static" defines everything that belongs to a class, as opposed to an object.

  • Simple enough but... calling a method from another class

    Hi all,
    I know it's simple enough, although I can't see where I'm going wrong for some reason. Basically I've got a class which extends JPanel but when I try to call one of its methods from my main class I get an error. The relevant code (I hope) is:
    Main.java
    import java.awt.BorderLayout;
    import javax.swing.UIManager;
    public class Main extends JFrame implements ActionListener {
         JFrame frame;
         public static JPanel statusBar;
         public Main() {
              // Add a status bar
              statusBar = new StatusBar();
              mainPanel.add( statusBar, BorderLayout.SOUTH );
              setContentPane( mainPanel );
         public static void setStatusBarText( String s ) {
              statusBar.setStatusText("Test");
    StatusBar.java
    import java.awt.Color;
    import javax.swing.SwingConstants;
    public class StatusBar extends JPanel {
         private int barWidth;
         private static JLabel status;
         public StatusBar() {
              super();
              //barWidth = Main.getProgramWidth();
              //setPreferredSize( new Dimension(barWidth,22) );
              setLayout( new FlowLayout( FlowLayout.LEADING ) );
              setBorder( BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(160,160,160) ) );
              status = new JLabel("Test", SwingConstants.LEFT);
              //status.setVerticalAlignment( SwingConstants.CENTER );
              add( status );
         protected void setStatusText( String s ) {
              status.setText( s );
              revalidate();
    }The "statusBar.setStatusText("Test");" call in the main class file doesn't work and I get the error:
    >
    cannot find symbol
    symbol : method setStatusText(java.lang.String)
    location: class javax.swing.JPanel
    statusBar.setStatusText("Test");
    >
    Any ideas what I'm doing wrong? I created an instance of the StatusBar class called statusBar, then I use this to call the setStatusText() method (via statusBar.setStatusText()) which I thought was all correct, then it doesn't work? Even if there's an easier way to do what I want to achieve (i.e. update a JLabel from the 'central' main class file instead of setting the JLabel to static and having every class call it directly), I'd appreciate knowing where I'm going wrong here nonetheless.
    Many thanks,
    Tristan

         public static JPanel statusBar;
         public static void setStatusBarText( String s ) {
              statusBar.setStatusText("Test");
    >
    cannot find symbol
    symbol : method setStatusText(java.lang.String)
    location: class javax.swing.JPanel
    statusBar.setStatusText("Test");
    >The type of variable statusBar is JPanel. That's all the compiler takes into account. It's irrelevant that at some point in the program the type of the object pointed to by this variable is a subclass of JPanel (because at another point it might be an instance of another subclass, or of JPanel itself.

  • How call a method from another class

    i make three class.class A,class B and class C.
    class A have One button.
    Class B have a action listener of that button.
    class c have a metod like
    public void test(){     }
    how can i call a method in class b from class c;
    is it necessary to pass the class a or b through the constructor of class c or another way to call the method.

    public class Foo
        public static void main(String[] args)
            Bar.staticFn();
            Bar b = new Bar();
            b.memberFn();
    class Bar
        public void memberFn()
            System.out.println("memberFn");
        public static void staticFn()
            System.out.println("staticFn");
      }

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • Calling a method from another class while in a seperate class

    Hello
    I am currently TRYING to proramme a simple alarm clock program, The way it has had to be set out is that there are two classes one is called ClockDisplay which is just the clock and the one i have had to create is called AlarmDisplay
    I am trying to write code so that when the String alarmdisplayString(this is located in the alarm class which i am typing this code) is the same as String displayString the system will print out something like "Beep wake up" So far i have this code but i cannot figue out what to put to reference the method from the ClockDisplay class while codingi n the AlarmDisplay class
    if(alarmdisplayString = DONT KNOW WHAT TO PUT HERE) {
    system.out.println ("DING WAKE UP");
    Any help would be great!
    Thanks

    That makes sense i have put in this code
    private void Alarmtone()
    ClockDisplay displayString = new ClockDisplay();
    if (alarmdisplayString == ClockDisplay.displayString){
    system.out.println ("DING WAKE UP");
    displayString is the method in the ClockDisplay Class
    alarmdisplayString is the method in the AlarmDisplay class
    I get the error message "non-static variable displayString cannot be referenced from a static context
    Thanks for the help so far :D

  • Calling a method from another class. Please Help!!

    Here is my full program. Like I said in my last post. I am having trouble calling the baseMakesError1 method. This method is called in the subcallsbase1 method. Also, it would be of great help if you could look for any other errors with with my program. Thank you so much. I really appreciate it.
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    public class ThomasR11
    String sy;
    public static void main(String[] args)
    System.out.println("(main): Ryan Thomas, file ThomasR11: Exceptions");
    SubRT obj3;
    SubRT obj4;
    String sX;
    String x;
    String s;
    String sY;
    try
    ThomasR11 obj1=new ThomasR11();
    catch(NullPointerException NPE)
    System.err.println("Null Pointer Exception");
    ThomasR11 obj2=new ThomasR11("Hello");
    System.out.println("This is the last statement in main");
    public ThomasR11()
    SubRT obj3= new SubRT();
    obj3.subCallsBase1();
    public ThomasR11(String sY)
    throws FileNotFoundException
    SubRT obj4= new SubRT();
    obj4.subError2();
    obj4.subError3(sY);
    private static class BaseRT
    public BaseRT()
    System.out.println("In BaseRT constructor= " + this);
    public void baseMakesError1(int value0)
    System.out.println("In BaseRT constructor, about to throw exception");
    if (value0==0)
    throw new NullPointerException("NullPointerException");
    private class SubRT extends BaseRT
    SubRT subNull;
    public SubRT()
    System.out.println("In SubRT constructor before call to aMakes an error= " +
    "\n SubRT constructor= " + this);
    public void subCallsBase1()
    try
    System.out.println("Calling the method baseMakeserror1");
    baseMakesError1(subNull);<---------------------This is where I am getting the error it says "ThomasR11.java [79:1] baseMakesError1(int) in ThomasR11.BaseRT cannot be applied to (ThomasR11.SubRT)"
    catch(NumberFormatException NFE)
    System.err.println("\nNumber Format Exception");
    catch (NullPointerException NPE)
    System.err.println(NPE.getMessage() + "\n");
    System.err.println(NPE.toString() + "\n");
    throw NPE;
    public void subError2()
    try
    BufferedReader in = new BufferedReader( new FileReader( "c:/xx/xx.xx" ) );
    catch(NullPointerException NPE)
    System.out.println("Null Pointer Exception");
    catch (FileNotFoundException FNFE)
    System.err.println("FileNotFoundException");
    public void subError3( String sX)
    try
    System.out.println("Hello");
    System.out.println (sX.length());
    catch(NullPointerException NPE)
    System.err.println("Null Pointer Exception");

    "ThomasR11.java [79:1] baseMakesError1(int) in ThomasR11.BaseRT cannot be applied to (ThomasR11.SubRT)"
    ...this error is telling out that you wrote baseMakesError1 to accept an "int" as an argument, and you are trying to pass it an instance of the ThomasR11.SubRT class. You either have to change baseMakesError1 to accept a SubRT as an argument, or change your call to pass an integer.

  • Re: problem calling a method from another class

    This line here:
    app.computeDiscount(ord,tentativeBill);... You are not capturing the returned amount.
    double d = app.computeDiscount(ord,tentativeBill);

    what kind of problem r u facing?
    plz highlight the code where u r facing the problem

Maybe you are looking for

  • Problems when downloading a file using jspsmartupload

    i am using jakarta tomcat 4.03 in linux .... to upload the file its ok .... im using this code here : String path = application.getRealPath("/upload"); try { count = mySmartUpload.save(path); it works fine ...... but when i try to download ..... putz

  • Text cannot be displayed right

    Helly Guys, I am a new mac user and I have transfered all my mails from MS Outlook 2007 for windwos to Mac Mail program successfully. However, some of the messages appeared as shown: "Ð&#151;дÑ&#128;авейÑ&#130;е, Ð&#152;зпÑ&#128;аÑ&#137;ам

  • Printer all in one hp 7210xi desk jet

    How to print wireless.

  • Planned Price (Production order) /Activity price

    Hello friends When i m creating Production order(sta- 81 Planned order to Production order)  Planned price is not showing after saving / release of order also activity price is not showing. Check the OPL8 setting , For activity Price is mentioned in

  • WLC 8500 SSO HA not working

    Hi there, We're running AireOS 8.0 in a  WLC 8500 series and we're getting problems trying to enable HA scenario. These are the scenarios we have tested: management interface tagged + switchport trunk tagged + HA tagged + switchport trunk tagged = SS