Accessing interface components from a seperate class

Hi there,
I've just been given a Java project to build, that involves writing an applet to allow text based communication between pairs of people. I've always thought the best way to go about it was to divide code into functional units, i.e. put the user interface code in one class and the code that responds to user interface interactions in other classes (of the same package).
The problem is getting the other classes to access the interface components created in the interface class.
So for brevity, here is my interface Applet class;
package name;
import statements here;
public class Communicate extends Applet {
declare all variables, strings, labels, combo boxes etc
//Construct the applet
public Communicate() {
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
//Initialize the applet
public void init() {
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
private void jbInit() throws Exception {
add components here
//Now the problem. In the interface there are combo boxes. When the user clicks a button it constructs a jframe that asks the user for a string. The idea is that the string be added to a combobox using add item. If I leave this code in the applet class it works fine, e.g.
public void jButton5_actionPerformed(ActionEvent actionEvent) {
JFrame f = new JFrame();
f.setSize(200, 200);
f.setLocation(200, 200);
f.setVisible(false);
//Add those boxes to the JFrame
JTextField titleField = new JTextField();
String title = "Please enter the title";
int result = JOptionPane.showOptionDialog(f,
new Object[] { message },
"New title", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null);
String title = titleField.getText();
jComboBox2.addItem(title);
//as jComboBox2 is decalred in the applet above, it adds the string no problem.
But what I'd like is the following, a title class on its own to make it easier to update and modify,
e.g.
public void jButton5_actionPerformed(ActionEvent actionEvent) {
try {
Title title = new Title();
catch (Exception ex) {
ex.printStackTrace();
with the Title class written as such:
package name;
import statements;
class Title {
Title() {
//Set the new title
JFrame f = new JFrame();
f.setSize(200, 200);
f.setLocation(200, 200);
f.setVisible(false);
//Add those boxes to the JFrame
JTextField titleField = new JTextField();
String title = "Please enter the title";
int result = JOptionPane.showOptionDialog(f,
new Object[] { message },
"New title", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null);
String title = titleField.getText();
*** Here is the problem: How do I reference jComboBox2 which is declared in the original applet class?
jComboBox2.addItem(title); (this wont work!)
public static void main(String[] args) {
Title title = new Title();
I'd thought perhaps I needed to create an instance of the applet and pass it to the second class to use it, so it can reference the components, but I'm not sure how to do this with an applet.
Thanks
Maria

I'm not going to look at your unformatted code, but I'll give you some general hints:
Have one set of classes being the GUI
Have one set of classes being the data (the chat history, basically)
Have one set of classes being the logic
Have one interface for the logic to manipulate the data (e.g. addNewMessage(String)
Have one interface for the GUI to get the data that's to be displayed (e.g. getLastTenMessages())
Have one interface for the logic to notify the GUI of changed data (refresh())
Have one interface for the GUI to notify the logic of user input (e.g. sendMessage(String))
The logic will receive data either from the user and send it, as well as storing it in your chat log, or it will receive it from the network and add it to the data model, both times notifying the GUI of changes afterwards.

Similar Messages

  • How to Access MXML components  from ActionScript class

    Hi ,
    I am having a Application Conataner , in which i am having a Form Container with some Label in it .
    This is some thing similar to this as shown :
    <Mx:Application>
    <Mx:Form>
    <Mx:Label text="Hello world"/>
    </Mx:Form>
    </Mx:Application>
    Can any body please let me know how can i access this Form's Label , from an ActionScript class .
    catch(error:*)
    // Here i want to access these Objects and set data to that Label .
    Basically My requirement is that iinside the catch block of my ActionScript class , i want to set some text to the Label , Please
    let me know if this is possible or not also ??
    Waiting for your Replies .

    Hi these both are not same these refer to different one...
    Well let me explain...
    Application.application.myCustomComp.myLabel.text = "sometext"; sets the label "myLabel" which is present inside your customcomponent(which is in main application).
    Application.application.myLabel.text = "sometext"; sets the label "myLabel" which is present directly inside your main application.
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Label id="myLabel"  text=""/> // So inorder to set the label(myLabel) present here you will use directly the 2nd line of code.
    <mx:CustomComp id="myCustomComp" /> // So inorder to set the label(myLabel) present inside this component you use 1st line of code.
    </mx:Application>
    Hope now its clear.
    If this post answers your question or helps, please kindly mark it as such.
    Thanks,
    Bhasker Chari

  • How to access graphic components from classes?

    Hi,
    I am creating a Flex application. In my Main.mxml, I add
    different UI elements, such as panels. I also have a few
    actionscript files. Everything is in the same folder. So my
    question is : how can I access a panel created in Main.mxml from an
    actionscript class ? By accessing the panel, I mean things like
    change its properties, etc. Is it possible to access those in a
    'Flash-like' way, using something like _root.myPanel, or is it only
    possible through passing parameters?

    Well...it pains me to see someone obviously new to programming struggle here...so I'll take this one on:
    Here is the BAD way to do it...but it is basically what you are looking for...to learn GOOD ways to do this, please invest in some programming books and learn about encapsulation, MVC, and other programming/architectural styles...anyways...here is the BAD, but easy way:
    In your SGui class, right after the constructor you have to "declare" your object reference as a class member, so edit your file to make it say:
    public class SGui {
         public JButton addStickButton;Then, edit the line in SGui that says:
    final JButton addStickButton = new JButton();so that it just says:
    addStickButton = new JButton();Then, in your Soft class, you can access it just the way you wanted to in your comment:
    gui.addStickButton.setEnabled(false);Other Java programmers reading this thread will probably shoot me for showing you how to do it this way, because it violates principles of encapsulation...but go ahead and use it so you can move forward...but study a little more online or in books to get the hang of it :)
    Message was edited by:
    beauanderson
    Message was edited by:
    beauanderson

  • Updating Swing components from a different class

    I would like to use the JTextArea component in a JFrame to display fast updating text from my application. My application is very simple. When the app launches the GUI is created then my application engine would start processing and displaying text data into the GUI. After reading about Thread safety when using Swing components I concluded it would not be a good idea for my app engine class to update the JTextArea class directly using methods such as .append(String).
    I would be grateful for any suggestions on how I should approach updating Swing components from different classes.
    Many Thanks in advance Sean

    Hi
    Why don't you just implement a basic callback method?
    To do this the right way you should probably define a simple Interface that has a public method like updateProcessText(String s). Your swing class then implements this interface, basically forcing it to provide the public method you defined (this is no different than implementing ActionListener, which forces you to define actionPerformed). Secondly modify your processing class, so that it take's a class that implements the interface you just created, as one of the arguments in it's constructor. Lastly assign the argument from your construnctor to a private var - this will enable your processing class to have a handle to your swing class and update it as it pleases.
    This might sound very complex, but it's really simple once you've done it once.

  • Accessing XML data from a different class

    Hi all,
    I have an xml class that loads xml data, I need to access the data from another class. I have imported the xml classinto the new class and created a new instance of it. However when I try to access the xml data it is coming back as null. I understand this is almost certainly because when it is called the xml data hasn't completed it's load. How can I get round this?
    xml class:
    package {
        import flash.xml.*;
        import flash.events.*;
        import flash.net.*
        import flash.display.*
        public class xml extends MovieClip
            public var xmlRequest:URLRequest;
            public var xmlLoader:URLLoader;
            public var xmlImages:XML;
            public function xml()
                xmlRequest = new URLRequest("images.xml");
                xmlLoader = new URLLoader(xmlRequest)
                xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
                xmlLoader.load(xmlRequest);
            private function xmlLoaded(event:Event):void
                trace(xmlLoader.data);
                xmlImages = new XML(xmlLoader.data);
    Thanks in advance

    One of the ways:
    package {
         import flash.xml.*;
        import flash.events.*;
        import flash.net.*
        import flash.display.*
        public class XMLLoader extends EventDispatcher
              public var xmlRequest:URLRequest;
              public var xmlLoader:URLLoader;
              public var xmlImages:XML;
              public function XMLLoader()
              public function loadXML(url:String):void {
                   xmlLoader = new URLLoader()
                   xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
                   xmlLoader.load(new URLRequest(url));
              private function xmlLoaded(event:Event):void
                   trace(xmlLoader.data);
                   xmlImages = new XML(xmlLoader.data);
                   dispatchEvent(event);
    Usage:
    var xmlLoader:XMLLoader = new XMLLoader();
    xmlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
    xmlLoader.loadXML("images.xml"):
    function onXMLLoad(e:Event):void{
         trace(xmlLoader.xmlImages);

  • Accessing XI Components from SAP GUI

    hi folks,
    I was just wordering, can we Access XI Components(IR, ID, SLD..etc) from with in SAP GUI ,i.e. is there any transaction used to see XI components and can we build the Application from with in it...!!
    help and Suggestions wud be appreciated.
    Thanks
    Jeet.

    Hi,
    Refer to following weblog for quick transactions.
    /people/morten.wittrock/blog/2006/03/23/getting-started-with-xi-part-1-xi-30-cheat-sheet
    Thanks,
    Prateek

  • Accessing a thread from a main class, please help!

    Hi, I have a thread, T1, that I need to access from my main class. I cannot use runnable, it's got to be done with extands thread. I can start it alright, but I cannot stop it;
    MAIN CLASS
    public class Uppgift1 {
    public static void main(String args[]) throws InterruptedException {
    // Start Thread 1
         Thread trad1 = new T1( );
         trad1.start( );
         //Wait for 5 seconds
         Thread.sleep(5000);
         //Stop the Thread
         trad1.stopIt();
    public class T1 extends Thread {
         boolean go = true;
    public void run ( ) {
    while(go){
         System.out.println("T1: Trad 1");
    try{
    Thread.sleep(1000);
    } catch( InterruptedException e ) {
    public void stopIt(){
    go = false;
    Why can't I run stopIt from my main class?
    Please help me.

    manswide wrote:
    The reason I have to use Thread is that it's for a school thing; I guess I gotta learn to do it the bad way in order to learn why to love the good way later on.Good plan. Making mistakes is a fantastic learning tool
    How do I declare a reference to my own class?
    T1 t1 = new T1();

  • Event handlers execute code from a seperate class

    i am having difficulties linking my event handlers to another piece of code in a seperate class. basically i want my event handler to execute a code which is in another class. how do i do this?

    while adding listener to the component for which u want to handle event add listener with the name of class where u r going to write the event handling code and declare that class as implementing the type of listener and handle the event in that class by implementing the definitions for the methods in the interface

  • Accessing EJB components from a Remote Client

    Hi,
    When an web component (Servlet/JSP/Java appl.) need to invoke an business method from an EJB, it first lookup for the registered name from the Application server and obtain the remote reference i.e. the EJB Remote interface. To do this, the client must have got the client-jar file containing the stub. Now, if in a distributed environment, my client is in a different machine and need to access the J2EE server across network, what would be the scenereo.
    Is it so, for every EJB the client need to call, it must have got the client-jar file in it's local classpath ? this seems to be not at all feasible.
    Is it so, the client loads the Stub acroos the network while obtaining the remote reference ?
    Please inform me, what actually happens when a client invokes a EJB call deployed in any application server, across the network !!!
    Regards,
    Kaustuv Bhattacharya

    Greetings,
    Hi,
    When an web component (Servlet/JSP/Java appl.) need to
    invoke an business method from an EJB, it first lookup
    for the registered name from the Application server
    and obtain the remote reference i.e. the EJB Remote
    interface. To do this, the client must have got the
    client-jar file containing the stub. Now, if in aFor web components running in the same application context, the client-jar is not required - the server-jar also contains the necessary stubs. However, for application clients, the client-jar is required...
    distributed environment, my client is in a different
    machine and need to access the J2EE server across
    network, what would be the scenereo.The client-jar must be distributed with your application, or accessible from a shared network resource, either way...
    Is it so, for every EJB the client need to call, it
    must have got the client-jar file in it's local
    classpath? this seems to be not at all feasible.Yes, the client-jar must be included in the client's classpath... Why isn't it feasible? The client-jar(s) can easily be distributed with your application. The necessity to include them in the application's CLASSPATH does not necessitate their inclusion into the client-machine's CLASSPATH. Simply include the jar(s) as part of the JVM's -cp option.
    Is it so, the client loads the Stub acroos the network
    while obtaining the remote reference?A copy of the remote interface's stub file is included for casting purposes. However, a copy of the stub containing the correct communication parameters (such as TCP/IP port number, reference ID, etc. per vendor implementation...), for the remote reference does get downloaded.
    Please inform me, what actually happens when a client
    invokes a EJB call deployed in any application server,
    across the network !!!The exact details are vendor specific and depends on the actual protocol in use by the stub-layer. However, the general behaviour is in-line with RMI(-IIOP) communication.
    Regards,
    Kaustuv BhattacharyaRegards,
    Tony "Vee Schade" Cook

  • Access jar file from in-memory classes...

    I have some classes that I compile to memory and everything works fine until one class that must access some external jar files. I have been unable to access those jar files from disk after trying every suggestion using URLClassLoader. I even tried someone's example to hack the SystemClassLoader which properly adds the jar file paths, but still they can't be seen. The only way it works is if I put the files in the jdk/jre/lib/ext directory. Then everything works fine. There must be a way to load the jar files in memory as well as the class files so they can be accessible. Has anyone done anything like this? Is it possible? Even though the class files are in memory, why would the jar files not be seen even when they are added to the same URLClassLoader's URL's. Thanks.

    Sorry that wasn't clear. What I mean is that the classes are compiled to byte code directly to memory and no physical .class file is created. Yes, I'm using my own ClassLoader that extends URLClassLoader and I'm setting the parent to ClassLoader.getSystemClassLoader(). I also should mention that I'm doing this inside a Netbeans module that is part of a Netbeans Platform application. I don't know why that should matter though, since I'm trying to do everything in memory without creating the physical files. Thanks.

  • How to access getter/setters from the entity classes

    Let me brake my question to two:
    1. in My JSP page, I need to get an exception from either the entity or the view class if I insert a duplicate value into the associated table. How can I do that?
    2. How can I access the entity's getter/setter functions in the JSP page?
    Thank you

    Let me brake my question to two:
    1. in My JSP page, I need to get an exception from either the entity or the view class if I insert a duplicate value into the associated table. How can I do that?You can mark the attribute as unique key attribute and choose to implement the unique-key validation in the Bc4J side. See help on UniqueKey and how to establish such validation
    2. How can I access the entity's getter/setter functions in the JSP page?You cannot access entities directly. You have to expose the accessors via ViewObject Rows and use those Rows from the JSP/or any client side.
    Thank you

  • Accessing String variables from several JAVA classes

    Hi.
    I have several java classes that accesses the same String variables. Instead of putting the String declarations in every java files, how can I put these declarations in a single file source, and get each java class to get the variables data from this file ?
    Please advice.
    Thanks.

    hi, of course you can solve it by the following methods:
    Method 1. define a superclass including the common string variable, and extend other classes from the superclass.
    Method 2. define a class , and define your common string variable as a static variable in it. In your other classes, you can call the string variable.
    Method 3. define it at your each classes.

  • Accessing a method from an outside Class

    I am working on a program that will create an array list and hashmap of 3 shapes--squares,triangles and circles. I have created classes for each shape as well as a class that creates arrays of these shapes (called ShapeGenerator).
    Now I need to create a class that will call ShapeGenerator to create the shapes and then put them into an arraylist and hashmap. Right now I just can't get seem to call the methods from ShapeGenerator to create the arrays. What follows is the code I've written. Any guidance would be appreciated. Thanks in advance...
    public class ShapeMaker{
         public ShapeMaker(){
    public ShapeGenerator[] makeShapes(){
         ShapeGenerator[] myShapeGenerator = new ShapeGenerator();
         myShapeGenerator.createSquares(5);
         return createSquares;
    public static void main(String[] args){
         ShapeMaker mySM = new ShapeMaker();
         mySM.makeShapes();
         System.out.println("I made a Shape");
    }

    ShapeGenerator[] myShapeGenerator = new ShapeGenerator();
    new ShapeGenerator will return a single instance of ShapeGenerator - Not an array.
    to create a new ShapeGenerator:
    ShapeGenerator sg=new ShapeGenerator();
    then your method call:
    Object squares[]= sg.createSquares(5);
    or you could just do:
    Object squares[]=new ShapeGenerator().createSquares(5);
    makeShapes() should then return an array of Object (or even better do you have a base Shape class?)
    So we finally end up with something like:
    public class ShapeMaker{
    public ShapeMaker(){
    public Object[] makeShapes(){
    ShapeGenerator myShapeGenerator = new ShapeGenerator();
    return myShapeGenerator.createSquares(5);
    public static void main(String[] args){
    ShapeMaker mySM = new ShapeMaker();
    mySM.makeShapes();
    System.out.println("I made a Shape");
    Excuse any typos but I have not tried to compile this as I don't have a myShapeGenerator etc and I'm too tired (or lazy) to write one.
    Good luck.

  • Accessing a movie from another movie (class)

    Hi all!,
    Ok, this is a little bit complicated to explain, but I will
    try my best. First, please click on the link below to see the
    mockup that I did:
    Link
    to mockup
    Now for some explanation:
    First of all, the Flash makes use of an XML file to grab some
    data. This part was freakin complicated and it's actually a
    programmer who helped me with that but he is very unfamiliar with
    AS on the whole so he couldn't really help me with the rest. OK so
    basically in the first frame I am loading the XML, then what you
    are seeing on the stage is in frame 2.
    on the stage there are 2 movies:
    1. scrollPane_mc
    2. cables_mc
    For now you can check and uncheck the items in the scroll
    pane and you can roll over the cables to see their names.
    1. scrollPane_mc
    scrollPane_mc is a scroll pane component that has a movie
    called cableList_mc as source.
    cableList_mc itself is an empty movie with just 1 frame and
    which dynamically grabs a movie called cableListItem_mc (itself
    attached to a class of the same name) from the library and
    duplicates it, based on data from the XML file.
    code in cableList_mc:
    var startY:Number = -0.8;
    for (var cableName:String in VPN_Utils.cables) {
    var listItem:cableListItem_mc = new cableListItem_mc();
    listItem.name = cableName;
    listItem.x = 0;
    listItem.y = startY;
    listItem.cableNameText.text =
    VPN_Utils.cables[cableName][0];
    addChild(listItem);
    startY += 18;
    code for cableListItem_mc.as (1 cableListItem_mc is basically 1
    checkbox item):
    package {
    import flash.display.*;
    import flash.events.*;
    import flash.text.TextField;
    import VPN_Utils;
    public class cableListItem_mc extends MovieClip {
    private var checked:Boolean = true;
    public function cableListItem_mc() {
    addEventListener (MouseEvent.MOUSE_DOWN, swap);
    private function swap(e:MouseEvent):void {
    if (checked) {
    this.gotoAndStop(2);
    } else {
    this.gotoAndStop(1);
    checked = !checked;
    trace (this + " " + this.name + " is " + checked);
    2. cables_mc
    cables_mc on the other hand just contains several movie
    clips, placed manually on the stage and all of them based on the
    class VPN_Cable.as
    code for VPN_Cable.as:
    package {
    import flash.display.*;
    import flash.events.*;
    public class VPN_Cable extends MovieClip {
    public function VPN_Cable() {
    addEventListener (MouseEvent.MOUSE_OVER, onMouseOver);
    addEventListener (MouseEvent.MOUSE_OUT, onMouseOut);
    private function onMouseOver(e:MouseEvent):void {
    text_mc.visible = true;
    private function onMouseOut(e:MouseEvent):void {
    text_mc.visible = false;
    So basically now what I want to achieve is to control and
    talk to the cables from the scroll pane. So when I uncheck "Cable
    1" in the scroll pane, "Cable 1" on the stage should turn invisible
    for example.
    I hope this is clear....
    Thanks a lot! in advance!
    jon.

    Hi kglad!
    uhhh, thnx a lot for u reply =] but it's not exactly this
    that i'm looking for. Well yeah, i know i have to assign mouse
    listeners to my checkboxes (....) (and I already have actually),
    but could you give some details about that? That would help
    greatly. My problem is that I don't know how to talk to the cables
    (which are in a separate movie) from the checkboxes (which are in
    yet another movie).
    Thanks!
    And happy new year!
    jon.

  • How to access static variable from a Thread class

    Kindly help me.......
    here's the code.....
    class Thread1 extends Thread
    int j=0;
    myClass2 mc = new myClass2();
         public void run()
              for( int a=0;a<6;a++)
                        {try
                             { Thread.sleep(5000);
                             catch(Exception e){System.out.println("Interrupted Exception");}
                             j++;
    mc.change1(i);
    } System.out.println("Thread1 executes "+j+" times");
    class Thread2 extends Thread
    int k=0;
         myClass2 mc1 = new myClass2();
         public void run()
              for( int a=0;a<6;a++)
                        {try
                             { Thread.sleep(5000);
                             catch(Exception e){System.out.println("Interrupted Exception");}
                             k++;
    mc1.change2(i);
    }System.out.println("Thread2 executes "+k+" times");
    class myClass2
    static int i=5;
    public synchronized void change1(int s)
    s=6;
    System.out.println("New value of i:"+s);
    public synchronized void change2(int s)
    s=7;
    System.out.println("New value of i:"+s);
         public static void main(String args[])
    Thread1 b1 = new Thread1();
    Thread2 b2 = new Thread2();
         b1.start();
    b2.start();
    I am unable to pass the variable i in my method call in Thread1: mc.change1(i); and similarly in Thread2:mc.change2(i);

    You can declare your i variable in myClass2 as public static and then simply call there
        mc.change1( myClass2.i ) ;

Maybe you are looking for