Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Can't set label text from a Jbutton

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Can't set label text from a Jbutton

    Hello all,

    I have the following code. I would like to be able to set the text in the label (called label) to something else when a user click the close button.

    I am guessing that my action class does not know what label is but I'm not sure how to reference since its in another class.

    Thanks!!
    VBGuy



    package test;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public class Main {
     
        public static void main(String[] args) {
            ShowFrame();
        }
     
        public static void ShowFrame() {
     
            JFrame MyWindow = new JFrame("Hello World");
            MyWindow.setSize(800, 600);
            MyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MyWindow.setLayout(null);
     
            //Label
            JLabel label = new JLabel("Hello World!");
            label.setBounds(200, 10, 100, 25);
     
            //Text Field
            JTextField bbox = new JTextField(16);
            bbox.setBounds(10, 10, 100, 25);
     
            //Add Buttons
            JButton CloseButton = new JButton("Close");
            CloseButton.setBounds(10, 100, 90, 40);
     
            JButton OkButton = new JButton("Ok");
            OkButton.setBounds(100, 100, 90, 40);
     
            //Add to Frame
            MyWindow.add(CloseButton);
            MyWindow.add(bbox);
            MyWindow.add(OkButton);
            MyWindow.add(label);
     
            //Set Visible
            MyWindow.setVisible(true);
            bbox.setVisible(true);
            CloseButton.setVisible(true);
            OkButton.setVisible(true);
     
            //Set Action Listener
            CloseButton.addActionListener(new Action());
     
        }
    }

    package test;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public class Action implements ActionListener {
     
        public void actionPerformed(ActionEvent e) {
            label.setText("You Clicked Close!");
     
        }
    }


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Can't set label text from a Jbutton

    Yes, your intuition is correct. Action has no idea what label is. The easiest way to solve this problem is to pass label to it when it's being constructed:

    public class Action implements ActionListener
    {
        private JLabel label;
        public Action(JLabel label)
        {
            this.label = label;
        }
     
        public void actionPerformed(ActionEvent e)
        {
            label.setText("You Clicked Close!");
        }
    }

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    VBGuy (July 8th, 2010)

  4. #3
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Can't set label text from a Jbutton

    Quote Originally Posted by helloworld922 View Post
    Yes, your intuition is correct. Action has no idea what label is. The easiest way to solve this problem is to pass label to it when it's being constructed:

    public class Action implements ActionListener
    {
        private JLabel label;
        public Action(JLabel label)
        {
            this.label = label;
        }
     
        public void actionPerformed(ActionEvent e)
        {
            label.setText("You Clicked Close!");
        }
    }

    Thanks Helloworld but I get an error when I try to run the code after your changes.

    I get 'cannot find symbol'

    Any thoughts?

    Thanks!

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Can't set label text from a Jbutton

    I get an error
    Please copy and paste full text of the error message here.
    What symbol?

  6. #5
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Can't set label text from a Jbutton

    Thank you both for all the help!!

    I have attached a screenshot of the error that now comes up.

    I am assuming this is the problem:

        public Action(JLabel label)
        {
            this.label = label;
        }

    If I remove it then I can compile and run (and crash) but it does compile.

    Is there no other way to reference the label object (or any object for that matter)?

    Thanks!!
    Attached Images Attached Images
    Last edited by VBGuy; July 8th, 2010 at 09:02 AM.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Can't set label text from a Jbutton

    If you are getting compile errors, you must copy and paste them here. We're not able to see them otherwise.

  8. #7
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Can't set label text from a Jbutton

    Quote Originally Posted by VBGuy View Post

    Is there no other way to reference the label object (or any object for that matter)?
    As far as referencing other object, you can pass reference to the class as shown above, or alternatively create an inner class (or inner anonymous class) which has access to the holding class variables (this can be useful in quite a few ways, but at times can create a mess as well)

     
    public class MyClass{
        JLabel label = new JLabel();
        JButton button = new JButton("press here");
        ////
         public MyClass(){
           //set up things
           button.add(new ButtonListener());//inner class example
            button.add( new ActionListener(){///inner anonymous class example
                  public void actionPerformed(ActionEvent e){
                        System.out.println("Button was pressed");
                        MyClass.this.label.setText("Changed");
                  }
            });
           ///note now 2 action listeners are registered on button
          }
        /**
        * Inner class 
        */
        private class ButtonListener implements ActionListener{
             public void actionPerformed(ActionEvent e){
                    System.out.println("Button was pressed");
                    MyClass.this.label.setText("Changed");
             }
        }
     
    }

    The error you see above is because you do not pass the label into the constructor of Action
    Last edited by copeg; July 8th, 2010 at 09:20 AM.

  9. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Can't set label text from a Jbutton

    Quote Originally Posted by VBGuy View Post
    Thanks Helloworld but I get an error when I try to run the code after your changes.

    I get 'cannot find symbol'

    Any thoughts?

    Thanks!
    Since the action listener class now has a constructor provided, you must use this constructor.

            //Set Action Listener
             // this is using the wrong constructor!
            // CloseButton.addActionListener(new Action());
            // correct constructor
            CloseButton.addActionListener(new Action(label));

  10. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Can't set label text from a Jbutton

    What package does your Action class come from? I can only see an interface in javax.swing.
    If you're making your own class, it'd be better not to use one of Sun's

Similar Threads

  1. java program to copy a text file to onother text file
    By francoc in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: April 23rd, 2010, 03:10 PM
  2. JButton help
    By tabutcher in forum Java Applets
    Replies: 4
    Last Post: March 9th, 2010, 07:04 PM
  3. JButton Help
    By ravjot28 in forum AWT / Java Swing
    Replies: 3
    Last Post: January 17th, 2010, 11:38 AM
  4. JButton...
    By chronoz13 in forum AWT / Java Swing
    Replies: 1
    Last Post: November 27th, 2009, 11:39 AM
  5. centering a label inside a rectangle
    By Brain_Child in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 19th, 2009, 09:08 AM