简体   繁体   English

如何从其他类制作的按钮对象中获取源代码

[英]How to getSource from a button object made from other class'

i am making a memory game using java swing.我正在使用 java swing 制作一个记忆游戏。 so far i have made a class that returns custom JButtons with an image already in them (unfliped).到目前为止,我已经创建了一个返回自定义 JButton 的类,其中已经有一个图像(未翻转)。 in the main class i am creating objects of that class and add them to the panel.在主类中,我正在创建该类的对象并将它们添加到面板中。 everything works but when i am adding the action listeners the getSource method returns a JButton and as a result i cant use the methods from inside the custom buttons class.一切正常,但是当我添加动作侦听器时,getSource 方法返回一个 JButton,因此我无法使用自定义按钮类中的方法。 How can i use getSource and create a button from the custom buttons class?如何使用 getSource 并从自定义按钮类创建按钮?

i have tried casting the button returned from the getSource method to Buttons(custom buttons class) but it didnt work.我曾尝试将从 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;
   }
}

in the main class i am using:在我使用的主类中:

    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");}

action listener works but since btn is a JButton it wont let me use the getId method of the Buttons class.动作侦听器有效,但由于 btn 是 JButton,它不会让我使用 Buttons 类的 getId 方法。

Why do you want your Buttons instance to have a separate button as an attribute?为什么你希望你的 Buttons 实例有一个单独的按钮作为属性? You already ARE a button.你已经是一个按钮。 This seems like a poor design choice.这似乎是一个糟糕的设计选择。

That said, since you set the button name to be the creation index,you could just use source.getName() and convert it back to an int, then use that int as an index for the jb array.也就是说,由于您将按钮名称设置为创建索引,您只需使用source.getName()并将其转换回 int,然后使用该 int 作为 jb 数组的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM