Results 1 to 16 of 16
Like Tree1Likes
  • 1 Post By PhHein

Thread: problems with jbutton/actionlistener

  1. #1
    nirro is offline Member
    Join Date
    Sep 2013
    Posts
    6
    Rep Power
    0

    Default problems with jbutton/actionlistener

    hi.. i am new to gui and i have some trouble.
    i'm trying to create button that change background color to random color.
    this is what i have done:

    Java Code:
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.Random;
    import javax.swing.*;
    
    
    public class Mainp extends JFrame 
    {	
    private ImageIcon image1;
    private JLabel label1;
    private JButton startbutton;
    
    
    public void rndbackground()
    {
    Random rand = new Random();
    float r = rand.nextFloat();
    float g = rand.nextFloat();
    float b = rand.nextFloat();
    Color randomcolor=new Color(r,g,b);
    getContentPane().setBackground(randomcolor); 
    }
    
    public void creation() 
    {
    	setLayout(new FlowLayout());
    	image1= new ImageIcon(getClass().getResource("sun_2.png"));
    	label1=new JLabel(image1);
    	startbutton = new JButton("Start");
    	add(label1);
    	add(startbutton);
    }
    
    Mainp()
    {
    creation();
    rndbackground();
    }
    
    public static void main(String[] args)
    {
    Mainp gui= new Mainp();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setVisible(true);
    gui.pack();
    gui.setTitle("title");
    }
    }

    when i change
    Java Code:
    public class Mainp extends JFrame
    to
    Java Code:
    public class Mainp extends JFrame implements ActionListener
    it make errors and doesn't recognize it.. what to do?

  2. #2
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: problems with jbutton/actionlistener

    What errors do you get?
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  3. #3
    nirro is offline Member
    Join Date
    Sep 2013
    Posts
    6
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    Description Resource Path Location Type
    The serializable class Mainp does not declare a static final serialVersionUID field of type long Mainp.java ‪/Gui-test/src‬ line 13 Java Problem
    The import java.awt.event.ActionEvent is never used Mainp.java ‪/Gui-test/src‬ line 8 Java Problem
    The import java.awt.event.ActionListener is never used Mainp.java ‪/Gui-test/src‬ line 7 Java Problem

    can you show me how to add the actionlistener to the button?

    i can see the button but i dont know how to make the button start "creation()"

  4. #4
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: problems with jbutton/actionlistener

    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  5. #5
    nirro is offline Member
    Join Date
    Sep 2013
    Posts
    6
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    wow thats realy useful i have never heard of google before

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,712
    Rep Power
    5

    Default Re: problems with jbutton/actionlistener

    Wow that's really useful, acting like a smart-ass. People will really want to help you now!
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    929
    Rep Power
    2

    Default Re: problems with jbutton/actionlistener

    Quote Originally Posted by nirro View Post
    wow thats realy useful i have never heard of google before
    Wind your neck in. The first hit of that Google result shows an example which you could have copied/pasted. I feel generous today and give it to you: How to Add ActionListener to a JButton in Swing?.

  8. #8
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: problems with jbutton/actionlistener

    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  9. #9
    nirro is offline Member
    Join Date
    Sep 2013
    Posts
    6
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    Quote Originally Posted by SurfMan View Post
    Wind your neck in. The first hit of that Google result shows an example which you could have copied/pasted. I feel generous today and give it to you: How to Add ActionListener to a JButton in Swing?.
    i tried to follow the example but it still doesnt work.

    Java Code:
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.Random;
    import javax.swing.*;
    
    
    public class Mainp extends JFrame 
    {	
    
    private void creation() 
    {
    JFrame frame1 = new JFrame("JAVA");
    ImageIcon image1;
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    image1= new ImageIcon(getClass().getResource("sun_2.png"));
    JLabel label1=new JLabel(image1);
    JButton startbutton = new JButton("Start");
    startbutton.addActionListener(new ActionListener()  
    {
    public void actionPerformed(ActionEvent e) 
    {
    System.out.println("You clicked the button");
    Random rand = new Random();
    float r = rand.nextFloat();
    float g = rand.nextFloat();
    float b = rand.nextFloat();
    Color randomcolor=new Color(r,g,b);
    getContentPane().setBackground(randomcolor); 
    }
    
    }
    );
    frame1.getContentPane().add(startbutton);
    frame1.getContentPane().add(label1);
    frame1.setVisible(true);
    frame1.pack();
    frame1.setTitle("title");
    }
    
    
    public void main(String[] args)
    {
    creation();
    }
    }
    ir says-
    Error: Main method is not static in class Mainp, please define the main method as:
    public static void main(String[] args)

    when i do that it says-
    Description Resource Path Location Type
    Cannot make a static reference to the non-static method creation() from the type Mainp Mainp.java ‪/Gui-test/src‬ line 47 Java Problem

  10. #10
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: problems with jbutton/actionlistener

    Create a new instance of Mainp and call create on that.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  11. #11
    nirro is offline Member
    Join Date
    Sep 2013
    Posts
    6
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    do you mean like this?
    Java Code:
    public static void main(String[] args)
    {
    javax.swing.SwingUtilities.invokeLater(new Runnable() 
    {
    public void run() 
    {
    	creation();
    }
    }
    );
    it still says- Error: Main method is not static in class Mainp, please define the main method as:
    public static void main(String[] args)

  12. #12
    PhHein's Avatar
    PhHein is offline Senior Member
    Join Date
    Apr 2009
    Location
    Germany
    Posts
    1,430
    Rep Power
    7

    Default Re: problems with jbutton/actionlistener

    No. Seriously, get back to the tutorials, your books, whatever you use and read up on the language basics. You're making first week beginner's mistakes here.
    Java Code:
    public void run()
    {
        Mainp mp = new Mainp();
        mp.creation();
    }
    gimbal2 likes this.
    Math problems? Call 1-800-[(10x)(13i)^2]-[sin(xy)/2.362x]
    The Ubiquitous Newbie Tips

  13. #13
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,712
    Rep Power
    5

    Default Re: problems with jbutton/actionlistener

    I call that the "forum thread trap". You have a thread running in a forum and then it becomes too big an attraction to just ask every little thing there in stead of doing the right thing and spending time figuring stuff out yourself. Using Google.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  14. #14
    mstabosz is offline Member
    Join Date
    Sep 2013
    Posts
    2
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    Quote Originally Posted by gimbal2 View Post
    I call that the "forum thread trap". You have a thread running in a forum and then it becomes too big an attraction to just ask every little thing there in stead of doing the right thing and spending time figuring stuff out yourself. Using Google.
    I like that. Now I'm no expert on Java. I'm just a student myself, but I pick stuff up pretty quickly and am usually pretty slow to ask questions. Even then I only do so after a lot of hesitation and effort.

    Anyway, to the original poster: I think you're missing something fundamental about listeners.


    1. You need to define a separate class to make a listener work. You call this class whatever you want. I usually go with something related to the type of GUI element it's supposed to handle. HandleButtonClicks for buttons, HandleCheckBoxes for check boxes, HandleSliders for slider bars etc.,

    2. The class must implement a listener interface, using the implements keyword. There are a few different listener interfaces, ItemListener and ActionListener are the ones I know off the top of my head. I think there are other ones for mouse and keyboard events. You'll need to do your own research to figure out what you need for a given situation. That's what I think is one of the keys to programming: you don't need to know the particulars off the top of your head, but you need to know how to find them.

    3. The listener class MUST use the function public void actionPerformed(ActionEvent e). This function is invoked whenever you interact with the item to which you register the listener (i.e. click a button, check a check box, move a slider bar etc.,) You can add additional functions if you like. Just like your primary class. I usually keep the body of my actionPerformed function simple. It usually contains if or switch statements and function calls and not much else. I like to pass off the heavy load to special functions.

    4. You have to invoke the addActionListener method on each GUI element you want tied to this listener. As the documentation for addActionListener states, you have to pass an instance of a listener object. You can do this with an explicitly named instance or pass it anonymously. So like if I had a "Submit" button named jbtSubmit, and a listener class named "HandleButtonClicks", I could do it explicitly:

    Java Code:
    HandleButtonClicks myListener = new HandleButtonClicks();
    jbtSubmit.addActionListener(myListener);
    or anonymously

    Java Code:
    jbtSubmit.addActionListener(new HandleButtonClicks());
    Then, any time you click the submit button, the statements inside the "actionPerformed" method of the "HandleButtonClicks" class are executed.

    There are a lot of problems with your code, but I wanted to give you a broad breakdown of how event driven programming works.

  15. #15
    mstabosz is offline Member
    Join Date
    Sep 2013
    Posts
    2
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    Quote Originally Posted by PhHein View Post
    No. Seriously, get back to the tutorials, your books, whatever you use and read up on the language basics. You're making first week beginner's mistakes here.
    Java Code:
    public void run()
    {
        Mainp mp = new Mainp();
        mp.creation();
    }
    Isn't public void run() the mandatory function you use when invoking the Runnable interface for a Task class when Multithreading? I've only read on Multithreading; didn't get around to writing anything with it yet. I just ask because I found the original poster's choice of function name incredibly odd.

  16. #16
    nirro is offline Member
    Join Date
    Sep 2013
    Posts
    6
    Rep Power
    0

    Default Re: problems with jbutton/actionlistener

    it works now..
    if you want to see here you go
    Java Code:
    package backgroundchanger;
    import java.util.Random;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class ButtonSettingBackground extends JPanel implements ActionListener 
    {
    private JButton yellowButton = new JButton("Press me");
    
    public ButtonSettingBackground() 
    {
    add(yellowButton);
    yellowButton.addActionListener(this);
    }
    
    public void actionPerformed(ActionEvent evt) {
    Random rand = new Random();
    float r = rand.nextFloat();
    float g = rand.nextFloat();
    float b = rand.nextFloat();
    Color randomcolor=new Color(r,g,b);
    setBackground(randomcolor);
    repaint();
    }
    
    public static void main(String[] args) {
    JFrame frame = new JFrame("ButtonTest");
    frame.setSize(500, 500);
    frame.addWindowListener(new WindowAdapter() 
    {
    public void windowClosing(WindowEvent e) 
    {
    System.exit(0);
    }
    }
    );
    Container contentPane = frame.getContentPane();
    contentPane.add(new ButtonSettingBackground());
    frame.show();
    }
    }

Similar Threads

  1. ActionListener for JButton after changing Button to JButton
    By ravi.joshi53 in forum Java Applets
    Replies: 2
    Last Post: 10-07-2011, 07:35 AM
  2. Replies: 2
    Last Post: 09-05-2011, 12:38 AM
  3. Multiple JButton/ActionListener problem
    By graympa in forum New To Java
    Replies: 3
    Last Post: 04-04-2011, 12:48 AM
  4. JButton ActionListener problems
    By Fortu in forum New To Java
    Replies: 6
    Last Post: 02-05-2011, 04:20 PM
  5. JButton actionlistener not working, very strange
    By alacn in forum New To Java
    Replies: 4
    Last Post: 08-05-2010, 02:25 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •