[英]How can I get the ImageIcon displayed in a 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 中。 虽然当我创建 move 方法时,它将切换两个按钮的两个图像,但我未能尝试获取JButton
的ImageIcon
。 它在第一种方法中报告此错误:
Icon cannot be converted to ImageIcon
我该如何解决?
Icon 是由 ImageIcon 类实现的接口,因此本质上每个 ImageIcon 都是一个 Icon,因此您可以将 Icon 转换为 imageIcon,如下所示
public ImageIcon getIcon(){
return (ImageIcon)button.getIcon();
/*getIcon() returns Icon and ImageIcon is child
of Icon so you can cast as you cast parent class reference to child class in this
case it is interface acting as parent*/
}
您可以通过构造函数添加它:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.