无法为 JRadioButton 创建和设置图标

问题描述

代码运行良好。但我无法为 Icon 设置 JRadioButton。我的猜测是它是一个 png 文件大小问题。但我已经选择了一个 250 像素 * 250 像素的 png 文件

如果这还不够小,请告诉我哪个网站可以获得免费的小 PNG 图标?

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

public class MyFrame extends JFrame implements ActionListener {
    JRadioButton pizzaButton;
    JRadioButton hamburgerButton;
    JRadioButton hotdogButton;
    ImageIcon pizzaIcon;
    ImageIcon hamburgerIcon;
    ImageIcon hotdogIcon;

    public MyFrame() {
        this.setLayout(new FlowLayout());
        this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);

        pizzaButton = new JRadioButton("Pizza");
        hamburgerButton = new JRadioButton("Hamburger");
        hotdogButton = new JRadioButton("Hotdog");
        pizzaIcon = new ImageIcon("pizza.png");
        hotdogIcon = new ImageIcon("hotdog.png");
        hamburgerIcon = new ImageIcon("hamburger.png");

        //pizzaButton.setIcon(pizzaIcon);
        hamburgerButton.setIcon(hamburgerIcon);
        //hotdogButton.setIcon(hotdogIcon);

///https://docs.oracle.com/javase/tutorial/uiswing/components/buttongroup.html
        //The ButtonGroup component manages the selected/unselected state for a set of buttons.
        // For the group,// the ButtonGroup instance guarantees that only one button can be selected at a time.
        //Initially,all buttons managed by a ButtonGroup instance are unselected.
        ButtonGroup group = new ButtonGroup();
        group.add(pizzaButton);
        group.add(hamburgerButton);
        group.add(hotdogButton);

        pizzaButton.addActionListener(this);
        hamburgerButton.addActionListener(this);
        hotdogButton.addActionListener(this);

        this.add(pizzaButton);
        this.add(hamburgerButton);
        this.add(hotdogButton);

        this.pack();
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == pizzaButton) {System.out.println("You have choose pizza.");}
        else if (e.getSource() == hamburgerButton) {System.out.println("You have choose Hamburger.");}
        else {System.out.println("You have choose hotdog. Good for you.");}


    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)