Instantiating objects from within listener methods!

Hi Everyone,

I have just finished writing a nice GUI for an application that I am developing. On the GUI there are several JButtons and several JComboBoxes. I have written listener methods for all the afore mentioned, except for one JButton.

The offending JButtons listener method needs to create an object from another entirely different class and I am having trouble doing this.

e.g.:

class GUI(){

.....

JButton buttonCalc = new JButton("Calculate);

.....

GUI()

{

.....

.....

Frame.add(buttonCalc)

.....

.....

.....

.....

buttonCalc.addActionListener(this);

.....

public void actionPerfromed(ActionEvent e)

{

if(e.getActionCommand().equals("Calculate"))

{

//Create an Object from a totally differnet class.

//e.g.:

//CalculateX CalcX = new CalculateX();

}

if(e.get.....

{

....

.....

}

}

class CalculateX{

.....

....

CalculateX{

......

......

}

}

I have tried code like the above but have so far found no success. The above code results in an error message similar to "Class CaclculateX not found in Class GUI".

I get the feeling that this is an issue of scope, however I have no idea how to resolve this.

Any help in creating an object of a different class from within the Listener method of another class (as indicated above) will be greatly appreciated.

Thanks

A-S

[1551 byte] By [Alpha-Sentinela] at [2007-9-27 5:09:43]
# 1
Dear Alpha-Sentinel The error is caused by the file not foundmake sure the CalculateX class is in the same directory because there is nothing wrong in calling another classThanksJoey
joeylta79a at 2007-7-8 1:25:05 > top of Java-index,Archived Forums,Swing...
# 2

Study this example, the Calculator class should realy go in a seperate file, but many compilers will let that go. Compile this as one file and run it, then as two and run it again. If it runs fine the first time and not the second, you have a class path problem.

import java.awt.BorderLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JButton;

import javax.swing.JLabel;

public class Gui

extends JPanel

{

public Gui()

{

final JLabel lbl= new JLabel(" ", JLabel.CENTER);

JButton btn= new JButton("Calculate");

btn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

lbl.setText(

"1 + 1 = " + new Calculator().add(1,1));

}

});

setLayout(new BorderLayout());

add(btn, BorderLayout.NORTH);

add(lbl, BorderLayout.CENTER);

}

public static void main(String[] argv)

{

JFrame frame= new JFrame("Gui");

frame.getContentPane().add(new Gui());

frame.pack();

frame.setDefaultCloseOperation(3);

frame.setVisible(true);

}

}

public class Calculator

{

public int add(int x, int y) {

return x +y;

}

}

dchswa at 2007-7-8 1:25:05 > top of Java-index,Archived Forums,Swing...