The following program tries to change the color of the window by pressing a button, whose name is the color to which the window will be changed. The code does not throw an error but it does not change the color of the panel. The idea is that you do not have to nest the ColorClass class to any other.
package graficos;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
public class PruebaEventos {
public static void main(String[] args) {
// TODO Auto-generated method stub
MarcoBotones ventana =new MarcoBotones();
ventana.setVisible(true);
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MarcoBotones extends JFrame{
public MarcoBotones(){
setTitle("Botones y eventos");
setBounds(550,150,500,500);
LaminaBotones milamina=new LaminaBotones();
add(milamina);
}
}
class LaminaBotones extends JPanel {
JButton botonAzul= new JButton("azul");
JButton botonAmarillo=new JButton("amarillo");
JButton botonRojo= new JButton("rojo");
public LaminaBotones(){
add(botonAzul);
add(botonAmarillo);
add(botonRojo);
ColorFondo Amarillo=new ColorFondo(Color.YELLOW);
ColorFondo Azul=new ColorFondo(Color.blue);
ColorFondo Rojo=new ColorFondo(Color.red);
botonAzul.addActionListener(Azul);
botonAmarillo.addActionListener(Amarillo);
botonRojo.addActionListener(Rojo);
}
}
class ColorFondo extends JPanel implements ActionListener{
public ColorFondo(Color c ){
colorDeFondo=c;
}
public void actionPerformed(ActionEvent e){
setBackground(colorDeFondo);
revalidate();
System.out.println("apreto el boton");
}
private Color colorDeFondo;
}