Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating objects of alternate classes from within Listener methods.

Status
Not open for further replies.

JProg

Programmer
Apr 4, 2002
88
JP
Hi Everyone,

At the moment I have a GUI class and associated method that contains several buttons. When one of the buttons is pressed I need to create an object from a totally different class.

i.e.:

public class GUI extends JFrame implements ActionListener{

JButton btn1 = new JButton(“Calculate”);

GUIV()
{
Con = getContentPane();

Con.add(btn1);

Btn1.addActionListener(this);

}

public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals(“Calculate”))
{
String str = …;
//Create an object from a totally different class, e.g. CalculateX
//Passing the CalculateX object of the CalculateX class the value
//of String str.
}
}

public void CalculateX{
String Calc = str (…from the GUI class)

If anybody can help with code that does something along these lines it will be greatly appreciated.

Thanks
 
Is this the sort of thing you are wanting?



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class GUI extends JFrame implements ActionListener {

JButton btn1 = new JButton("Calculate");

GUI()
{
Container c = getContentPane();

c.add(btn1);

btn1.addActionListener(this);

}

public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Calculate"))
{
String str = "...";
CalculateX myCalculateX = new CalculateX(str);
}
}

class CalculateX {
String str;

CalculateX(String strArg) {
str = strArg;
}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top