Calling methods from other classes

I have a bunch of little java files in a folder, do I need to make a package in order to access all the methods in all the classes, or can I just make an instance of any of the methods because all the classes are in the same folder?

HI,
If your methods have a "public" modifier (and the class does too) then you can instantiate your classes as objects from that (so-called) "default" package in any other class or object in any other package and then call the methods on those instantiated objects as you please.
If that sounds confusing... I'd seriously try the excellent tutorials at this site, especially "the java tutorial".
/k1

Similar Messages

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

  • Calling method from another class problem

    hi,
    i am having problem with my code. When i call the method from the other class, it does not function correctly?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Dice extends JComponent
        private static final int SPOT_DIAM = 9; 
        private int faceValue;   
        public Dice()
            setPreferredSize(new Dimension(60,60));
            roll(); 
        public int roll()
            int val = (int)(6*Math.random() + 1);  
            setValue(val);
            return val;
        public int getValue()
            return faceValue;
        public void setValue(int spots)
            faceValue = spots;
            repaint();   
        @Override public void paintComponent(Graphics g) {
            int w = getWidth(); 
            int h = getHeight();
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.WHITE);
            g2.fillRect(0, 0, w, h);
            g2.setColor(Color.BLACK);
            g2.drawRect(0, 0, w-1, h-1); 
            switch (faceValue)
                case 1:
                    drawSpot(g2, w/2, h/2);
                    break;
                case 3:
                    drawSpot(g2, w/2, h/2);
                case 2:
                    drawSpot(g2, w/4, h/4);
                    drawSpot(g2, 3*w/4, 3*h/4);
                    break;
                case 5:
                    drawSpot(g2, w/2, h/2);
                case 4:
                    drawSpot(g2, w/4, h/4);
                    drawSpot(g2, 3*w/4, 3*h/4);
                    drawSpot(g2, 3*w/4, h/4);
                    drawSpot(g2, w/4, 3*h/4);
                    break;
                case 6:
                    drawSpot(g2, w/4, h/4);
                    drawSpot(g2, 3*w/4, 3*h/4);
                    drawSpot(g2, 3*w/4, h/4);
                    drawSpot(g2, w/4, 3*h/4);
                    drawSpot(g2, w/4, h/2);
                    drawSpot(g2, 3*w/4, h/2);
                    break;
        private void drawSpot(Graphics2D g2, int x, int y)
            g2.fillOval(x-SPOT_DIAM/2, y-SPOT_DIAM/2, SPOT_DIAM, SPOT_DIAM);
    }in another class A (the main class where i run everything) i created a new instance of dice and added it onto a JPanel.Also a JButton is created called roll, which i added a actionListener.........rollButton.addActionListener(B); (B is instance of class B)
    In Class B in implements actionlistener and when the roll button is clicked it should call "roll()" from Dice class
    Dice d = new Dice();
    d.roll();
    it works but it does not repaint the graphics for the dice? the roll method will get a random number but then it will call the method to repaint()???
    Edited by: AceOfSpades on Mar 5, 2008 2:41 PM
    Edited by: AceOfSpades on Mar 5, 2008 2:42 PM

    One way:
    class Flintstone
        private String name;
        public Flintstone(String name)
            this.name = name;
        public String toString()
            return name;
        public static void useFlintstoneWithReference(Flintstone fu2)
            System.out.println(fu2);
        public static void useFlintstoneWithOutReference()
            Flintstone barney = new Flintstone("Barney");
            System.out.println(barney);
        public static void main(String[] args)
            Flintstone fred = new Flintstone("Fred");
            useFlintstoneWithReference(fred); // fred's the reference I"m passing to the method
            useFlintstoneWithOutReference();
    {code}
    can also be done with action listener
    {code}    private class MyActionListener implements ActionListener
            private Flintstone flintstone;
            public MyActionListener(Flintstone flintstone)
                this.flintstone = flintstone;
            public void actionPerformed(ActionEvent arg0)
                //do whatever using flinstone
                System.out.println(flintstone);
        }{code}
    Edited by: Encephalopathic on Mar 5, 2008 3:06 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Calling repaint from other Class file.

    Hi,
    First of all i am pretty new to Java so I hope you understand what I am trying to explain..
    I am trying to create an applet which draws some polygons on the screen. For the drawing of these polygons I have created another class which is located in another package but the same project. I plan to use this second package as some kind of library so that i can simple call 2 or 3 functions in future applets to draw these polygons (which always have the same shape). In the library file i have created a contructor, a draw function and some other functions to change some properties. I also created a function that created a popup window as soon as i click on one of the polygons i have created. In the popup some buttons are available which change the color of the polygon. All this works fine, but the problem i have is the following:
    When i click a button the main class (in package 1) needs to be repainted for the changes to be visable. But the main class can always be a different one. Is it possible to check in the class in the library package, which class from the main package called the class, and execute a repaint() on that class. So i have the following situation:
    Package 1 (Applets):
    package applets;
    class myApplet extends Applet implements .... {
    private Tank tank1 = new Tank(20, 20, 100, 200);
    private Tank tank2 = new Tank(250, 20, 100, 200);
    public void paint(Graphics g) {
    tank1.drawTank(g);
    tank2.drawTank(g);
    public void mouseClicked(MouseEvent e) {
    tank1.openWindow();
    tank2.openWindow();
    Package 2 (Library):
    package applets.library;
    class Tank {
    public Tank(int xPos, int yPos, int height, int width) {
    public void drawTank(Graphics g) {
    public void openWindow() {
    new myWindow("Window1");
    public class myWindow extends Frame {
    public myWindow(String name) {
    show();
    public boolean action(Event e, Object arg) {
    return true;
    So what i want to do is: In class Tank in the public class myWindow in the method action, i want to call the repaint() of the class myApplet
    I hope my problem is clear to you, as you may have noticed i have a little trouble explaining it clearly..

    First of all thanks a lot for your reply and sorry for my way of programming. Like i said i am pretty new to Java, i am actually only programming for about 2 weeks and trying to learn from some examples on the internet.
    I dont really understand what you want me to do, is it maybe possible to give a little bit of sample code? That would help me a lot.
    Maybe some background information about the project will help a bit too.
    I work at a company that develops automation solutions. We program PLC's and SCADA systems. Now Siemens has some PLC's that support Java applets which make it possible to visualize industrial processes. Now i am trying to figure out if it is possible to start developing own java applets for visualisation in the future. Since most programmers here have no experience in any higher programming language i want to keep it as simple as possible, by developing libraries that do the most of the programming work for them.
    Now i want to create the first part of this library by programming some kind of storage tank. This tank always has a valve. when i click on the valve a popup should open with the operation button to open of close that valve. When a valve is opened it should be colored green and when its closed it should be colored gray or something. The Tank class has a couple of methods:
    drawTank(); to draw the tank in my applet,
    openValve(); to open the Valve,
    closeValve(); to close the Valve,
    After all this is created i want to be able to use this class in all my other classes and create a tank by simple making a new Tank object, draw it on my applet using the drawTank() method and open or close the Valve using the other 2 methods, however when i open or close the Valve the color of the valve should change so i must be able to call the repaint of all the classes that use my Tank class, but i want to do that INSIDE my Tank class.
    If there is another way of doing this i would love to hear so, but i would help me a lot if you can explain in a little bit of sample code. It doesn't have to be really long or detailed.
    Thnx in advance

  • JFrame not showing components when called method in other class

    Hi everyone,
    I am new to SWING,and have this little problem.
    i have created a JFrame which has a button and its calling a method in another class.the result takes much more time(around 3mins) as the call involved with FTP.
    My problem is , i click the button(other componetns also there),and waiting for the result.all the time my Frame doesnt show any of the components,it looks as if the components are added to it.but when the call returns.everything is OK.
    Can any1 help me?
    Thanx in advance
    ethirajan

    http://java.sun.com/docs/books/tutorial/essential/threads/
    http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

  • Calling method from another class

    Got the below code for the Bank class with a log in system, Want i need is a While loop for
    "While ValidUser = True, Do method in Accounts class."
    package bank;
    import javax.swing.*;
    import java.lang.*;
    public class Bank {
                  /*User Arrays */
        public  String Customer[]= new String[4];
        public  String Pin[] = new String[4];
                 /* User Tryed details */
            String User;
          String PinAuth;
    Boolean ValidUser;
    public Bank ()
                  /*Customers */
              Customer[0]="John";
        Customer[1]="Alan";
        Customer[2]="Lisa";
        Customer[3]="Liam";
        Pin[0]="1234";
        Pin[1]="1982";
        Pin[2]="4321";
        Pin[3]="5678";
    public Bank(String CustAtt, String PinAtt)
         User = CustAtt;
         PinAuth = PinAtt;
    public String getUser()
        return User;
    public String getPin()
        return PinAuth;
    public void setUser(String CustAtt)
        User = CustAtt;
    public void setPin(String PinAtt)
        PinAuth = PinAtt;
      public static void main    (String args[] ){
    System.out.println("Welcome to The Bank of Scotland");
          String User;
          String PinAtt;
        boolean ValidUser;
          /* Get User Details */
         User =
                JOptionPane.showInputDialog("Please Enter Your Name");
        /* Get User pin */
         PinAtt =
                JOptionPane.showInputDialog("Enter your Pin");
    /* Print USer Details */
         System.out.println(User);
         System.out.println(PinAtt);
    /* Authorise Customer */
    Bank newBank = new Bank();
    for(int i=0; i<4;i++)
    if(User.equals(newBank.Customer) && PinAtt.equals(newBank.Pin[i]))
    ValidUser=true;
    else
    ValidUser=false;
    if(ValidUser=true)
    System.out.println("Auth");
    else if(ValidUser=false)
    System.out.println("Log in details are in correct");
    while(ValidUser=true)
    Account Class, in this class i need options for selecting withdraw deposit  and close account, not sure if i could do this in the Current account class though.
    Any advice will be great package bank;
    import javax.swing.*;
    import java.lang.*;
    public class Account {
    private String AccountNo;
    private int Balance;
    private int Deposit;
    String AccountUsed;
    public Account () {
    public String getAccountNo ()
    return AccountNo;
    public void setAccountNo (int val) {
    AccountUsed = AccountNo;
    public int getBalance () {
    return Balance;
    public void setBalance (int val) {
    this.Balance = val;
    public int getDeposit ()
    return Deposit;
    public void setDeposit (int val)
    this.Deposit = val;
    this.Balance=this.Balance+this.Deposit;
    public void setWithdrawl (int val)
    this.Balance=this.Balance-val;
    public static void account (String args[] ){
    String Deposit = new String();
    String Withdraw = new String() ;
    System.out.println("Deposit - Withdraw");
    Account newAccount = new Account();
    Deposit =
    JOptionPane.showInputDialog("Enter the ammount you wish to deposit");
    Withdraw =
    JOptionPane.showInputDialog("Enter the amount you wish to Withdraw");
    System.out.println(Deposit);
    System.out.println(Withdraw);
    Account custAccount =new Account();
    custAccount.setDeposit(Integer.parseInt(Deposit));
    custAccount.setWithdrawl(Integer.parseInt(Withdraw));
    System.out.println(custAccount.getBalance());

    Maxideon wrote:
    All of these are valid,
    while(validUser == true) {
    while(validUser) {
    //I prefer this one
    if(validUser == true) {
    if(validUser) {
    //I prefer this one
    } What you have,
    if(validUser = true) {
    if(validUser = false) {
    }is different. I have two equal signs, while you have one. What do you think one equal sign does?
    P.S. All your variable names are screwed up. They should begin with a lower case letter.
    Edit
    Some other anomalies: you declared ValidUser as a Boolean and you imported java.lang. .... Why?
    Edit
    Another weird thing.
    String Deposit = new String();
    String Withdraw = new String();?I Am fairly new to java, I have things "working" to an extent, and i am aware of the naming conventions over the variable names,

  • Call method from another class instance

    Forgive me if I don't make sense, I'm relatively new to Java and still not up on all the lingo.
    So here's what I want to do... This is probably easier explained with code:
    ParentClass.java
    public class ParentClass {
         public static void main(String[] args)
              ChildClass1 child1 = new ChildClass1();
              ChildClass2 child2 = new ChildClass2();
              System.out.println("ParentClass");
              System.out.println(child1.getText());
              System.out.println(child2.getText());
    ChildClass1.javapublic class ChildClass1 {
         private String text = "ChildClass1";
         public ChildClass1()
              System.out.println("ChildClass1 Constructor");
         public String getText()
         { return text; }
    }ChildClass2.java is identical to ChildClass1, except the 1's replaced with 2's etc.
    I need to be able to call getText() in ChildClass1 from ChildClass2, and eventually methods in the ParentClass class.
    As I understand, if I make the ChildClass's extend the ParentClass, every new instance of the ChildClass will create a new instance of the ParentClass. What I need though, is one instance of ParentClass with it's eventual variables etc. set, and then have the two classes defined within, able to talk to each other and the methods in the ParentClass.
    How does one go about doing this? Does that even make sense?
    Thanks, Savage

    You may need to read thru the information provided on this page to understand how to create objects: http://java.sun.com/docs/books/tutorial/java/data/objectcreation.html
    I'd also suggest you read the tutorial available at: http://java.sun.com/docs/books/tutorial/java/index.html
    Regarding how you call a method belonging to another class you could do it in the foll. ways depending on whether the method is static or not - a static method may be called using the class name followed by a dot and the static method name while a non-static method would require you to create an instance of the class and then use that instance name followed by a dot and the method name. All said and done i'd still suggest you read thru the complete Java programming tutorial to get a good grounding on all these concepts and fundamentals of the language if you are looking to master the technology.
    Thanks
    John Morrison

  • Acessing Methods From Other Class....

    Hi,
    Im creating a Estate Agent system for a project.
    Basically I have 4 class..
    Customer.class
    AddCustomer.class
    Buyer.class
    Seller.class
    The Customer class is used to create an instance of a customer in order to do things with this information latter on by passing values to it from the AddCustomer.class where the user inputs this information . The AddCustomer adds information to the database that the user has inputted.
    What i want to do with the Buyer and Seller class though is access this customer information that has been passed from AddCustomer to the Customer class... Im Just To Sure How...

    Nope....
    Im trying to access the created customer instance information that I created from within AddCustomer from Buyer And Seller in order to use that information...
          package estateAgent;
        import info.clearthought.layout.TableLayout;
        import java.awt.BorderLayout;
        import java.awt.FlowLayout;
        import java.awt.Font;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;
        import java.sql.Connection;
        import java.sql.PreparedStatement;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        import javax.swing.JButton;
        import javax.swing.JComboBox;
        import javax.swing.JFormattedTextField;
        import javax.swing.JLabel;
        import javax.swing.JOptionPane;
        import javax.swing.JPanel;
    import javax.swing.JTextField;
         * @author scs5kjb
         * @author Christopher James Cartlidge
         * @author SI
         * @version 1.5
        public class AddCustomer extends Screen
          private GUI gui;
          private JButton buyerButton;
          private JButton sellerButton;
          private JButton cancelButton;
          private JPanel buttonPanel;
          private JComboBox title;
          private JTextField firstName;
          private JTextField surname;
          private JTextField address1;
          private JTextField address2;
          private JTextField address3;
          private JTextField county;
          private JFormattedTextField postcode;
          private JTextField phoneNumber1;
          private JTextField phoneNumber2;
          private JPanel textPanel;
          private String customerID = "";
         private PreparedStatement addCustomerQuery;
         private PreparedStatement getCustomerIDQuery;  
           * Creates an AddCustomer.
           * @param gui The GUI object that displays the screen
          public AddCustomer( GUI gui, Connection database )
            this.gui = gui;
            String message = "Fields marked with a * need to be filled in";
            addHelp( null, message );
            createButtons();
            arrangeButtons();
            configureButtons(database);
            createFields();
            arrangeFields();
            addMainComponent( textPanel );
           * Initialises the buttons to go on the screen
          @Override public void createButtons()
            buyerButton = new JButton( "Buyer" );
            sellerButton = new JButton( "Seller" );
            cancelButton = new JButton( "Cancel" );
           * Initialises the text fields to go on the screen
          @Override public void createFields()
            Font fieldFont = new Font( "Sans", Font.PLAIN, 14 );
            String[] titles = { "Mr", "Mrs", "Ms", "Dr" };
            title = new JComboBox( titles );
            firstName = new JTextField( 15 );
            firstName.setFont( fieldFont );
            surname = new JTextField( 15 );
            surname.setFont( fieldFont );
            address1 = new JTextField( 15 );
            address1.setFont( fieldFont );
            address2 = new JTextField( 15 );
            address2.setFont( fieldFont );
            address3 = new JTextField( 15 );
            address3.setFont( fieldFont );
            county = new JTextField( 15 );
            county.setFont( fieldFont );
            postcode = new JFormattedTextField( );
            postcode.setFont( fieldFont );
            phoneNumber1 = new JTextField( 15 );
            phoneNumber1.setFont( fieldFont );
            phoneNumber2 = new JTextField( 15 );
            phoneNumber2.setFont( fieldFont );
           * Positions the buttons on the screen
          @Override public void arrangeButtons()
            buttonPanel = new JPanel( new FlowLayout() );
            buttonPanel.add( buyerButton );
            buttonPanel.add( sellerButton );
            buttonPanel.add( cancelButton );
            add( buttonPanel, BorderLayout.SOUTH );
           * Positions the text fields on the screen
          @Override public void arrangeFields()
            double p = TableLayout.PREFERRED;
            // double f = TableLayout.FILL; - commented out as this is never read
            double b = 10; //border size
            double g = 10; //gap size
            double[][] size = {
                { b, p, g, p, g, b },
                { b, p, g, p, g, p, g, p, g, p, g, p, g, p, g, p, g,
                  p, g, p, g, b }
            textPanel = new JPanel( new TableLayout( size ) );
            textPanel.add( new JLabel( "Title:" ), "1, 1" );
            textPanel.add( title, "3, 1" );
            textPanel.add( new JLabel( "First Name:*" ), "1, 3" );
            textPanel.add( firstName, "3, 3" );
            textPanel.add( new JLabel( "Surname:*" ), "1, 5" );
            textPanel.add( surname, "3, 5" );
            textPanel.add( new JLabel( "Address 1:*" ), "1, 7");
            textPanel.add( address1, "3, 7");
            textPanel.add( new JLabel( "Address 2:" ), "1, 9");
            textPanel.add( address2, "3, 9");
            textPanel.add( new JLabel( "Town/City:" ), "1, 11");
            textPanel.add( address3, "3, 11");
            textPanel.add( new JLabel( "County:" ), "1, 13");
            textPanel.add( county, "3, 13");
            textPanel.add( new JLabel( "Postcode:*" ), "1, 15");
            textPanel.add( postcode, "3, 15");
            textPanel.add( new JLabel( "Telephone 1:*" ), "1, 17");
            textPanel.add( phoneNumber1, "3, 17");
            textPanel.add( new JLabel( "Telephone 2:" ), "1, 19");
            textPanel.add( phoneNumber2, "3, 19");
           * Configures the actions to be taken when one of the buttons on the
           * screen is pressed
          public void configureButtons(final Connection database)
            setBuyerButtonHandler(
                new ActionListener()
                  public void actionPerformed(ActionEvent e)
                    if( validateFields() ) {
                      try {
                       findNextCustomerID(database);
                       addNewCustomer(database);
                      catch (SQLException error) {
                        error.printStackTrace();
                      gui.select( "Add Buyer" );
                      clear();
            setSellerButtonHandler(
                    new ActionListener()
                      public void actionPerformed(ActionEvent e)
                        if( validateFields() ) {
                          try {
                            addNewCustomer(database);
                          catch (SQLException error) {
                            error.printStackTrace();
                          clear();
            setCancelButtonHandler(
                new ActionListener()
                  public void actionPerformed(ActionEvent e)
                    clear();
           * Deals with button clicks on the buyerButton
           * @param listener The action listener to deal with button presses
          private void setBuyerButtonHandler(ActionListener listener)
            buyerButton.addActionListener( listener );
           * Deals with button clicks on the buyerButton
           * @param listener The action listener to deal with button presses
          private void setSellerButtonHandler(ActionListener listener)
            sellerButton.addActionListener( listener );
           * Sets the action listener for the cancel button on the screen
           * @param listener The action listener to be added
          private void setCancelButtonHandler( ActionListener listener )
            cancelButton.addActionListener( listener );
           * Checks whether the information entered is valid
           * @return true if the information entered is valid
          public boolean validateFields()
            String message = "";
            boolean valid = true;
            if( ! Validation.validString( firstName.getText() ) ) {
              message += "Invalid first name. This field may only contain" +
                  " alphabetic characters\nand no white space";
              valid = false;
            if( ! Validation.validString( surname.getText() ) ) {
              if( ! message.equals( "" ) )
                message += "\n\n";
              message += "Invalid last name. This field may only contain" +
                  " alphabetic characters\nand no white space";
              valid = false;
            if( ! Validation.validAddress1( address1.getText() ) ) {
              if( ! message.equals( "" ) )
                message += "\n\n";
              message += "Invalid address 1. This field must have the house" +
                  " number as the first\ncharacters followed by alphabetic" +
                  " characters only";
              valid = false;
            if( ! address2.getText().equals( "" ) ) {
              if( ! Validation.validSentence( address2.getText() ) ) {
                if( ! message.equals( "" ) )
                  message += "\n\n";
                message += "Invalid address 2. This field may contain alphabetic" +
                    " characters only";
                valid = false;
            if( ! address3.getText().equals( "" ) ) {
              if( ! Validation.validSentence( address3.getText() ) ) {
                if( ! message.equals( "" ) )
                  message += "\n\n";
                message += "Invalid address 3. This field may contain alphabetic" +
                    " characters only";
                valid = false;
            if( ! county.getText().equals( "" ) ) {
              if( ! Validation.validSentence( county.getText() ) ) {
                if( ! message.equals( "" ) )
                  message += "\n\n";
                message += "Invalid county. This field may contain alphabetic" +
                    " characters only";
                valid = false;
            if( ! Validation.validPostcode( postcode.getText() ) ) {
              if( ! message.equals( "" ) )
                message += "\n\n";
              message += "Invalid postcode. The postcode must be in the format:\n" +
                  "L(L)N(N) NLL\nWhere 'L' is a letter, 'N' is a number and " +
                  "values in brackets\nare optional";
              valid = false;
            if( ! Validation.validPhone( phoneNumber1.getText() ) ) {
              if( ! message.equals( "" ) )
                message += "\n\n";
              message += "Invalid primary phone number. This field may contain" +
                  " only numbers.\nThe area code must be included, and white" +
                  " space is not allowed";
              valid = false;
            if( ! phoneNumber2.getText().equals( "" ) ) {
              if( ! Validation.validPhone( phoneNumber2.getText() ) ) {
                if( ! message.equals( "" ) )
                  message += "\n\n";
                message += "Invalid secondary phone number. This field may contain" +
                " only numbers.\nThe area code must be included, and white" +
                " space is not allowed";
                valid = false;
            if( ! message.equals( "" ) )
              JOptionPane.showMessageDialog( gui, message, "Alert",
                  JOptionPane.ERROR_MESSAGE );
            return valid;
           * Clears all of the fields on the screen
          @Override public void clear()
            title.setSelectedIndex( 0 );
            firstName.setText( "" );
            surname.setText( "" );
            address1.setText( "" );
            address2.setText( "" );
            address3.setText( "" );
            county.setText( "" );
            postcode.setText( "" );
            phoneNumber1.setText( "" );
            phoneNumber2.setText( "" );
         * Stores the values entered by the user in the database
         * Also retrives the serial Customer_ID
         * These will then be stored in a Customer object to be used elsewhere.
         * @param database Connection to the database
         * @throws SQLException
           public void addNewCustomer(Connection database) throws SQLException
             String ADD_CUSTOMER_SQL = "INSERT INTO Customer_Details (First_Name," +
             " Last_Name, Address_1, Address_2, Address_3, County, Post_Code,"
            +"Phone_Number_1, Phone_Number_2) VALUES('"+firstName.getText()+"', '"+surname.getText()+
            "', '"+address1.getText()+"', '"+address2.getText()+"', '"+address3.getText()
            +"', '"+county.getText()+"', '"+postcode.getText()+"', '"
            +phoneNumber1.getText()+"', '"+phoneNumber2.getText()+"')";
             Address customerAddress = new Address(address1.getText(), address2.getText(), address3.getText(),
                 county.getText(), postcode.getText());
            Customer newCustomer = new Customer(findNextCustomerID(database), firstName.getText(),
             surname.getText(), customerAddress, phoneNumber1.getText(), phoneNumber2.getText());
             //Constructs and prepares a query to insert the details into the Database
             //Note: We need to set Customer_ID to be serial.
             addCustomerQuery = database.prepareStatement(ADD_CUSTOMER_SQL);
             addCustomerQuery.executeUpdate();
           * Constructs and prepares a statement to retrieve the ID of the customer just entered
           * Dirty dirty hack alert
           * @param database
           * @return
           * @throws SQLException
          public String findNextCustomerID(Connection database) throws SQLException
            String GET_NEW_ID_SQL = "SELECT Customer_ID FROM Customer_Details WHERE First_Name = '"
              +firstName.getText()+"' AND Last_Name = '"+surname.getText()+"' AND Address_1 = '"+address1.getText()+
              "' AND Address_2 = '"+address2.getText()+"' AND Address_3 = '"+address3.getText()+"' AND County ='"
              +county.getText()+"' AND Post_Code ='"+postcode.getText()+"' AND Phone_Number_1 = '"
              +phoneNumber1.getText()+"' AND Phone_Number_2 = '"+phoneNumber2.getText()+"'";
            Address customerAddress = new Address(address1.getText(),address2.getText(),address3.getText(),
                county.getText(),postcode.getText());
            getCustomerIDQuery = database.prepareStatement(GET_NEW_ID_SQL);
            ResultSet idResults = getCustomerIDQuery.executeQuery();
            while (idResults.next())
              customerID = (idResults.getString("Customer_ID"));
            return customerID;
          @Override public void configureButtons()
            // TODO Auto-generated method stub
        }As you can see the information has been written to the database already, and I have also created an instance of Customer with this information and Now I want to access the newCustomer instance from Buyer And Seller..
    package estateAgent;
    * @author scs5kjb
    * @version 23-03-07
    public class Buyer extends Customer
      private String contract, location, type;
      private int rooms, bedrooms, bathrooms, ensuite, stories;
      private double maxPrice, minPrice;
      private int garden;
      private String garage;
      Customer.
       * Creates a Buyer.
       * @param id The id of a buyer
       * @param firstName The first name of a buyer
       * @param lastName The last name of a buyer
       * @param address The address of a buyer
       * @param phone1 The primary phone number of a buyer
       * @param phone2 The secondary phone number of a buyer
       * @param contract The type of contract (Buy or Rent) wanted
       * @param location The location wanted
       * @param type The type of property wanted
       * @param rooms The number of rooms wanted
       * @param bedrooms The number of bedrooms wanted
       * @param bathrooms The number of bathrooms wanted
       * @param ensuite The number of ensuite wanted
       * @param stories The number of stories wanted
       * @param maxPrice The maximum price a buyer is willing to pay
       * for a property
       * @param minPrice The minimum price of a property
       * @param garden The size of garden wanted
       * @param garage The type of garage wanted
      public Buyer( String id, String firstName, String lastName,
          Address address, String phone1, String phone2, String contract,
          String location, String type, int rooms, int bedrooms,
          int bathrooms, int ensuite, int stories, double maxPrice,
          double minPrice, int garden, String garage )
        super( id, firstName, lastName, address, phone1, phone2 );
        this.contract = contract;
        this.location = location;
        this.type = type;
        this.rooms = rooms;
        this.bedrooms = bedrooms;
        this.bathrooms = bathrooms;
        this.ensuite = ensuite;
        this.stories = stories;
        this.maxPrice = maxPrice;
        this.minPrice = minPrice;
        this.garden = garden;
        this.garage = garage;
       * @return The type of contract wanted
      public String getContract()
        return contract;
       * @return The location wanted
      public String getLocation()
        return location;
       * @return The type of contract wanted
      public String getType()
        return type;
       * @return The number of rooms wanted
      public int getRooms()
        return rooms;
       * @return The number of bedrooms wanted
      public int getBedrooms()
        return bedrooms;
       * @return The number of bathrooms wanted
      public int getBathrooms()
        return bathrooms;
       * @return The number of ensuite wanted
      public int getEnsuite()
        return ensuite;
       * @return The number of stories wanted
      public int getStories()
        return stories;
       * @return The max. price wanted
      public double getMaxPrice()
        return maxPrice;
       * @return The min. price wanted
      public double getMinPrice()
        return minPrice;
       * @return The size of garden wanted
      public int getGarden()
        return garden;
       * @return The type of garage wanted
      public String getGarage()
        return garage;
       * @return A string representation of a buyer
      @Override public String toString()
        String string = super.toString();
        string += "\n\nBuyer Preferences:";
        if( contract != null )
          string += "\nType of contract: " + contract;
        if( location != null )
          string += "\nLocation: " + location;
        if( type != null )
          string += "\nType of Property: " + type;
        if( rooms != 0 )
          string += "\nNumber of Rooms: " + rooms;
        if( bedrooms != 0 )
          string += "\nNumber of Bedrooms: " + bedrooms;
        if( bathrooms != 0 )
          string += "\nNumber of Bathrooms: " + bathrooms;
        if( ensuite != 0 )
          string += "\nNumber of Ensuite: " + ensuite;
        if( stories != 0 )
          string += "\nNumber of Stories: " + stories;
        if( maxPrice != 0 )
          string += "\nMax. Price: " + maxPrice;
        if( minPrice != 0 )
          string += "\nMin. Price: " + minPrice;
        if( garden != -1 ) {
          if( garden == 0 )
            string += "\nGarden Size: None";
          else
            string += "\nGardenSize: " + garden;
        if( garage != null )
          string += "\nGarage Type: " + garage;
        return string;
    }See this is my Buyer class, for example a Customer can either be and buyer or seller so i create a generic customer and then use that information to create a buyer or seller depending on wha button they press...

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

  • How to call a method from a class without creating an instance fromthisclas

    I want to create a class with methods but I want to call methods from this class without creating an instance from this class. Is this possible?
    Is there in Java something like class methods and object methods????

    keyword 'static' my friend.
    public class foo {
    public static void bar {
    System.out.println ("hello");
    foo.bar()

  • Use methods in other classes

    Can I use methods from other classes than the class that myClass extends?
    ex. myClass extends parentClass{
    myMethod()
    myMethod() is declared in i third class. Is this possible or can I only use classes from the parent class?
    -Thanks-

    I'm not really sure what the previous two answers were getting at.
    Yes, you can use methods all the way up the class hierarchy, as long as they are visible.
    For example, Object implements toString(). You can call toString() on any object in Java and it will render the object to a string in one way or another. That is because toString() is public.
    If toString() were protected, you would only be able to call the method if you were a subclass of of that object (or in the same package), which would make the toString() method much less useful.
    I would suggest reading up on the differences in the four visibility modifiers (private, (default), protected, and public). Private is the only one which nothing else can call. If you are public or protected, any subclass can call the method, even if there are 20 superclasses between the implementor and the caller.
    Good luck!
    Steve

  • Is Two Classes that call methods from each other possible?

    I have a class lets call it
    gui and it has a method called addMessage that appends a string onto a text field
    i also have a method called JNIinterface that has a method called
    sendAlong Takes a string and sends it along which does alot of stuff
    K the gui also has a text field and when a button is pushed it needs to call sendAlong
    the JNIinterface randomly recieves messages and when it does it has to call AddMessage so they can be displayed
    any way to do this??

    Is Two Classes that call methods from each other possible?Do you mean like this?
       class A
         static void doB() { B.fromA(); }
         static void fromB() {}
       class B
         static void doA() { A.fromB(); }
         static void fromA() {}
    .I doubt there is anyway to do exactly that. You can use an interface however.
       Interface IB
         void fromA();
       class A
         IB b;
         A(IB instance) {b = instance;}
         void doB() { b.fromA(); }
         void fromB() {}
       class B implements IB
         static void doA() { A.fromB(); }
         void fromA() {}
    .Note that you might want to re-examine your design if you have circular references. There is probably something wrong with it.

  • 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

  • Calling a method from abstarct class

    Hi Experts,
    Am working on ABAP Objects.
    I have created an Abstract class - with method m1.
    I have implemented m1.
    As we can not instantiate an abstract class, i tried to call the method m1 directly with class name.
    But it it giving error.
    Please find the code below.
    CLASS c1 DEFINITION ABSTRACT.
      PUBLIC SECTION.
        DATA: v1 TYPE i.
        METHODS: m1.
    ENDCLASS.                    "c1 DEFINITION
    CLASS c1 IMPLEMENTATION.
      METHOD m1.
        WRITE: 'You called method m1 in class c1'.
      ENDMETHOD. "m1
    ENDCLASS.                    "c1 IMPLEMENTATION
    CALL METHOD c1=>m1.
    Please tell me what is wrong and how to solve this problem.
    Thanks in Advance.

    Micky is right, abstract means not to be instantiated. It is just a "template" which you can use for all subsequent classes. I.e you have general abstract class vehicle . For all vehicles you will have the same attributes like speed , engine type ,  strearing , gears etc and methods like start , move etc.
    In all subsequent classes (which inherit from vehicle) you will have more specific attributes for each. But all of these classes have some common things (like the ones mentioned above), so they use abstract class to define these things for all of them.
    Moreover there is no sense in creating instance (real object) of class vehicle . What kind of physical object would vehicle be? there is no such object in real world, right? For this we need to be more precise, so we create classes which use this "plan" for real vehicles. So the abstract class here is only to have this common properties and behaviour defined in one place for all objects which will have these. Abstract object however cannot be created per se. You can only create objects which are lower in hierarchy (which are specific like car , ship, bike etc).
    Hope this claryfies what we need abstract classes for.
    Regards
    Marcin

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

Maybe you are looking for