1

我正在为此创建按钮,当我单击他时.. 没有发生任何事情...当我单击 btn 时,没有调用函数 btnActionPerformed ...如何使其工作?

private void btButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
    // TODO add your handling code here
    int[] ret = new int[SQL.freetables().size()];
    Iterator<Integer> iterator = SQL.freetables().iterator();
    for (int i = 0; i < ret.length; i++)
    {
    ret[i] = iterator.next().intValue();
    int num=SQL.freetables().size() + 1;
    this.btn = new JButton();
    this.btn.setText("" + ret[i]);
    this.btn.setSize(60,20);
    int x = 100+(80*i);
    this.btn.setLocation(x, 140);
    this.btn.setVisible(true);
    this.add(btn);     
   // }

    }
    this.revalidate();
    this.repaint();
}          

private void btnActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:
    System.out.print("\b Test: " + btn.getText());
} 
4

2 回答 2

3

你必须实现ActionListener接口。这些方法都不匹配我可以看到的所需签名。

http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html

方法是actionPerformed。侦听器必须附加到JButton. 我在您的代码中都没有看到。

您似乎急需Swing 教程

于 2013-09-15T15:00:29.860 回答
3

你需要注册actionPreformed

this.btn.addActionListener(this);

你的代码应该是:

bt.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
       // TODO add your handling code here
       int[] ret = new int[SQL.freetables().size()];
       Iterator<Integer> iterator = SQL.freetables().iterator();
       for (int i = 0; i < ret.length; i++)
       {
          ret[i] = iterator.next().intValue();
          int num=SQL.freetables().size() + 1;
          this.btn = new JButton();
          this.btn.setText("" + ret[i]);
          this.btn.setSize(60,20);
          int x = 100+(80*i);
          this.btn.setLocation(x, 140);
          this.btn.setVisible(true);
          this.add(btn);   
          btn.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) { 
               // TODO add your handling code here:
               System.out.print("\b Test: " + btn.getText());
             } 
          }

          this.revalidate();
          this.repaint();
       }
    }
});
于 2013-09-15T15:01:36.707 回答