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

Similar Messages

  • Use a method from another class in another package?

    How can I use a method from another class in another package?

    WhiteJ wrote:
    What do you mean by "new keyword?" You posted this previously:
    I tried that, it seems to not be working. I want to use the constructor from the other class. I imported it, using this piece of code:
    import components.FileChooser;
    components.FileChoser();
    Typically if I am going to call a constructor on a class called Fubar, I'd use new to create a new object:
    Fubar myFubar = new Fubar();Incidently, is it a simple typo in your post or are you trying to use a FileChoser object when it should be FileChooser?

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

  • 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

  • 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][                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Calling a TextFields get method from another class as a String

    This is my first post so be kind....
    I'm trying to create a login screen with Java Studio Creator. The Login.jsp has a Text Field for both the username and password. JSC automatically created get and set methods for these.
    public class Login extends AbstractPageBean
    private TextField usernameTF = new TextField();
    public TextField getUsernameTF() {
    return usernameTF;
    public void setUsernameTF(TextField tf) {
    this.usernameTF = tf;
    private PasswordField passwordTF = new PasswordField();
    public PasswordField getPasswordTF() {
    return passwordTF;
    public void setPasswordTF(PasswordField pf) {
    this.passwordTF = pf;
    My problem is in trying to call these methods from another class and return the value as a string.
    Any help on this matter would be greatly appreciated.

    the method returns the textfield, so you just need to get its text
    import java.awt.*;
    class Testing
      public Testing()
        Login login = new Login();
        System.out.println(login.getUsernameTF().getText());//<----
      public static void main(String[] args){new Testing();}
    class Login
    private TextField usernameTF = new TextField("Joe Blow");
    public TextField getUsernameTF() {
        return usernameTF;
    }

  • Is it possible to call methods from another class from within an abstract c

    Is it possible to call methods from another class from within an abstract class ?

    I found an example in teh JDK 131 JFC that may help you. I t is using swing interface and JTable
    If you can not use Swing, then you may want to do digging or try out with the idea presented here in example 3
    Notice that one should refine the abstract table model and you may want to create a method for something like
    public Object getValuesAtRow(int row) { return data[row;}
    to give the desired row and leave the method for
    getValuesAt alone for getting valued of particaular row and column.
    So Once you got the seelcted row index, idxSelctd, from your table
    you can get the row or set the row in your table model
    public TableExample3() {
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    // Take the dummy data from SwingSet.
    final String[] names = {"First Name", "Last Name", "Favorite Color",
    "Favorite Number", "Vegetarian"};
    final Object[][] data = {
         {"Mark", "Andrews", "Red", new Integer(2), new Boolean(true)},
         {"Tom", "Ball", "Blue", new Integer(99), new Boolean(false)},
         {"Alan", "Chung", "Green", new Integer(838), new Boolean(false)},
         {"Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true)},
         {"Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false)},
         {"Brian", "Gerhold", "Green", new Integer(0), new Boolean(false)},
         {"James", "Gosling", "Pink", new Integer(21), new Boolean(false)},
         {"David", "Karlton", "Red", new Integer(1), new Boolean(false)},
         {"Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false)},
         {"Peter", "Korn", "Purple", new Integer(12), new Boolean(false)},
         {"Phil", "Milne", "Purple", new Integer(3), new Boolean(false)},
         {"Dave", "Moore", "Green", new Integer(88), new Boolean(false)},
         {"Hans", "Muller", "Maroon", new Integer(5), new Boolean(false)},
         {"Rick", "Levenson", "Blue", new Integer(2), new Boolean(false)},
         {"Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false)},
         {"Chester", "Rose", "Black", new Integer(0), new Boolean(false)},
         {"Ray", "Ryan", "Gray", new Integer(77), new Boolean(false)},
         {"Georges", "Saab", "Red", new Integer(4), new Boolean(false)},
         {"Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false)},
         {"Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false)},
         {"Arnaud", "Weber", "Green", new Integer(44), new Boolean(false)}
    // Create a model of the data.
    TableModel dataModel = new AbstractTableModel() {
    // These methods always need to be implemented.
    public int getColumnCount() { return names.length; }
    public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {return data[row][col];}
    // The default implementations of these methods in
    // AbstractTableModel would work, but we can refine them.
    public String getColumnName(int column) {return names[column];}
    public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
    public boolean isCellEditable(int row, int col) {return (col==4);}
    public void setValueAt(Object aValue, int row, int column) {
    data[row][column] = aValue;
    };

  • 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

  • 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?

  • Running a main Method from another class??

    Hi,
    I am trying to run a main method from another class, eg the main method is in Class1 and i am trying to run it from class2.
    So I have
    class1 c1 = new class1();
    c1.main();and I get the following compilation error:
    clas2.java:42: main(java.lang.String[]) in class1 cannot be applied to () c1.main();
    any ideas on how to do this correctly
    thanks in advance,
    Donal

    Hi thanks for the replies,
    tried just passing a string earlier and that just gave errors too, I should have been more specific and pass a string array.
    Its working now thanks again.
    Donal

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

  • 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 results of a method from another class

    Very very new to Java, so apologies for the lack of basic knowledge. I am making a programme with 3 classes. One class gathers details about a module. Another about the results of this module (which requires some of the information inputted for the first class). For some reason I cannot find how to use results created in the first class in this second class. How do you call the results of a method from one class in another class?
    Thanks.

    Thank you.
    I am given the following information:
    '_ModuleRecord_
    This class is used to record information about a module taken by a single student. It has a constructor that takes three parameters:
    a Module,
    an int representing the examination mark achieved by a student, and
    an int representing the coursework mark achieved by a student.
    The class has another constructor that takes a single Module parameter.'
    and the code looks like this:
    public class ModuleRecord
      public ModuleRecord(Module m, int eMark, int cMark)
      public ModuleRecord(Module m)
      } I am a bit confused by the whole thing to be honest. I assume that the Module is referring to the other class, but how do I forge the link between them here?

  • Calling a class's method from another class

    Hi, i would like to know if it's possible to call a Class's method and get it's return from another Class. This first Class doesn't extend the second. I've got a Choice on this first class and depending on what is selected, i want to draw a image on the second class witch is a Panel extended. I put the control "if" on the paint() method of the second class witch is called from the first by the repaint() (first_class.repaint()) on itemStateChanged(). Thankx 4 your help. I'm stuck with this.This program is for my postgraduation final project and i'm very late....

    import java.awt.*;
    import java.sql.*;
    * This type was generated by a SmartGuide.
    class Test extends Frame {
         private java.awt.Panel ivjComboPane = null;
         private java.awt.Panel ivjContentsPane = null;
         IvjEventHandler ivjEventHandler = new IvjEventHandler();
         private Combobox ivjCombobox1 = null;
    class IvjEventHandler implements java.awt.event.WindowListener {
              public void windowActivated(java.awt.event.WindowEvent e) {};
              public void windowClosed(java.awt.event.WindowEvent e) {};
              public void windowClosing(java.awt.event.WindowEvent e) {
                   if (e.getSource() == Test.this)
                        connEtoC1(e);
              public void windowDeactivated(java.awt.event.WindowEvent e) {};
              public void windowDeiconified(java.awt.event.WindowEvent e) {};
              public void windowIconified(java.awt.event.WindowEvent e) {};
              public void windowOpened(java.awt.event.WindowEvent e) {};
         private Panel ivjPanel1 = null;
    * Combo constructor comment.
    public Test() {
         super();
         initialize();
    * Combo constructor comment.
    * @param title java.lang.String
    public Test(String title) {
         super(title);
    * Insert the method's description here.
    * Creation date: (11/16/2001 7:48:51 PM)
    * @param s java.lang.String
    public void conexao(String s) {
         try {
              Class.forName("oracle.jdbc.driver.OracleDriver");
              String url = "jdbc:oracle:thin:system/[email protected]:1521:puc";
              Connection db = DriverManager.getConnection(url);
              //String sql_str = "SELECT * FROM referencia";
              Statement sq_stmt = db.createStatement();
              ResultSet rs = sq_stmt.executeQuery(s);
              ivjCombobox1.addItem("");
              while (rs.next()) {
                   String dt = rs.getString(1);
                   ivjCombobox1.addItem(dt);
              db.close();
         } catch (SQLException e) {
              System.out.println("Erro sql" + e);
         } catch (ClassNotFoundException cnf) {
    * connEtoC1: (Combo.window.windowClosing(java.awt.event.WindowEvent) --> Combo.dispose()V)
    * @param arg1 java.awt.event.WindowEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.WindowEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.dispose();
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the Combobox1 property value.
    * @return Combobox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Combobox getCombobox1() {
         if (ivjCombobox1 == null) {
              try {
                   ivjCombobox1 = new Combobox();
                   ivjCombobox1.setName("Combobox1");
                   ivjCombobox1.setLocation(30, 30);
                   // user code begin {1}
                   this.conexao("select * from referencia");
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjCombobox1;
    * Return the ComboPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getComboPane() {
         if (ivjComboPane == null) {
              try {
                   ivjComboPane = new java.awt.Panel();
                   ivjComboPane.setName("ComboPane");
                   ivjComboPane.setLayout(null);
                   getComboPane().add(getCombobox1(), getCombobox1().getName());
                   getComboPane().add(getPanel1(), getPanel1().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjComboPane;
    * Return the ContentsPane property value.
    * @return java.awt.Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private java.awt.Panel getContentsPane() {
         if (ivjContentsPane == null) {
              try {
                   ivjContentsPane = new java.awt.Panel();
                   ivjContentsPane.setName("ContentsPane");
                   ivjContentsPane.setLayout(new java.awt.BorderLayout());
                   getContentsPane().add(getComboPane(), "Center");
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjContentsPane;
    * Return the Panel1 property value.
    * @return Panel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private Panel getPanel1() {
         if (ivjPanel1 == null) {
              try {
                   ivjPanel1 = new Panel();
                   ivjPanel1.setName("Panel1");
                   ivjPanel1.setBackground(java.awt.SystemColor.scrollbar);
                   ivjPanel1.setBounds(24, 118, 244, 154);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjPanel1;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         this.addWindowListener(ivjEventHandler);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combo");
              setLayout(new java.awt.BorderLayout());
              setSize(460, 300);
              setTitle("Combo");
              add(getContentsPane(), "Center");
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:02:58 PM)
    * @return java.lang.String
    public String readCombo() {
         String dado = ivjCombobox1.getSelectedItem();
         return dado;
    * Starts the application.
    * @param args an array of command-line arguments
    public static void main(java.lang.String[] args) {
         try {
              /* Create the frame */
              Test aTest = new Test();
              /* Add a windowListener for the windowClosedEvent */
              aTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosed(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Test");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 1:59:15 PM)
    * @author:
    class Combobox extends java.awt.Choice {
         public java.lang.String dado;
    * Combobox constructor comment.
    public Combobox() {
         super();
         initialize();
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Combobox");
              setSize(133, 23);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Combobox aCombobox;
              aCombobox = new Combobox();
              frame.add("Center", aCombobox);
              frame.setSize(aCombobox.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of Combobox");
              exception.printStackTrace(System.out);
    * Insert the type's description here.
    * Creation date: (11/17/2001 2:16:11 PM)
    * @author:
    class Panel extends java.awt.Panel {
    * Panel constructor comment.
    public Panel() {
         super();
         initialize();
    * Panel constructor comment.
    * @param layout java.awt.LayoutManager
    public Panel(java.awt.LayoutManager layout) {
         super(layout);
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("Panel");
              setLayout(null);
              setSize(260, 127);
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              java.awt.Frame frame = new java.awt.Frame();
              Panel aPanel;
              aPanel = new Panel();
              frame.add("Center", aPanel);
              frame.setSize(aPanel.getSize());
              frame.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              frame.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of java.awt.Panel");
              exception.printStackTrace(System.out);
    * Insert the method's description here.
    * Creation date: (11/17/2001 2:18:36 PM)
    public void paint(Graphics g) {
    /* Here's the error:
    C:\Test.java:389: non-static method readCombo() cannot be referenced from a static context
         System.out.println(Test.lerCombo());*/
         System.out.println(Test.readCombo());

Maybe you are looking for

  • Not Able To View Data in Web Service Model

    Hi ,    I m trying to view a table using web service model.    When i write the same code for binding it to context , i m able to view its data.    But not so while using Web Service Model(not adaptive web service model).    The code is:           Re

  • Can I use a 45 Magsafe charger for a Early 2011 i7 MBP regularly?

    Hello, A few weeks ago the 60w charger that came with my MBP started to fail and ended up shutting the mac down unexpectedly and preventing it to boot. Therefore, I had to take it to a tech to reinstall OS with all the inconveniences this caused me.

  • DVD Sony camcorder, ts video files

    I am trying to import the video files from a sony dvd camcorder into final cut. I imported the vob file, but it only imports a few seconds of the clip. How do I convert these files to be compatible with QT and final cut so I can edit?! thank you all

  • In iTunes, it shows that there are 6 apps to be updated, but afaik that's wrong.

    This started happening a few months ago and I have ignored it and just gone about updating my apps more or less weekly, but it just went from 5 updates available to 6 -- I don't know why = is there any way to clear this out or figure it

  • Apex 2.1 (XE) Master/Detail Page Question Regarding Prev/Next Buttons

    When creating a page of type master/detail the master form is auto-populated with two buttons that allow the user to navigate to the previous or next record. These buttons are implemented as submit buttons, which cause the session variables to be upd