java - 如何让 ImageIcon 显示在 JButton 中?
问题描述
public ImageIcon getIcon(){
return button.getIcon();
}
public void moveTo(Square j){
JButton current = new JButton();
current = button;
button.setIcon(j.getIcon());
button.setIcon(current.getIcon());
}
这就是问题所在。Button 只是一个JButton
没有内容的简单,并且有条件我正在向 Button 添加不同的内容。虽然当我创建移动方法时,它将切换两个按钮的两个图像,但我未能尝试获取ImageIcon
. JButton
它在第一种方法中报告此错误:
Icon cannot be converted to ImageIcon
我该如何解决?
解决方案
您可以通过构造函数添加它:
JButton button = new JButton("text", icon);
更好的方法是创建一个动作并从该动作创建按钮。然后你可以更新动作的图标,它会在任何使用动作的地方更新:按钮、菜单栏、弹出菜单等。
Action action = new AbstractAction("text", icon) {
public void actionPerformed(ActionEvent e) {
}
}
//place the action in an ActionMap
Jbutton button = new JButton(action);
然后,当您需要更新图标时,它就是
getActionMap().get(key).putValue(Action.LARGE_ICON_KEY, icon); //for buttons
getActionMap().get(key).putValue(Action.SMALL_ICON_KEY, icon); //for menus
推荐阅读
- python - 为什么在读取包含大量行的文件时使用多线程这么慢?
- python-3.x - ModuleNotFoundError:烧瓶程序中没有名为“pandas”的模块
- java - 如何在 JAVA 中通知类中的所有线程?
- javascript - document.body.appendChild(form) 复制页面底部的表单
- scala - 将字符串列转换为特定格式的日期
- c# - 如何将 SocketIO 与 C# 客户端连接
- oracle - 如何导出/导入完整的 OracleDB 数据转储?
- java - 从链表中搜索并删除一个节点
- azure - 使用 Azure 数据工厂进行参数化
- python - 如何从数据框中创建序列并将它们放入数组数组或列表中?