How to get change a GUI component from another class?

Hi there,
I'm currently trying to change a GUI component in my 'Application' class from my 'Dice' class.
So the Application class sets up some GUI including a JLabel that initially displays "Change".
The 'Dice' class contains the ActionPerformed() method for when the 'Change' button (made from Application class) is clicked.
And it returns an 'int' between 1 and 6.
Now I want to set this number back int he JLabel from the Application class.
APPLICATION CLASS
import javax.swing.*;
import java.awt.*;
import java.util.Random;
import java.awt.event.*;
public class Application extends JFrame implements ActionListener{
     public JPanel rollDicePanel = new JPanel();
     public JLabel dice = new JLabel("Loser");
     public Container contentPane = getContentPane();
     public JButton button = new JButton("Change");
     public Dice diceClass = new Dice();
     public Application() {}
     public static void main(String[] args)
          Application application = new Application();
          application.addGUIComponents();
     public void addGUIComponents()
          contentPane.setLayout(new BorderLayout());
          rollDicePanel.add(dice);
        button.addActionListener(diceClass);
        contentPane.add(rollDicePanel, BorderLayout.SOUTH);
        contentPane.add(button,BorderLayout.NORTH);
          this.setSize(460, 655);
          this.setVisible(true);
          this.setResizable(false);
     public void changeDice()
          dice.setText("Hello");
     public void actionPerformed(ActionEvent e) {}
}DICE
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Dice implements ActionListener
     public Dice() {}
     public void actionPerformed(ActionEvent e)
          //super.actionPerformed(e);
          String event = e.getActionCommand();
          if(event.equals("Change"))
               System.out.println("Will be about to change the 'dice' label");
               Application application = new Application();
               application.dice.setText("Hello");
}

It's all about references, baby. The Dice object needs a way to communicate with the Application object, and so Dice needs a reference to Application. There are many ways to pass this. In my example I pass the application object directly to Dice, but a better way would use interfaces and some indirection. Look up the Observer pattern for a better way to do this that scales much better than my brute-force approach.
import javax.swing.*;
import java.awt.*;
public class Application extends JFrame // *** implements ActionListener
    // *** make all of these fields private ***
    private JPanel rollDicePanel = new JPanel();
    private JLabel dice = new JLabel("Loser");
    private Container contentPane = getContentPane();
    private JButton button = new JButton("Change");
    // *** pass a reference to your application ("this")
    // *** to your Dice object:
    private Dice diceClass = new Dice(this);
    public Application()
    public static void main(String[] args)
        Application application = new Application();
        application.addGUIComponents();
    public void addGUIComponents()
        contentPane.setLayout(new BorderLayout());
        rollDicePanel.add(dice);
        button.addActionListener(diceClass);
        contentPane.add(rollDicePanel, BorderLayout.SOUTH);
        contentPane.add(button, BorderLayout.NORTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(460, 655));
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    // *** I'm not sure what this is supposed to be doing, so I commented it out.
    //public void changeDice()
        //dice.setText("Hello");
    // *** ditto.  I strongly dislike making a GUI class implement ActionListeenr
    //public void actionPerformed(ActionEvent e)
    // *** here's the public method that the Dice object calls
    public void setTextDiceLabel(String text)
        dice.setText(text);
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Dice implements ActionListener
    // *** have a variable that holds a reference to your application object
    private Application application;
    private boolean hello = true;
    public Dice(Application application)
        // *** get that reference via a constructor parameter (one way to do this)
        this.application = application;
    public void actionPerformed(ActionEvent e)
        String event = e.getActionCommand();
        if (event.equals("Change"))
            System.out.println("Will be about to change the 'dice' label");
            if (hello)
                // *** call the application's public method
                application.setTextDiceLabel("Hello");
            else
                application.setTextDiceLabel("Goodbye");
            hello = !hello;
            //Application application = new Application();
            //application.dice.setText("Hello");
}

