JAVA Action执行不起作用

时间:2013-09-15 14:58:51

标签: java swing jframe jbutton buttonclick

我正在为此创建按钮,当我点击他时...没有发生任何事情...当我点击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());
} 

2 个答案:

答案 0 :(得分:3)

您必须实现ActionListener接口。这些方法都不符合我能看到的所需签名。

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

方法是actionPerformed。听众必须附加到JButton。我在你的代码中看不到任何一个。

您似乎迫切需要Swing tutorial

答案 1 :(得分: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();
       }
    }
});