actionlistener problem

Hello all !

First at all, im french, so sorry if my english looks bad.

I have a little problem…

I wan tto make my “main” with play and quit buttons, but, my frame juste show the last one i said to show.

If i code first buttons and background after, it show only the backgound, and vice versa.

here’s my code:

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


public class fenetre {
    JFrame fenetre ;
    JButton jbPlay;
    JButton jbClose;
    JLabel label;
    
    
//***********french noy=tes.. :D*************

public fenetre(String titre) {                 //création de la méthode constructeur
fenetre = new JFrame(titre);                   //création de la Jframe
Container contenu = fenetre.getContentPane();  //création du conteneur


// ***************************************************************************************
// French notes again :P 


JPanel Button = new JPanel();                  // ceci pour contenir les boutons Jouer et Quitter
JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

       


Button.add(jbPlay);                              //ajout des boutons au panel
jbPlay.setFocusPainted(false);
jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
jbPlay.setContentAreaFilled(false);
        


Button.add(jbClose);
jbClose.setFocusPainted(false);
jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
jbClose.setContentAreaFilled(false);
        

contenu.setLayout(new BorderLayout());
JLabel label = new JLabel();
Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
label.setIcon(new ImageIcon(image));
contenu.add(label,BorderLayout.CENTER);
contenu.add(Button,BorderLayout.CENTER);

// *****************************caractéristiques de la fenetre*********************************

fenetre.setSize(600,500);
fenetre.setVisible(true);
fenetre.pack();
fenetre.setResizable(false);
fenetre.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }}

you put both components in the same location:

contenu.add(label,BorderLayout.CENTER);
contenu.add(Button,BorderLayout.CENTER);

try this:

contenu.add(label,BorderLayout.NORTH);
contenu.add(Button,BorderLayout.SOUTH);

Hum… Thanks but that’s not the problem, I want them on the background, not under… because i want to place buttons in a precise location where it’s empty in my background
here is an exemple :

http://img257.imageshack.us/img257/5896/hereqs.png

You should set Button’s layout manager to null and call setBounds on the buttons yourself.

If it is to only have a main screen menu, you should not bother yourself with component and layout. Display your image and deal with the mouse even yourself.

Try this:


JPanel p = new JPanel();
p.setLayout(new GridLayout(2,1));
p.add(label);
p.add(Button);
contenu.add(p,BorderLayout.CENTER);

I think Bonbon-Chan offers the simpler solution.

Don’t bother with buttons at all, add a mouse-listener to the label and capture click-X,Y.
If they fall into the area your buttons would be, call whatever fuction your buttons’ actionlisteners would have called anyway.
All you need do is add the existence of the buttons (sensitive areas) in the label image.

If you want it to look like Swing, why reinvent the wheel? It takes a while to implement full button functionality. Might as well use Swing if it works for you.

Hum, ok, thank you, so, I just have to make my background and to place mouse listener in xy position? Woaw, so simple o_O

What is the name of the method for make a mouse listener in xy position ?

Because I found this:"ActionEvent(Object source, int id, String command) "
but I can’t choose the xy position…

Thanks you very much

Greetings from little french guy :slight_smile:


class FenetreLabel extends JLabel implements MouseListener {
	private FenetreFrame myOwner = null;
	public FenetreLabel(FenetreFrame frameowner) { myOwner = frameowner; }
	//MouseListener methods
	public void mouseClicked(MouseEvent me) { ; } //Invoked when the mouse button has been clicked (pressed and released) on a component.
 	public void mouseEntered(MouseEvent me) { ; } //Invoked when the mouse enters a component.
 	public void mouseExited(MouseEvent me) { ; } //Invoked when the mouse exits a component.
 	public void mousePressed(MouseEvent me) { ; } //Invoked when a mouse button has been pressed on a component.
 	public void mouseReleased(MouseEvent me) { //Invoked when a mouse button has been released on a component.
 		int sensitiveareaLeftX = 100,sensitiveareaRightX = 200,sensitiveareaTopY = 150,sensitiveareaBottomY = 50;
 		if (me.getButton() == MouseEvent.BUTTON1) { //Capture left mouse button only
 			if ((me.getX() >= sensitiveareaLeftX)&&(me.getX() <= sensitiveareaRightX)&&
 				(me.getY() >= sensitiveareaBottomY)&&(me.getY() >= sensitiveareaTopY)) {
 					//release was inside sensitive area
 					//do whatever needs doing
 					if (myOwner != null) { myOwner.sensitive_area_was_clicked(); }
 			} // else {} the other sensitive areas...
 		}
 	}
}

