gpt4 book ai didi

java - 向由另一个 JButton 创建的 JButton 添加操作

转载 作者:行者123 更新时间:2023-11-29 07:15:33 24 4
gpt4 key购买 nike

我有一个 Jbutton,当按下它时会创建另一个按钮并将新按钮添加到面板中。如何向新按钮添加 actionListener?

例如:

JButton button = new JButton("lala");
button.addActionListener(this);

public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button)
{
JButton newButton = new JButton("ahah");
newButton.addActionListener(this);
}
}

我想给 newButton 添加 Action ,我该怎么做?

编辑代码:

 public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button)
{
String name = tfOne.getText();
Icon flag = new ImageIcon("flag/"+name+".png");
JButton[] newButton = new JButton[click];
newButton[click-1] = new JButton(name, flag);
p2.add(newButton[click-1]);
newButton[click-1].addActionListener(new aListener());
p2.setLayout(new GridLayout(5+click,1)); //p2 is a panel that has been created
setSize(500,450+(click*20));

click++; //number of times the button is pressed
}
}

public class aListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
tfOne.setText("lala");
}
}

代码组织得不好,但这或多或少是我想做的

最佳答案

一种方法是拥有一个包含监听器的内部类:

public void actionPerformed(ActionEvent event)
{
if (event.getSource() == button)
{
JButton newButton = new JButton("ahah");
newButton.addMouseListener(new yourListener());
}
}

//add this class as a inner class
public class aListener extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
JButton buttonReference=(JButton)e.getSource(); // you want this since hardcoding the name of the button is bad if you want listeners for more then one button
buttonReference.setText("lala");
}
}

这将创建一个 yourListener 的实例,并在您单击它时将其添加到按钮

关于java - 向由另一个 JButton 创建的 JButton 添加操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9824296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com