Frage

I'm doing a menu in Java and I'm using images as JButtons. However, when I run the application I can't click on the buttons. Here's the code of a button:

JButton butoEtnies = null;
try {
    butoEtnies = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Etnies.png"))));
} catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
butoEtnies.setContentAreaFilled(false);
butoEtnies.setBorderPainted(false);
butoEtnies.setFocusPainted(false);
butoEtnies.addActionListener(this);

And here is the actionPerformed:

public void actionPerformed(ActionEvent e) {
    String et = null;
    String accio = e.getActionCommand();

    if(accio.equals("Etnies"))
        et = entrarEtnies();
    else
        System.exit(0);
}

Can it be that it doesn't recognise "Etnies" in the actionPerformed method? The problem gets fixed if I use: JButton butoEtnies = new JButton("Etnies"); But then it shows 2 buttons, the one with the image and another one with this text. If I press the one with the text it works but I still can't click the other one.
How can I do it?

War es hilfreich?

Lösung

You have either given it a title, or an image, not both. You should use the

JButton butoEtnies = new JButton("Etnies", /*Here goes the icon*/);

Or you can also try:

JButton butoEtnies = new JButton("Etnies");
butoEtnies.setIcon(/*Here goes the icon*/);

Besides, here's the Java API for JButton

EDIT #2

Next, provides an particular actionlistener for the butoEtnies button, in which you do not need to specify an ID or a title for the getActionCommand

JButton butoEtnies = new JButton (/*path to icon*/);
butoEtnies.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
         //You can code whatever you want here
         System.out.println("butoEtnies clicked");
     }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top