Then you instantiate this new class instead:


FenetreLabel label = new FenetreLabel (this);
Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
label.setIcon(new ImageIcon(image));

and somewhere in the frame you implement the called method:


public void sensitive_area_was_clicked() { System.out.println("Sensitive area!"); }//do whatever needs doing

That’s simpler?!

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

public class fenetre {
	JFrame fenetre ;
	JButton jbPlay;
	JButton jbClose;
	JLabel label;
    
    //***********french noy=tes.. :D*************

	public Demo(String titre) {                 //création de la méthode constructeur
		fenetre = new JFrame(titre);                   //création de la Jframe
		Container contenu = fenetre.getContentPane();  //création du conteneur

		// ***************************************************************************************
		// French notes again :P 

		JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
		JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

		jbPlay.setFocusPainted(false);
		jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
		jbPlay.setContentAreaFilled(false);

		jbClose.setFocusPainted(false);
		jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
		jbClose.setContentAreaFilled(false);

		contenu.setLayout(null);
		JLabel label = new JLabel();
		Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
		label.setIcon(new ImageIcon(image));

		contenu.add(jbPlay, 0);
		contenu.add(jbClose, 1);
		contenu.add(label, 2);
		label.setBounds(0, 0, 600, 500);
		jbPlay.setBounds(50, 200, 200, 50);
		jbClose.setBounds(50, 300, 200, 50);

		// *****************************caractéristiques de la fenetre*********************************

		fenetre.setSize(600,500);
		fenetre.setResizable(false);
		fenetre.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		fenetre.setVisible(true);
	}
}

Or as a patch against the original code:

23d22
< JPanel Button = new JPanel();                  // ceci pour contenir les boutons Jouer et Quitter
30d28
< Button.add(jbPlay);                              //ajout des boutons au panel
37d34
< Button.add(jbClose);
43c40
< contenu.setLayout(new BorderLayout());
---
> contenu.setLayout(null);
47,48c44,50
< contenu.add(label,BorderLayout.CENTER);
< contenu.add(Button,BorderLayout.CENTER);
---
>
> contenu.add(jbPlay, 0);
> contenu.add(jbClose, 1);
> contenu.add(label, 2);
> label.setBounds(0, 0, 600, 500);
> jbPlay.setBounds(50, 200, 200, 50);
> jbClose.setBounds(50, 300, 200, 50);
53,54d54
< fenetre.setVisible(true);
< fenetre.pack();
56a57
> fenetre.setVisible(true);

Keeping the buttons separate like this has the major advantage of allowing you to move them if you decide that they’re 3 pixels too far left without having to recreate your background image. (Minor saving in hassle if you do everything yourself; major saving if you’re working with an artist).

I just find it shocking that everybody says '‘oh, just roll your own’ when it’s obvious that he doesn’t have a lot of experience.

He did write:
contenu.add(label,BorderLayout.CENTER); contenu.add(Button,BorderLayout.CENTER);

So Swing is probably new to him. Let him figure out Swing first, don’t immediately think that if something is easy/easier for you, it’s the best thing to suggest to a newless clubbie.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;

public class fenetre  {
	JFrame fenetre ;
	JButton jbPlay;
	JButton jbClose;
	JLabel label; 
    
    //***********french notes.. :D*************

	public fenetre (String titre) {                 //création de la méthode constructeur
		fenetre = new JFrame(titre);                   //création de la Jframe
		Container contenu = fenetre.getContentPane();  //création du conteneur

		// ***************************************************************************************
		// French notes again :P 

		JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
		JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

		jbPlay.setFocusPainted(false);
		jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
		jbPlay.setContentAreaFilled(false);

		jbClose.setFocusPainted(false);
		jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
		jbClose.setContentAreaFilled(false);
jbClose.addActionListener(null);
		contenu.setLayout(null);
		JLabel label = new JLabel();
		Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
		label.setIcon(new ImageIcon(image));

		contenu.add(jbPlay, 0);
		contenu.add(jbClose, 1);
		contenu.add(label, 2);
		label.setBounds(0, 0, 900, 800);
		jbPlay.setBounds(50, 445, 850, 78);
		jbClose.setBounds(50, 640, 158, 50);
 
		    ;
		    
		// *****************************caractéristiques de la fenetre*********************************

		fenetre.setSize(907,832);
		fenetre.setResizable(false);
		fenetre.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		fenetre.setVisible(true);}}

It work, but when i implement action listener it bug…

