我有一个Jbutton,当按下时创建另一个按钮并将新按钮添加到面板。如何添加一个actionListener到新的按钮?添加动作到由另一个JButton创建的JButton
例如:
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,我该怎么办呢?
编辑的代码:
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");
}
}
的代码是没有得到很好的组织,但是这或多或少是我想做的事情
不,你的'aListener'类必须实现'ActionListnere',因为你正在做'addActionListener(...)'或者你写'newButton [click - 1] .addMouseListener(new aListener());'使它工作。 – 2012-03-22 15:50:54
啊的确如此。你在调用addActionListener,但它应该是addMouseListener在需要aListener类的按钮上,或者你可以让类实现ActionListener而不是扩展MouseAdapter,但是你需要改变方法public void actionPerformed(ActionEvent e)的鼠标点击 – 2012-03-22 16:00:14
为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。但简单来说:1)应用程序资源通常只能通过URL访问,而接受'String'的'ImageICon'构造函数将其解释为'File'路径。 2)看起来这个GUI的整个逻辑是可疑的。它打算实现什么? 3)布局更有可能兑现组件的首选尺寸,而不是尺寸。但要小心谨慎地设置首选大小,这不是轻言放弃。 4)添加一个'ActionListener'而不是'MouseListener'到按钮。 – 2012-03-22 16:04:22