如何解决无法为 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 举报,一经查实,本站将立刻删除。