【发布时间】:2019-04-20 18:09:54
【问题描述】:
我正在使用 java swing 制作一个记忆游戏。到目前为止,我已经创建了一个返回自定义 JButtons 的类,其中已经包含图像(未翻转)。在主类中,我正在创建该类的对象并将它们添加到面板中。一切正常,但是当我添加动作侦听器时,getSource 方法返回一个 JButton,因此我无法使用自定义按钮类内部的方法。如何使用 getSource 并从自定义按钮类创建一个按钮?
我尝试将 getSource 方法返回的按钮转换为 Buttons(自定义按钮类),但没有成功。
public class Buttons extends JButton{
int id;
JButton butt;
private static int x=0;
public Buttons() throws IOException{
butt=this.retButton();
}
public JButton retButton() throws IOException{
BufferedImage img =
ImageIO.read(getClass().getResourceAsStream("/folder/flipped.png"));
ImageIcon image = new ImageIcon(img);
JButton button = new JButton();
button.setName(Integer.toString(x));
button.setIcon(image);
button.setBackground(Color.white);
x+=1;
return button;
}
public JButton getButton(){
return this.butt;
}
public int getId() {
return id;
}
}
在我正在使用的主类中:
for (int i=0; i<12; i++){
jb[i] = new Buttons();
jb[i].getButton().addActionListener(this);
jb[i].setId(cardNums.get(i));
panel.add(jb[i].getButton());
}
frame.add(panel, BorderLayout.CENTER);
frame.pack();
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
System.out.println("hey");}
动作监听器有效,但由于 btn 是一个 JButton,它不会让我使用 Buttons 类的 getId 方法。
【问题讨论】:
标签: java swing actionlistener