如果我尝试实现抽象操作接口,为什么 JButton 不会出现在 JFrame 上?

问题描述

我不知道为什么 JButton 没有出现在 JFrame 中。我认为代码没问题,这让我发疯。如果有人知道发生了什么,我将不胜感激。

如果我在代码的注释部分添加一个按钮,它可以完美地工作,但如果我尝试使用 AccionColor 类来制作它,则它不会。可能是我用于 GIF 图像的路线的问题吗?我不这么认为。如果是按钮会出现但没有图像,不是吗?

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.*;

public class EventosMultiplesFuentes {
    public static void main(String[] args) {
        marcoAcciones marco1 = new marcoAcciones();
        marco1.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class marcoAcciones extends JFrame { 
    
    public marcoAcciones(){
        this.setVisible(true); //hay que poner el setVisible aqui o si no no se ven los botones no se por que
        this.setTitle("Multiples fuentes");
        this.setBounds(550,250,600,300);
        
        PanelFuentes capa = new PanelFuentes();
        add(capa);
    }
}

class PanelFuentes extends JPanel{

    public PanelFuentes(){
       AccionColor accionAmarillo = new AccionColor("Amarillo",new ImageIcon("C:/Users/VicLo/Desktop/twitch/bichote pequeño.png"),Color.YELLOW);
//       JButton botonAmarillo = new JButton("Amarillo");
//        JButton botonAzul = new JButton("Azul");
//        JButton botonRojo = new JButton("Rojo");
//        
//       add(botonAmarillo);
//        add(botonAzul);
//        add(botonRoj      

        add(new JButton(accionAmarillo));
    }
}

class AccionColor extends AbstractAction{
    
    public AccionColor(String nombre,Icon icono,Color color_boton){
        putValue(Action.NAME,nombre);
        putValue(Action.SMALL_ICON,icono);
        putValue(Action.SHORT_DESCRIPTION,"Poner la lamina del color " + nombre);
        putValue("Color de fondo",color_boton);
    }

    public void actionPerformed(ActionEvent e) {
    }
}

解决方法

只需在 revalidate(); 末尾的 add(capa); 之后添加 MarcoAcciones()