Using my Method from my Class (clearer explanation)
I wrote a class called day. With some methods that perform simple operations. Here is a simple one that prints the day of the week:
public void printDay()
System.out.print("Day of the week is "+ day);
My question is:
How do I call this method in a new program ?
I wrote a class called day. With some methods that
perform simple operations. Here is a simple one that
prints the day of the week:
public void printDay()
System.out.print("Day of the week is "+ day);
My question is:
How do I call this method in a new program ?Mate, i'm hardly an expert, but what you probably want to do is instantiate an object of your class in the class that will use it. That means, for an object called "myDay" or whatever else:
Day myDay = new Day();you can then call your method through the object:
myDay.printDay();hope that's helpful somehow.
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? -
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() methodi 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);
} -
Using a method from a class into another
Hello,
I have two classes that do separate things , one makes a checkboard and the other one creates a fading effect, and i would like to know how can i modify the first one in order for the black rectangles of the checkerboard to have a fading effect, only the black ones.
Checkerboard
import java.awt.Frame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.AWTEvent;
import java.awt.event.WindowEvent;
public class DrawCheckerboard extends Frame {
public static void main(String arg[]) {
new DrawCheckerboard();
DrawCheckerboard() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
Checkerboard checkerboard = new Checkerboard();
add(checkerboard);
pack();
show();
public void processWindowEvent(WindowEvent event) {
if(event.getID() == WindowEvent.WINDOW_CLOSING)
System.exit(0);
class Checkerboard extends Canvas {
Checkerboard() {
setSize(256,256);
public void paint(Graphics g) {
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
if(((i+j) & 1) == 0) {
int x = i * 64;
int y = j * 64;
g.fillRect(x,y,64,64);
Fade
import java.awt.Frame;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.AWTEvent;
import java.awt.event.WindowEvent;
public class DrawFade extends Frame {
public static void main(String arg[]) {
new DrawFade();
DrawFade() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
Fade fade = new Fade();
add(fade);
pack();
show();
public void processWindowEvent(WindowEvent event) {
if(event.getID() == WindowEvent.WINDOW_CLOSING)
System.exit(0);
class Fade extends Canvas {
Fade() {
setSize(400,300);
public void paint(Graphics g) {
int x = 0;
int y = 0;
int width = 2;
int height = 400;
Color color = new Color(100,50,150);
while(x < 400) {
g.setColor(color);
g.fillRect(x,y,width,height);
x += width;
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
if(++red > 255)
red = 255;
if(++green > 255)
green = 255;
if(++blue > 255)
blue = 255;
color = new Color(red,green,blue);
}Looks more or less like reinventing the wheel.
The wheel in this case being java.awt.GradientPaint.
db -
Doubt on exec method from Process class
i want to use exec method from Process class to run an external exe.
now the problem is that Process is an abstract class and hence cant be instantiated.nor can i access exec method directly even though i import the required packages as its not static.how can i go about using exec() if thats the case.
Also can i run a file like notepad.exe present in system32 by providing the path of notepad.exe as an arguement in execi would be really grateful to you if you can write
the syntax for me along eith the class.i tried it out
and i got a lot of errors
this is what i obbtained from the documentation
"public Process exec(String command)
throws IOException"
l to comprehend is what that class Process is doing
in the syntax.from the method its supposed to return
Process class.can you explain it and the usage of
exec too
import java.lang.*;
class abc
Runtime ob1;
ob1.exec("c:\\windows\\system32\\notepad.exe");
//i am getting a compile time error for this code
which cites that <identifier> required at line 6You need to put the exec call in a method or constructor. You can't just place code anywhere within a class.
You should also cal Runtime.exec just as I told you. It's a static method.
There are lots of examples if you google.
Kaj -
Use method from father class for event
Hi,
I want to use a preDelete event in my class, but the method I would like to call for the event is not in the class itself, but in the (abstract) predecessor class. Any chance to do this? At the moment I can't select the method in the event tab page (it's not in the list to choose from ...)
Thank you!
J.F.In 9.0.4 you will need to add the parent class as a descriptor and choose to deactivate it. This will allow you to choose methods from that class in the subclass descriptors.
In 10.1.3 there is a dialog for specifying classes that are not persistent, but necessary in other persistent classes: http://www.oracle.com/technology/products/ias/toplink/doc/1013/main/_html/mw007.htm#sthref629
A good explanation of why we don't store the parent and referenced classes unless explictly asked can be found here: Re: Mapping Workbench 10.1.3.0 Bug - Cannot add Implemented Interfaces
Hope this helps,
Karen -
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? -
ABAP Objects : calling one method from another class
Hi,
Can you please tell me how to call method from one class or interfce to another class.The scenario is
I have one class CL_WORKFLOW_TASK, this class have interface IF_WORKFLOW_TASK & this interface have method IF_WORKFLOW_TASK~CLOSE. Now my requirement is ,
There is another class CL_WORKFLOW_CHAIN ,this class have interface IF_WORKFLOW_CHAIN & this interface have method IF_WORKFLOW_CHAINCLOSE_ALL_PREDECESSORS. Now i have to write my code in this method but i have to use IF_WORKFLOW_TASKCLOSE method for closing the task.
Can you please give me the code for the above .
Please waiting for reply.Hi,
You can use the concept of INHERITANCE in this scenario.By using this concept, you can call all the public and protected methods of class CL_WORKFLOW_TASK in the required calss CL_WORKFLOW_CHAIN as per your requirement.
Go through the Introdctory(INHERITANCE) programming from this SAPHELP link.
http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
I hope, it will help in you inresolving your problem.
by
Prasad GVK. -
Calling a non-static method from another Class
Hello forum experts:
Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
populates a JTable.
2. User selects a row in the table and then clicks a button on the icon toolbar
which is part of UIMenu class.
3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
(a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
== OR ==
(b). I could declare UpdateDatabase() as static and call this method without
creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
object specific data.
With option (b), if I declare the method as static, the variables used in the method would also have to be static.
The variables, in which case, would not be object specific.
Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
way?
Any ideas or thoughts will be of tremendous help. Thanks in advance.Hello Forum:
Danny_From_Tower, Encephalatic: Thank you both for your responses.
Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
and declared as public.
public class MyMenu {
public JButton btnAccept;
//Constructor
public MyMenu() {
btnAccept = new JButton("Accept");
} I instantiate an object for MyMenu class in the main application class MyApp.
public class MyApp {
private MyMenu menu;
//Constructor
public MyApp(){
menu = new MyMenu();
public void openOrder(){
MyGUI MyIntFrame = new MyGUI(menu.btnAccept);
}I pass this button all the way down to the class detail02. Now I want to set up a listener for this
button in the class detail02. I am not able to do this.
public class MyGUI {
private JButton acceptButton;
private detail02 dtl1 = new detail02(acceptButton);
//Constructor
public AppGUI(JButton iButton){
acceptButton = iButton;
public class detail02{
private JButton acceptButton;
//Constructor
public detail02(JButton iButton){
acceptButton = iButton;
acceptButton.addActionListener(new acceptListener());
//method
private void acceptListener_actionPerformed(ActionEvent e){
System.out.println("Menu item [" + e.getActionCommand( ) + "] was pressed.");
class acceptListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
acceptListener_actionPerformed(e);
} I am not able to get the button Listener to work. I get NullPointerException at this line
acceptButton.addActionListener(new acceptListener());in the class detail02.
Is this the right way? Or is there a better way of accomplishing my objective?
Please help. Your inputs are precious! Thank you very much for your time! -
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 -
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][ -
Moving a method from one class to another issues
Hi, im new. Let me explain what i am trying to achieve. I am basically trying to move a method from one class to another in order to refactor the code. However every time i do, the program stops working and i am struggling. I have literally tried 30 times these last two days. Can some one help please? If shown once i should be ok, i pick up quickly.
Help would seriously be appreciated.
Class trying to move from, given that this is an extraction:
class GACanvas extends Panel implements ActionListener, Runnable {
private WorldMenuItems speedMenuItems, designMenuItemsPlantGrowth, designMenuItemsPlantCount;
private WorldMenuItems designMenuItemsPlantEaten, designMenuItemsApproximatePopulation;
private WorldMenuItems designMenuItemsEatersBorn,designMenuItemsMutationProbability;
private WorldMenuItems designMenuItemsCrossoverProbability;
MenuBar getMenuBar() {
menuBar = new MenuBar();
addControlItemsToMenuBar();
addSpeedItemsToMenuBar();
addWorldDesignItemsToMenuBar();
return menuBar;
This is the method i am trying to move (below)
public void itemsInsideWorldDesignMenu() {
designMenuItemsPlantGrowth = new WorldMenuItems("Plants Grow",
new String[] { "In Rows", "In Clumps", "At Random",
"Along the Bottom", "Along the Edges" }, 1);
designMenuItemsPlantCount = new WorldMenuItems("Number Of Plants",
new String[] { "50", "100", "150", "250", "500" }, 3);
designMenuItemsPlantEaten = new WorldMenuItems("When a Plant is Eaten",
new String[] { "It grows back somewhere",
"It grows back nearby", "It's Gone" }, 0);
designMenuItemsApproximatePopulation = new WorldMenuItems(
"Approximate Population", new String[] { "10", "20", "25",
"30", "40", "50", "75", "100" }, 2);
designMenuItemsEatersBorn = new WorldMenuItems("Eaters are Born",
new String[] { "At the Center", "In a Corner",
"At Random Location", "At Parent's Location" }, 2);
designMenuItemsMutationProbability = new WorldMenuItems(
"Mutation Probability", new String[] { "Zero", "0.25%", "0.5%",
"1%", "2%", "3%", "5%", "10%" }, 3);
designMenuItemsCrossoverProbability = new WorldMenuItems(
"Crossover Probability", new String[] { "Zero", "10%", "25%",
"50%", "75%", "100%" }, 4);
Class Trying to move to:
class WorldMenuItems extends Menu implements ItemListener {
private CheckboxMenuItem[] items;
private int selectedIndex = -1;
WorldMenuItems(String menuName, String[] itemNames) {
this(menuName, itemNames, -1);
WorldMenuItems(String menuName, String[] itemNames, int selected) {
super(menuName);
items = new CheckboxMenuItem[itemNames.length];
for (int i = 0; i < itemNames.length; i++) {
items[i] = new CheckboxMenuItem(itemNames);
add(items[i]);
items[i].addItemListener(this);
selectedIndex = selected;
if (selectedIndex < 0 || selectedIndex >= items.length)
selectedIndex = 1;
items[selectedIndex].setState(true);
public int getSelectedIndex() {
return selectedIndex;
public void itemStateChanged(ItemEvent evt) { // This works on other systems
CheckboxMenuItem newSelection = (CheckboxMenuItem)evt.getSource();
for (int i = 0; i < items.length; i++) {
if (newSelection == items[i]) {
items[selectedIndex].setState(false);
selectedIndex = i;
newSelection.setState(true);
return;Ok i've done this. I am getting an error on the line specified. Can someone help me out and tell me what i need to do?
GACanvas
//IM GETTING AN ERROR ON THIS LINE UNDER NAME, SAYING IT IS NOT VISIBLE
WorldMenuItems worldmenuitems = new WorldMenuItems(name, null);
public MenuBar getMenuBar() {
menuBar = new MenuBar();
addControlItemsToMenuBar();
addSpeedItemsToMenuBar();
worldmenuitems.addWorldDesignItemsToMenuBar();
return menuBar;
class WorldMenuItems extends Menu implements ItemListener {
private WorldMenuItems speedMenuItems, designMenuItemsPlantGrowth, designMenuItemsPlantCount;
private WorldMenuItems designMenuItemsPlantEaten, designMenuItemsApproximatePopulation;
private WorldMenuItems designMenuItemsEatersBorn,designMenuItemsMutationProbability;
private WorldMenuItems designMenuItemsCrossoverProbability;
GACanvas gacanvas = new GACanvas(null);
private CheckboxMenuItem[] items;
private int selectedIndex = -1;
WorldMenuItems(String menuName, String[] itemNames) {
this(menuName, itemNames, -1);
WorldMenuItems(String menuName, String[] itemNames, int selected) {
super(menuName);
items = new CheckboxMenuItem[itemNames.length];
for (int i = 0; i < itemNames.length; i++) {
items[i] = new CheckboxMenuItem(itemNames);
add(items[i]);
items[i].addItemListener(this);
selectedIndex = selected;
if (selectedIndex < 0 || selectedIndex >= items.length)
selectedIndex = 1;
items[selectedIndex].setState(true);
public int getSelectedIndex() {
return selectedIndex;
public void itemStateChanged(ItemEvent evt) { // This works on other systems
CheckboxMenuItem newSelection = (CheckboxMenuItem)evt.getSource();
for (int i = 0; i < items.length; i++) {
if (newSelection == items[i]) {
items[selectedIndex].setState(false);
selectedIndex = i;
newSelection.setState(true);
return;
public void itemsInsideWorldDesignMenu() {
designMenuItemsPlantGrowth = new WorldMenuItems("Plants Grow",
new String[] { "In Rows", "In Clumps", "At Random",
"Along the Bottom", "Along the Edges" }, 1);
designMenuItemsPlantCount = new WorldMenuItems("Number Of Plants",
new String[] { "50", "100", "150", "250", "500" }, 3);
designMenuItemsPlantEaten = new WorldMenuItems("When a Plant is Eaten",
new String[] { "It grows back somewhere",
"It grows back nearby", "It's Gone" }, 0);
designMenuItemsApproximatePopulation = new WorldMenuItems(
"Approximate Population", new String[] { "10", "20", "25",
"30", "40", "50", "75", "100" }, 2);
designMenuItemsEatersBorn = new WorldMenuItems("Eaters are Born",
new String[] { "At the Center", "In a Corner",
"At Random Location", "At Parent's Location" }, 2);
designMenuItemsMutationProbability = new WorldMenuItems(
"Mutation Probability", new String[] { "Zero", "0.25%", "0.5%",
"1%", "2%", "3%", "5%", "10%" }, 3);
designMenuItemsCrossoverProbability = new WorldMenuItems(
"Crossover Probability", new String[] { "Zero", "10%", "25%",
"50%", "75%", "100%" }, 4);
public void addWorldDesignItemsToMenuBar() {
gacanvas = new GACanvas(null);
itemsInsideWorldDesignMenu();
Menu designMenuItems = new Menu("WorldDesign");
designMenuItems.add(designMenuItemsPlantGrowth);
designMenuItems.add(designMenuItemsPlantCount);
designMenuItems.add(designMenuItemsPlantEaten);
designMenuItems.add(designMenuItemsApproximatePopulation);
designMenuItems.add(designMenuItemsEatersBorn);
designMenuItems.add(designMenuItemsMutationProbability);
designMenuItems.add(designMenuItemsCrossoverProbability);
gacanvas.menuBar.add(designMenuItems); -
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! :Df1d 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 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
-
[SOLVED] Mpd and sonata doesn't seem to work
Hi guys! I 'm facing with an issue . I can't seem to configure mpd correctly to run it with sonata . I've followed the alternative setup from archwiki and this is my config file . # An example configuration file for MPD # See the mpd.conf man page fo
-
Today I tried listening to music on my iPhone 4S, only to find that my volume adjuster had disappeared. And just to clarify, when I say that it disappeared, I mean that when I press the volume buttons on my phone, I see the speaker icon but the gauge
-
External harddisk not working on windows, what can i do?
I am a new Mac user and cannot seem to get it with the external harddrives. I bought one that is supposed to be working with both windows and mac but after installing time machine (which formatted it in a non windows way i guess) it is not readable b
-
Sense Error burning DVD disc in Toast
HI there, I'm trying to burn an ISO (DVD R disc) using Roxio's Toast Titanium and no matter what brand of disc I use, I keep getting "The drive reported an error: Sense Key = MEDIUM ERROR Sense Code = 0x73, 0x03. I'm using a 2008 15inch MacBook Pro,
-
Dear SAP Guru's I have query kindly solve my issue. What is the basic configuration for RD04 out put type. Becoz iam doing the crosscompany sales, while customer is ordering the to Plant A, at tht time plant A is not having the goods, then Plant B wi