Similar Messages

  • How to get  value on jsp file from ActionServlets class

    Hi All,
    I am facing problem in action servlets class into Struts, I am able to get the value on jsp file from action class with the help of session scope but i want to another method for it , so how i can solve the problem.Plz help me
    Thanks......... in advance

    I got a way out to access the attribute, i feel it is
    <jsp:usebean id="myRack" class="settings.Rack"/>
    <c:foreach var="book" item="myRack.books">
    </c:foreach>
    I am not able to check if this is correct or not because myRack.books is not having any value set by me in the request scope. How do i get instance of Rack class set by another page in the current request? I can get the value if i use scriptlet but i dont want to use scriptlet.
    I am continiously trying, if I get an answer, I shall post, else pls somebody guide.

  • How to get properties of a bean from another java class

    Hi,
    I am new to JSF. Currently I am facing a problem, and hope you experts can give me some guidance.
    The JSF app i am working on has one Java class for handling a tree structure, MyTreeNode.java, and it also has a bean, NameBean.java, which has two properties, username and password.
    I can easily associate an input text with the #{name.username} to store the user's login... but later on, I need to fetch that information inside of MyTreeNode.java. How do I do that? Thanks!
    -- Jim

    <managed-bean>
         <managed-bean-name>Person</managed-bean-name>
         <managed-bean-class>demo.PersonBean</managed-bean-class>
         <managed-bean-scope>session</managed-bean-scope>
         <managed-property>
              <property-name>bank</property-name>
              <property-class>demo.BankBean</property-class>
              <value>#{bank}</value>
         </managed-property>
    <managed-bean>
    <managed-bean>
         <managed-bean-name>bank</managed-bean-name>
         <managed-bean-class>demo.BankBean</managed-bean-class>
         <managed-bean-scope>session</managed-bean-scope>
    <managed-bean>this version doesnt work for me.
    does the single beans have to look any special?
    some demo code out there?
    thx!

  • How to get JSP to include content from another WAR

    I'm writing a group of web applications that are all going to be run out of the same web server with the same domain name. Since these applications are all independent, I want to give them separate wars.
    I've created a directory application that lets the user create an account, log in, and pull up a listing of each of the other applications on the server. However, rather than just posting a hyperlink to each of the other apps, I'd like to call a custom .jspf in the respective wars so that they can return a block of HTML that gives a richer user experience (the HTML will contain some formatted text that describes the link, given the user ID and a couple of other parameters).
    Anyhow, jsp:include seems to have me sandboxed inside my directory app. <jsp:include page="../MyOtherApp/link.jspf"/> causes an error. Is there someway I can have my directory call custom pages in my other wars and include the results in the generated webpage?

    use <%@include file="../MyOtherApp/link.jspf" %>

  • How to display values in textfields obtained from another class

    Hi,
    Why, oh why, doesn't this work:
    When I select a row in my tableClass (consist of a JTable) I want to display these values (strings) in my TextFieldGUI class (consist of just JTextFields). My code looks like this:
    TableClass:
    public void mouseClicked(java.awt.event.MouseEvent mouseEvent) {
        textFieldGUI = new TextFieldGUI() ;//reference to my textfield class
        gui = new mainGUI() ; //reference to my GUI class
        int tabbedIndex = gui.getSelectedIndex() ;
        int col = tableModel.getColumnCount() ;
        Vector string = new Vector() ;
        String empty = "" ;
        for(int index = 0; index < col ; index++){
            if(table.getValueAt(row, index) == null)
                string.addElement(empty) ;
            else
                string.addElement(table.getValueAt(row, index).toString()) ;
        if(tabbedIndex == 0){       
            System.out.println(string) ; //works fine
            textFieldGUI.setTextFieldValues(string) ;
    }TextField class:
    public void setTextFieldValues(Vector s){
        Vector string = new Vector() ;
        string = s ;
        System.out.println("TextFieldVector: " + string) ; //works fine as well
        String name = "" ;
        String dob = "" ;
        String web = "" ;
        name = string.elementAt(0).toString() ;       
        dob = string.elementAt(1).toString() ;       
        web = string.elementAt(2).toString() ;
        System.out.println("NAME: " + name +
                           ", BIRTH: " + dob +
                           ", WEB: " + web) ; //values are correctly printed
        txtName.setText(name) ; //writes nothing (empty)
        txtDob.setText(dob) ; //writes nothing (empty)
        txtWeb.setText(web) ; //writes nothing (empty)
    }Anyone got a hint on how I should svolve this one?
    thanks
    gmtongar

    Hi
    my problem is, for each job_id there is many users. Oh that's something completlty different...
    I Strongly Recommand to_
    1.*create 2 tables Jobs & users*
    2.*create a relation between them* 1 to many to get for each job more than a user that's the way that Must be -- execuse me the bad design of the db pulled u into this trap -
    3.then u can deal with it normally no need to a sample code but just a form with Jobs as  (Master) and Users as (detail) with a relation and with a simple query u can display each job_id is for many users.
    no null values no commas r needed.
    Hope this helps...
    Regards,
    Amatu Allah.

  • How do I change my user id from dsgence to dsgrence? Under the menu / title I keep getting where you would see a pop-up message title "know your rights" how do I get rid of that also?

    How do I change my user name from dsgence to dsgrence? Under the title bar where you would see pop-ups a message "know your right" keeps coming up every time I reboot?

    You can post a request in the contributors forum if you want to change the user name.
    *https://support.mozilla.org/en-US/forums/contributors
    Add [ATTN ADMIN] in front of the subject title to get the attention of a forum Administrator.
    See also:
    *http://kb.mozillazine.org/Preferences_not_saved
    *https://support.mozilla.org/kb/Preferences+are+not+saved

  • How to get back deleted software component along with underlaying objects.

    Dear Experts,
    By mistake i deleted my software component. When i deleted it even doesn't ask for activate. When i check in change list there is no change list for that deleted software component. So request you please let me how to get back my software component with all the namespaces and objects.
    Please treat this as high priority and revert me back ASAP.
    Thanks in advance.
    HAri.

    I don't know if is possible to restore a deleted SoftComp and all dependent object in repository... You can try to renew the SoftComp import from SLD....

  • How to get changed data in ALV in Web Dynpro for ABAP

    METHOD on_data_check .
    DATA:
        node_spfli                          TYPE REF TO if_wd_context_node,
        node_sflight                        TYPE REF TO if_wd_context_node,
        itab_sflight2                        TYPE if_display_view=>elements_sflight.
      node_spfli = wd_context->get_child_node( name = if_display_view=>wdctx_spfli ).
      node_sflight = node_spfli->get_child_node( name = if_display_view=>wdctx_sflight ).
      CALL METHOD node_sflight->get_static_attributes_table
        IMPORTING
          table = itab_sflight2.
    this code is ..get all data(changed and not changed)
    but i want get changed data only, not all data.
    how to get changed data?
    Edited by: Ki-Joon Seo on Dec 27, 2007 6:04 AM

    Hi,
    To get only the changed data in the ALV grid of a WD, you need to capture the "ON_DATA_CHECK" of the ALV grid.
    To this please do the following in the ALV initialization of the ALV table settings :
        lr_table_settings->set_data_check(
                IF_SALV_WD_C_TABLE_SETTINGS=>DATA_CHECK_ON_CELL_EVENT ).
    You may also do this:
        lr_table_settings->set_data_check(            IF_SALV_WD_C_TABLE_SETTINGS=>DATA_CHECK_ON_CHECK_EVENT)
    The above two ways would depend on when do you need to check for the changed data. If you want to check the data as soon as it is entered, then use the first method. Else, use the second method.
    You need to register an EVENT HANDLER for this event.(You may do this in your VIEW or Component Controller).
    In this Event handler, you would find an importing parameter R_PARAM which is a ref type of      IF_SALV_WD_TABLE_DATA_CHECK.
    The attribute T_MODIFIED_CELLS of this interface IF_SALV_WD_TABLE_DATA_CHECK will contain the modified cells of the ALV with the old & new values.

  • How can i change My app store from USA To Sweden?

    How can i change My app store from USA To Sweden?

    If you are getting an 'account not in this country' message then try going to the bottom of the Featured tab in the App Store app on your iPad and tap on your account id, tap on 'View Apple ID' on the popup and log into your account, and then select the Country/Region section and select Sweden.

  • How do i change my itunes settings from Australian to NZ ?

    How do i change my itunes settings from Australian to NZ ?

    If you are getting an 'account not in this country' message then try going to the bottom of the Featured tab in the App Store app on your iPhone and tap on your account id, tap on 'View Apple ID' on the popup and log into your account, and then select the Country/Region section and select New Zealand.
    If you have moved to New Zealand and want to update your details then you might be able to update your billing address by tapping on your id in Settings > iTunes & App Store on your phone and logging into it, or you can do it via the Store > View Account menu option on your computer's iTunes. If you have a credit card on your account then it will need to have been issued by a New Zealand bank and be registered to your address there.

  • HT1766 HOW CAN I CHANGE MY BACKUP FOLDER FROM THE C DRIVE TO ANOTHER?????

    HOW CAN I CHANGE MY BACKUP FOLDER FROM THE C DRIVE TO ANOTHER????? because my c drive in the windows computer gets filled and i need to back up my ipod to a portable hard disk.. bt i dont know how to do it.. plz help

    you can't change the backup folder as far as I know, but you can choose to move backups. The information you need can be found in this article: http://support.apple.com/kb/ht4946
    Where iTunes backups are stored on your computer
    The folder where your backup data are stored varies depending on the computer's operating system.   Make sure the backup folder is included in your periodic data-backup routine.
    iTunes places the backup files in the following places:
    Mac:  ~/Library/Application Support/MobileSync/Backup/
    Windows XP:  \Documents and Settings\(username)\Application Data\Apple Computer\MobileSync\Backup\
    Note: To quickly access the Application Data folder, click Start, and choose Run. Type %appdata% and click OK.
    Windows Vista and Windows 7:  \Users\(username)\AppData\Roaming\Apple Computer\MobileSync\Backup\
    Note: To quickly access the AppData folder, click Start. In the search bar, type %appdata% and press the Return key.
    Hope this helps
    Regards,
    Stijn

  • How to get the list of component?

        How to get the list of component through java API in Adobe CQ5?

    There are probably more than a few ways, but here is a little component .jsp code that uses the jcr query api to pull out all the components and list them on a page.  If I know CQ, there might be a way to ask for a list of components another way though, maybe through another API, or possibly a .json url, I might remember reading something about that, somewhere, lol, but this at least gets you the list in a somewhat simple way.
    Code Example:
    <%@include file="/apps/psul/components/global.jsp"%>
    <%@ page import="javax.jcr.*,
                       javax.jcr.query.*"
    %>
    <%
       // Login to create an anonymous session on the default workspace
       Session session = resourceResolver.adaptTo(Session.class);
           //Declare a query for all the components in the system
           String SQL = "select * from cq:Component";
    //side note: if you want just the components in your site area, then make the query more like below...
    //  SQL = "select * from cq:Component where jcr:path like '/apps/yoursitename/%'";
           QueryManager qm = session.getWorkspace().getQueryManager();
           Query query = qm.createQuery(SQL, Query.SQL);
           QueryResult result = query.execute();
           NodeIterator nodes = result.getNodes();
           while (nodes.hasNext()) {
               Node node = (Node)nodes.next();
               %>
                    <p><%=node.getName() %> (<b><%=node.getPath() %></b>)</p>
    <%     } %>

  • How to get the default selection color from JTable

    Hi, there,
    I have a question for how to get the default selection color from JTable. I am currently implementing the customized table cell renderer, but I do want to set the selection color in the table exactly the same of default table cell renderer. The JTable.getSelectionBackgroup() did not works for me, it returned dark blue which made the text in the table unreadable. Anyone know how to get the window's default selection color?
    Thanks,
    -Jenny

    The windows default selection color is dark blue. Try selecting any text on this page. The difference is that the text gets changed to a white font so you can actually see the text.
    If you don't like the default colors that Java uses then use the UIManager to change the defaults. The following program shows all the properties controlled by the UIManager:
    http://www.discoverteenergy.com/files/ShowUIDefaults.java
    Any of the properties can be changed for the entire application by using:
    UIManager.put( "propertyName", value );

  • How to delete/remove the software component from integration repository

    Dear All
    How to delete/remove the software component from integration repository which we have created some Data and message types.
    Regards
    Blue

    Hi,
      Follow the steps below to delete the Software component:
    1. Delete the created Data Types, Message Types, Message Interfaces, Message Mappings, Interface Mappings and other imported objects like RFC's or IDoc's. Activate all changes.
    2. Then delete the namespace and the default datatypes present with the namespace after checking "objects are modifiable".
    3. Then delete the SW component, after placing the radio button in "Not permitted".
    Regds,
    Pinangshuk.

  • Premiere Elements 4.0 - How do I change all the clips from 5 seconds to 2 seconds in length?

    Premiere Elements 4.0 - How do I change all the clips from 5 seconds to 2 seconds in length?

    Christine,
    The Duration of Stills is set with Edit>Preferences to the number of Frames required, where ~ 30 Frames = 01 sec. of Duration.
    Unfortunately, the Duration cannot be reset (Edit>Preferences) for material that has already been Imported. The procedure is to Delete those Imported Stills, and make the change, then re-Import them, and you will get the Duration that you have reset.
    The only other option at this point is to manually Click-drag on the Head, or Tail of each Still in the Timeline, to adjust the Duration. I do this with the Info Panel open and visible to make it easier. Personally, unless I am well into the editing process, the Delete, change and re-Import option is my choice.
    Good luck,
    Hunt
    PS - the ability to alter the Duration en masse for Imported Stills in the Project Panel has just been added in PrPro CS5. I do not know if it has been added in PrE 9 though.

Maybe you are looking for

  • IPhoto '08 loses exif data when exporting RAW to JPG

    I'm using a Canon 40D shooting only RAW. I just recently noticed that when I export to JPG, iPhoto loses quite a bit of important EXIF data, including, aperture info. Is this a known issue, or is it something unique to my system?

  • BAPI for F-30 / F-36

    Hi everybody, I need a BAPI to post documents like F-30 and F-36 (closing open items). Do anybody know wich is the rigth one ? Regards PabloX.

  • Performance Tuning Certification for Application Developer

    Hi, Can you please advise if there is any Oracle Performance Tuning certification for an Application Developer and Oracle 9i to 10G migration certification? If yes, can you please let me know its Oracle examination number? I have already passed 1Z0-0

  • Project library - audio

    What does the little icon (next to all of my projects) in the project library window mean? It has what looks like an audio symbol and an exclamation mark in a small triangle.

  • LinkSys E2500 Internet Problems

    Hello, I've recently bought an E2500 Wireless Router for my home, but every 1-2 days I've been having an issue.  The internet connection will suddenly drop. Upon checking the "Internet Connection" information, under "Status" I see that the internet I