I am trying to put an icon in the JButton with one of the constructors of the JButton class. When I execute this project, the three buttons do not appear, but when I use a constructor without an icon, the three buttons are displayed. I do not know why it does not work, I do not know if it's something I'm doing wrong or just on my computer does not work. I leave the code below.
package graficos;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class PruebaAcciones {
public static void main(String[] args) {
// TODO Auto-generated method stub
MarcoAcciones mimarco = new MarcoAcciones();
mimarco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MarcoAcciones extends JFrame {
public MarcoAcciones() {
setVisible(true);
setBounds(300,100,600,300);
add(new PanelAccion());
}
}
class PanelAccion extends JPanel {
public PanelAccion() {
AccionColor accionAmarillo = new AccionColor("Amarillo", new ImageIcon("src/graficos/iconoAmarillo"), Color.YELLOW);
AccionColor accionAzul = new AccionColor("Azul", new ImageIcon("src/graficos/iconoAzul"), Color.BLUE);
AccionColor accionRojo = new AccionColor("Rojo", new ImageIcon("src/graficos/iconoRojo"), Color.RED);
add(new JButton(accionAmarillo));
add(new JButton(accionAzul));
add(new JButton(accionRojo));
/*JButton botonAmarillo = new JButton("Amarillo");
JButton botonAzul = new JButton("Azul");
JButton botonRojo = new JButton("Rojo");
add(botonAmarillo);
add(botonAzul);
add(botonRojo);*/
}
/* Se pasó esta clase como interna de PanelAccion ya que se nesecita usar, dentro
* de esta clase, el método setBackground() que pertenece a la clase JPanel,
* no a AbstractAction ni a la interfaz Action, así podemos usar ese método
* (setBackground) aún sin heredar de JPanel */
private class AccionColor extends AbstractAction { //Es la clase adaptadora de la interface Action
public AccionColor(String nombre, Icon icono, Color colorBoton) {
//Mandando información a traves del objeto de tipo Action
putValue(Action.NAME, nombre);
putValue(Action.SMALL_ICON, icono);
putValue(Action.SHORT_DESCRIPTION, "Poner la lámina de color " + colorBoton);
putValue("colorDeFondo", colorBoton);
}
public AccionColor(String nombre, Color colorBoton) {
//Mandando información a traves del objeto de tipo Action
putValue(Action.NAME, nombre);
putValue(Action.SHORT_DESCRIPTION, "Poner la lámina de color " + colorBoton);
putValue("colorDeFondo", colorBoton);
}
@Override
public void actionPerformed(ActionEvent e) {
Color c = (Color) getValue("colorDeFondo"); //Se hace un casting ya que getValue devuelve string
setBackground(c);
System.out.println("Nombre: " + getValue(Action.NAME) + " Descripción: " + getValue(Action.SHORT_DESCRIPTION));
}
}
}