I tried all for place actionlisteners in my buttons, but eclipse say me he can’t do it -__-’

Usually you’d do action listeners with buttons like this:


private JButton button1;
private JButton button2;

public void somewhere()
{
    button1 = new JButton("Button 1");
    button2 = new JButton("Button 2");

    add(button1);
    add(button2);

    ActionListener listener = new ButtonHandler();
    button1.addActionListener(listener);
    button2.addActionListener(listener);
}

private class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        Object o = e.getSource();

        if (o == button1)
        {
            doButton1();
        }
        else if (o == button2)
        {
            doButton2();
        }
    }
}

Also note that if you’re constantly requesting focus in a panel somewhere that can sometimes make buttons unclickable (depending on OS).

wow, when i laucn this code :

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class ButtonHandler  extends fenetre implements ActionListener {

	public ButtonHandler() {
		super("test");
		// TODO Auto-generated constructor stub
	}

	@Override
	public void actionPerformed(ActionEvent e) {
	    
	        Object t = e.getSource();

	        if (t == jbPlay)
	        {
	            game();
	        }
	        else if (t == jbClose)
	        {
	            
	        }
	    }

	private void game() {
		System.out.print("test reussi");
		
	}
	}                             

and this code:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;

public class fenetre  {
	JFrame fenetre ;
	JButton jbPlay;
	JButton jbClose;
	JLabel label; 
    
    //***********french notes.. :D*************

	public fenetre (String titre) {                 //création de la méthode constructeur
		fenetre = new JFrame(titre);                   //création de la Jframe
		Container contenu = fenetre.getContentPane();  //création du conteneur

		// ***************************************************************************************
		// French notes again :P 

		JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
		JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

		jbPlay.setFocusPainted(false);
		jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
		jbPlay.setContentAreaFilled(false);

		jbClose.setFocusPainted(false);
		jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
		jbClose.setContentAreaFilled(false);
jbClose.addActionListener(null);
		contenu.setLayout(null);
		JLabel label = new JLabel();
		Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
		label.setIcon(new ImageIcon(image));

		contenu.add(jbPlay, 0);
		contenu.add(jbClose, 1);
		contenu.add(label, 2);
		label.setBounds(0, 0, 900, 800);
		jbPlay.setBounds(50, 445, 850, 78);
		jbClose.setBounds(50, 640, 158, 50);
		
		  ActionListener listener = new ButtonHandler();
		    jbPlay.addActionListener(listener);
		    jbClose.addActionListener(listener);
 
		    ;
		    
		// *****************************caractéristiques de la fenetre*********************************

		fenetre.setSize(907,832);
		fenetre.setResizable(false);
		fenetre.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		fenetre.setVisible(true);}}

eclipse say me :
Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space
Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space
Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space
Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space
Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space
Exception in thread “Image Fetcher 0” java.lang.OutOfMemoryError: Java heap space

I dont understand :confused:

ButtonHandler extends fenetre, which means that when you make a ButtonHandler it makes two ButtonHandlers, each of which makes two more, and so you run out of memory.

Change “ButtonHandler extends fenetre” to “ButtonHandler”.

yeah, but I made it because if I delete extends fenetre, jbPlay and jbClose aren’t recognized…

So I tried this but it bug:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;

public class fenetre  {
	JFrame fenetre ;
	JButton jbPlay;
	JButton jbClose;
	JLabel label; 
    
    //***********french notes.. :D*************

	public fenetre (String titre) {                 //création de la méthode constructeur
		fenetre = new JFrame(titre);                   //création de la Jframe
		Container contenu = fenetre.getContentPane();  //création du conteneur

		// ***************************************************************************************
		// French notes again :P 

		JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
		JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

		jbPlay.setFocusPainted(false);
		jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
		jbPlay.setContentAreaFilled(false);

		jbClose.setFocusPainted(false);
		jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
		jbClose.setContentAreaFilled(false);
jbClose.addActionListener(null);
		contenu.setLayout(null);
		JLabel label = new JLabel();
		Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
		label.setIcon(new ImageIcon(image));

		contenu.add(jbPlay, 0);
		contenu.add(jbClose, 1);
		contenu.add(label, 2);
		label.setBounds(0, 0, 900, 800);
		jbPlay.setBounds(50, 445, 850, 78);
		jbClose.setBounds(50, 640, 158, 50);
		
	 ButtonHandler();
		    ;
		    
		// *****************************caractéristiques de la fenetre*********************************

		fenetre.setSize(907,832);
		fenetre.setResizable(false);
		fenetre.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		fenetre.setVisible(true);}

public void ButtonHandler() {
	
	// TODO Auto-generated constructor stub
}
jbPlay.addActionListener(listener);
jbClose.addActionListener(listener);
public void actionPerformed(ActionEvent e) {
    
        Object t = e.getSource();

        if (t == jbPlay)
        {
            game();
        }
        else if (t == jbClose)
        {
         System.out.print("failure");  
        }
    }

private void game() {
	System.out.print("test reussi");
	
}
}    

