[英]Issue with button icons, Java 8-Queens puzzle
The problem I am running into is this: I have a grid of buttons in a JPanel, these buttons are supposed to change to an image of a queen when I click them. 我遇到的问题是:在JPanel中有一个按钮网格,当我单击它们时,这些按钮应该变为皇后图像。 The code looks like this:
代码如下:
private Component createButtonBlack() {
final JButton button = new BoardButton();
final ImageIcon queen = new ImageIcon("/images/queen.png");
button.setBackground(Color.BLACK);
button.setPreferredSize(new Dimension(40, 40));
class QueenClick implements ActionListener {
public void actionPerformed(ActionEvent event) {
button.setIcon(queen);
button.repaint();
}
} // end QueenClick
ActionListener queenClicker = new QueenClick();
button.addActionListener(queenClicker);
return button;
} // end createButtonBlack
The problem (image not appearing) occurs on both the methods for creating black and white buttons but the methods are the same except for the color. 在创建黑色和白色按钮的两种方法上均出现问题(未出现图像),但是除了颜色之外,其他方法相同。 Ideally I would like to be able to un-click the buttons and the image disappears but I do not know how to do that.
理想情况下,我希望能够取消单击按钮,图像消失,但是我不知道该怎么做。
I am having difficulty with other parts of my 8queens GUI based problem so if you have any suggestions let me know! 我在基于8queens GUI的问题的其他部分遇到困难,因此,如果您有任何建议,请告诉我!
Also if you need more code I will certainly supply it. 另外,如果您需要更多代码,我一定会提供。 Thank you.
谢谢。
State the exact problem when asking a question. 提出问题时请陈述确切的问题。
These buttons are supposed to change to an image of a queen when I click them.
当我单击它们时,这些按钮应该更改为女王的图像。
So I'm guessing the icon doesn't change? 所以我猜图标不会改变吗?
Did you: 你是否:
You can easily add a System.out.println(...) to verify both of the above. 您可以轻松地添加System.out.println(...)来验证上述两项。
final ImageIcon queen = new ImageIcon("/images/queen.png");
I'm guessing the problem is the leading "/" in the path. 我猜问题出在路径中的前导“ /”。 The "/" tells the file system to look at the root of the drive.
“ /”告诉文件系统查看驱动器的根目录。
if you have any suggestions let me know!
如果您有任何建议,请告诉我!
There is no need to create two methods. 无需创建两个方法。 You can just do:
您可以这样做:
Component button = createButton();
button.setBackground( Color.BLACK );
There is no need to create individual ActionListeners. 无需创建单独的ActionListeners。 You can create a single generic listener with code like:
您可以使用以下代码创建单个通用侦听器:
ActionListener queenClicker = new ActionListener()
{
@Override
public void actionPerformed(Action Event e)
{
JButton button = (JButton)e.getSource();
button.setIcon( queen );
//button.repaint(); // not needed the setIcon method will do the repaint()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.