error console:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	ButtonHandler cannot be resolved to a type

	at fenetre.<init>(fenetre.java:45)
	at main.main(main.java:12)

sorry to make you waste your time, but it dont work !! :-\

I dont know hot to make button listener without these (merdiques!) errors

Are you using an IDE? Try Eclipse or Netbeans.

lol yeah, I’m using eclipse ::slight_smile:

So I’ll try to understand why it bug… But its hard


 import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;

public class fenetre  {
	JFrame fenetre ;
	JButton jbPlay;
	JButton jbClose;
	JLabel label; 
    
    //***********french notes.. :D*************

	public fenetre (String titre) {                 //création de la méthode constructeur
		fenetre = new JFrame(titre);                   //création de la Jframe
		Container contenu = fenetre.getContentPane();  //création du conteneur

		// ***************************************************************************************
		// French notes again :P 

		JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
		JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

		jbPlay.setFocusPainted(false);
		jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
		jbPlay.setContentAreaFilled(false);

		jbClose.setFocusPainted(false);
		jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
		jbClose.setContentAreaFilled(false);
jbClose.addActionListener(null);
		contenu.setLayout(null);
		JLabel label = new JLabel();
		Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
		label.setIcon(new ImageIcon(image));

		contenu.add(jbPlay, 0);
		contenu.add(jbClose, 1);
		contenu.add(label, 2);
		label.setBounds(0, 0, 900, 800);
		jbPlay.setBounds(50, 445, 850, 78);
		jbClose.setBounds(50, 640, 158, 50);
		jbPlay.addActionListener(new game(this));      // errors here
        jbClose.addActionListener(new game(this));           // and here
	
		    ;
		    
		// *****************************caractéristiques de la fenetre*********************************

		fenetre.setSize(907,832);
		fenetre.setResizable(false);
		fenetre.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		fenetre.setVisible(true);}





public void actionPerformed(ActionEvent e) {
    
        Object t = e.getSource();

        if (t == jbPlay)
        {
            game();
        }
        else if (t == jbClose)
        {
         System.out.print("failure");  
        }}
    

private void game() {
	System.out.print("test reussi");
	
}
}                              

You can tell your class to be an actionlistener:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import javax.swing.*;

public class Fenetre  extends JFrame implements ActionListener {
	JButton jbPlay;
	JButton jbClose;
	JLabel label; 
    
    //***********french notes.. :D*************

	public Fenetre (String titre) {                 //création de la méthode constructeur
		setTitle (titre);
		Container contenu = getContentPane();

		JButton jbPlay = new JButton("", new ImageIcon("jouer.gif"));
		JButton jbClose = new JButton("", new ImageIcon("exit.gif"));

		jbPlay.setFocusPainted(false);
		jbPlay.setBorderPainted(false);                  // ces trois lignes enelvent la bordure du boutton
		jbPlay.setContentAreaFilled(false);

		jbClose.setFocusPainted(false);
		jbClose.setBorderPainted(false);               // ces trois lignes sont les meme que la haut :)
		jbClose.setContentAreaFilled(false);

		contenu.setLayout(null);
		JLabel label = new JLabel();
		Image image = Toolkit.getDefaultToolkit().createImage("background.gif");// nouveau JLabel backgound
		label.setIcon(new ImageIcon(image));

		contenu.add(jbPlay, 0);
		contenu.add(jbClose, 1);
		contenu.add(label, 2);
		label.setBounds(0, 0, 900, 800);
		jbPlay.setBounds(50, 445, 850, 78);
		jbClose.setBounds(50, 640, 158, 50);
		jbPlay.addActionListener(this);      // errors here
        jbClose.addActionListener(this);           // and here
	
		setSize(907,832);
		setResizable(false);
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setVisible(true);
	}

	public void actionPerformed(ActionEvent e) {
		Object t = e.getSource();

        if (t == jbPlay) {
            game();
        } else if (t == jbClose) {
         System.out.print("failure");  
        }
	}
    

	private void game() {
		System.out.print("test reussi");
	}
}